Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor 1c00ae3492 security: write the release from the release job only (SonarCloud S8233)
The workflow-level contents: write granted every job the right to push
tags and releases; the reusable release workflow is the only job that
needs it. Workflow level drops to read.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-10-23 17:16:13 -04:00
Dylan M. Taylor c1dd60ffd6 Merge pull request #2018 from dylanmtaylor/ci/sonar-main-not-cancelled
ci(sonar): stop cancelling main-branch runs so coverage is published
2026-10-23 16:58:56 -04:00
Dylan M. Taylor bec28d6b87 ci(sonar): don't cancel superseded runs on main, so coverage is published 2026-10-23 16:50:42 -04:00
aiongg d3e6111cf1 Xrefs and data links: resolve stored paths with craft-docpath's resolve_absolute (#1750)
* Xrefs and data links: use resolve_absolute for stored paths

* CI: check that git dependencies come from storytold

* CI: release only with git dependencies from storytold

* Parse Cargo.lock as TOML when checking git sources

* Use the shared git-sources check in CI

* Parse cargo config, legacy .cargo/config included, in the git-sources check
2026-10-23 16:42:01 -04:00
aiongg dd1f0531ac i18n: missing translations never fail; cargo xtask i18n reports them (#2013) 2026-10-23 15:40:12 -04:00
aiongg 37150774c6 CI: run the gate through craft-common-actions' shared gate.yml; FreeBSD nightly and on release (#1987)
ci.yml is new: it calls the shared workflow (cached apt packages, nextest, main-only cache saves, Cargo.lock check). FreeBSD and Windows ARM64 run nightly and on pushes to release instead of on pull requests. Depends on storytold/craft-common-actions#69.
2026-10-23 13:56:16 -04:00
aiongg 9cf115e808 CI: one test binary per crate, nextest, line tables only (#1989)
* Build: line tables only in dev, no debug info for dependencies

* Tests: one integration-test binary per crate

Each crate's tests/*.rs becomes a module of tests/it/main.rs. Files that
install process-wide state (the file io hooks, user aliases, SAVETIME and
SAVEFILEPATH, user linetype and pattern files, registered fonts) stay their
own test binaries.

* xtask ci: nextest, tests without examples, one wasm check call
2026-10-23 13:34:26 -04:00
aiongg 9d8f16c825 Merge pull request #1991 from marcoarnulfo/fix/harfrust-0.14
Build main again after the #1957 dependency bump
2026-10-23 13:00:16 -04:00
Dylan M. Taylor f043540d13 packaging: use [[ ]] tests, named locals and explicit returns in shell scripts (SonarCloud S7688/S7679/S7682) (#1972)
All flagged scripts run under bash (shebang or '# shellcheck shell=bash'), so
[[ ]] is safe. Positional parameters in helper functions are copied into named
locals, and helper functions end with a bare 'return', which keeps the exit
status of the last command (no behaviour change, notably for sha256 under
pipefail). packaging/linux/postinst.sh is POSIX sh and is left alone.
2026-10-23 11:16:40 -04:00
Dylan M. Taylor 78decf80f7 web: allow browser zoom in the viewport meta (SonarCloud Web:S7926) (#1974)
user-scalable=no stops people with low vision from zooming the page. The
canvas keeps its own pinch/pan handling: eframe already prevent_default()s
touch and gesture events on the canvas, so dropping the flag only restores
browser zoom (and accessibility zoom) outside of the app's gestures.
2026-10-23 11:16:34 -04:00
Marco Arnulfo 8ad9a3ce15 dwg: require acadrust 0.6.5, the first version that inverts dimension bit 0 itself 2026-10-23 14:54:19 +02:00
Marco Arnulfo 251fddb658 fonts: harfrust comment names both versions; the advance check skips fonts at 1000 per em 2026-10-23 09:49:38 +02:00
Marco Arnulfo 51db2d52e4 dependabot: leave the egui crates at 0.36 until craft-ui moves to 0.37 (craft-libs#199) 2026-10-23 09:49:38 +02:00
Marco Arnulfo 9621dcbd94 dwg: drop the dimension bit-0 inversion that acadrust 0.6.5 now does itself 2026-10-23 09:30:10 +02:00
Marco Arnulfo 5648a06ac4 Hold the egui crates at 0.36 until craft-ui moves to 0.37 (craft-libs#199) 2026-10-23 09:14:51 +02:00
Marco Arnulfo f344cf4460 engine: pass the query envelope by value to rstar 0.13 2026-10-23 08:50:32 +02:00
Marco Arnulfo e61e328edb io: read SVG element and attribute names with quick-xml 0.42 2026-10-23 08:50:32 +02:00
Marco Arnulfo 611eb9f5a9 fonts: port complex-text shaping to harfrust 0.14 2026-10-23 08:44:31 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 1977a493c7 chore(deps): bump the cargo-dependencies group across 1 directory with 17 updates (#1957)
Bumps the cargo-dependencies group with 17 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [serde_json](https://github.com/serde-rs/json) | `1.0.151` | `1.0.154` |
| [tiny-skia](https://github.com/linebender/tiny-skia) | `0.11.4` | `0.12.0` |
| [skrifa](https://github.com/googlefonts/fontations) | `0.47.0` | `0.48.0` |
| [harfrust](https://github.com/harfbuzz/harfrust) | `0.12.0` | `0.14.0` |
| [quick-xml](https://github.com/tafia/quick-xml) | `0.41.0` | `0.42.0` |
| [egui](https://github.com/emilk/egui) | `0.36.2` | `0.37.0` |
| [egui_kittest](https://github.com/emilk/egui) | `0.36.2` | `0.37.0` |
| [eframe](https://github.com/emilk/egui) | `0.36.2` | `0.37.0` |
| [egui-wgpu](https://github.com/emilk/egui) | `0.36.2` | `0.37.0` |
| [arboard](https://github.com/1Password/arboard) | `3.6.1` | `3.7.0` |
| [acadrust](https://github.com/hakanaktt/acadrust) | `0.6.4` | `0.6.5` |
| [rstar](https://github.com/georust/rstar) | `0.12.2` | `0.13.0` |
| [libc](https://github.com/rust-lang/libc) | `0.2.190` | `0.2.191` |
| [miniz_oxide](https://github.com/Frommi/miniz_oxide) | `0.8.9` | `0.9.1` |
| [getrandom](https://github.com/rust-random/getrandom) | `0.3.4` | `0.4.3` |
| [muda](https://github.com/tauri-apps/muda) | `0.21.0` | `0.21.2` |
| [winresource](https://github.com/BenjaminRi/winresource) | `0.1.31` | `0.1.34` |



Updates `serde_json` from 1.0.151 to 1.0.154
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.151...v1.0.154)

Updates `tiny-skia` from 0.11.4 to 0.12.0
- [Changelog](https://github.com/linebender/tiny-skia/blob/main/CHANGELOG.md)
- [Commits](https://github.com/linebender/tiny-skia/compare/v0.11.4...v0.12.0)

Updates `skrifa` from 0.47.0 to 0.48.0
- [Release notes](https://github.com/googlefonts/fontations/releases)
- [Changelog](https://github.com/googlefonts/fontations/blob/main/docs/RELEASE.md)
- [Commits](https://github.com/googlefonts/fontations/compare/skrifa-v0.47.0...skrifa-v0.48.0)

Updates `harfrust` from 0.12.0 to 0.14.0
- [Release notes](https://github.com/harfbuzz/harfrust/releases)
- [Changelog](https://github.com/harfbuzz/harfrust/blob/main/CHANGELOG.md)
- [Commits](https://github.com/harfbuzz/harfrust/compare/0.12.0...0.14.0)

Updates `quick-xml` from 0.41.0 to 0.42.0
- [Release notes](https://github.com/tafia/quick-xml/releases)
- [Changelog](https://github.com/tafia/quick-xml/blob/master/Changelog.md)
- [Commits](https://github.com/tafia/quick-xml/compare/v0.41.0...v0.42.0)

Updates `egui` from 0.36.2 to 0.37.0
- [Release notes](https://github.com/emilk/egui/releases)
- [Changelog](https://github.com/emilk/egui/blob/main/CHANGELOG.md)
- [Commits](https://github.com/emilk/egui/compare/0.36.2...0.37.0)

Updates `egui_kittest` from 0.36.2 to 0.37.0
- [Release notes](https://github.com/emilk/egui/releases)
- [Changelog](https://github.com/emilk/egui/blob/main/CHANGELOG.md)
- [Commits](https://github.com/emilk/egui/compare/0.36.2...0.37.0)

Updates `eframe` from 0.36.2 to 0.37.0
- [Release notes](https://github.com/emilk/egui/releases)
- [Changelog](https://github.com/emilk/egui/blob/main/CHANGELOG.md)
- [Commits](https://github.com/emilk/egui/compare/0.36.2...0.37.0)

Updates `egui-wgpu` from 0.36.2 to 0.37.0
- [Release notes](https://github.com/emilk/egui/releases)
- [Changelog](https://github.com/emilk/egui/blob/main/CHANGELOG.md)
- [Commits](https://github.com/emilk/egui/compare/0.36.2...0.37.0)

Updates `arboard` from 3.6.1 to 3.7.0
- [Release notes](https://github.com/1Password/arboard/releases)
- [Commits](https://github.com/1Password/arboard/compare/v3.6.1...v3.7.0)

Updates `acadrust` from 0.6.4 to 0.6.5
- [Release notes](https://github.com/hakanaktt/acadrust/releases)
- [Changelog](https://github.com/hakanaktt/acadrust/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hakanaktt/acadrust/compare/v0.6.4...v0.6.5)

Updates `rstar` from 0.12.2 to 0.13.0
- [Commits](https://github.com/georust/rstar/compare/v0.12.2...v0.13.0)

Updates `libc` from 0.2.190 to 0.2.191
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Changelog](https://github.com/rust-lang/libc/blob/0.2.191/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.190...0.2.191)

Updates `miniz_oxide` from 0.8.9 to 0.9.1
- [Changelog](https://github.com/Frommi/miniz_oxide/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Frommi/miniz_oxide/commits)

Updates `getrandom` from 0.3.4 to 0.4.3
- [Changelog](https://github.com/rust-random/getrandom/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/getrandom/compare/v0.3.4...v0.4.3)

Updates `muda` from 0.21.0 to 0.21.2
- [Release notes](https://github.com/tauri-apps/muda/releases)
- [Changelog](https://github.com/tauri-apps/muda/blob/dev/CHANGELOG.md)
- [Commits](https://github.com/tauri-apps/muda/compare/muda-v0.21...muda-v0.21.2)

Updates `winresource` from 0.1.31 to 0.1.34
- [Commits](https://github.com/BenjaminRi/winresource/commits)

---
updated-dependencies:
- dependency-name: acadrust
  dependency-version: 0.6.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: arboard
  dependency-version: 3.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: eframe
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: egui
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: egui-wgpu
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: egui_kittest
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: getrandom
  dependency-version: 0.4.3
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: harfrust
  dependency-version: 0.14.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: libc
  dependency-version: 0.2.191
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: miniz_oxide
  dependency-version: 0.9.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: muda
  dependency-version: 0.21.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: quick-xml
  dependency-version: 0.42.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: rstar
  dependency-version: 0.13.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: serde_json
  dependency-version: 1.0.154
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: skrifa
  dependency-version: 0.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: tiny-skia
  dependency-version: 0.12.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: winresource
  dependency-version: 0.1.34
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-22 23:54:32 -04:00
skylar taylor-barrick a08fd7c1d1 Merge pull request #1963 from storytold/docs/security-review-docstrings-20261022
docs: document security limits and regression guarantees
2026-10-22 18:36:19 -06:00
skylartaylor fa6bb0351b docs: clarify security regression guarantees 2026-10-23 02:14:11 +02:00
Brandon ThomasandClaude Opus 5.5 bad1073fdf Release 0.12.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 20:06:04 -04:00
skylartaylor 48b4165591 docs: document security limits and regression guarantees 2026-10-23 01:59:55 +02:00
Dylan M. Taylor 01bbdb24bc security: confine craft-fonts manifest paths and reject newline directives (CWE-22, CWE-74) (#1841)
The optional `CRAFT_FONTS_DIR` build input lets a font manifest select the file
each face is embedded from. `build.rs` canonicalised that file with no
containment check, so an absolute path, a `..` traversal, or a symlink inside
the checkout could make the generated `include_bytes!` read an arbitrary file
on the build host and expose its bytes through `CRAFT_FONTS` (CWE-22).

It also printed the resolved path straight into Cargo's newline-delimited
build-script protocol (`cargo::rerun-if-changed=…`). A path containing an
embedded newline — reachable through a crafted symlink target — could inject a
second directive such as `cargo::rustc-env=OUT_DIR=…`, redirecting the
generated-source include to attacker-supplied Rust (CWE-74).

- `resolve_font` rejects absolute and `..` manifest paths and requires the
  canonicalised result to stay inside the canonicalised checkout root.
- `rerun_if_changed` refuses any path containing CR/LF before emitting the
  directive; `one_line` collapses CR/LF in checkout-derived diagnostics.

Addresses findings rows 5 (CWE-22) and 14 (CWE-74).
2026-10-22 18:42:51 -04:00
Dylan M. Taylor 15ba3dc5cc security: submit XATTACH picked path as literal text, not a command line (CWE-74) (#1843)
The External References palette's XATTACH handler passed the file picker's
result to `app.cmdline(&path)`. `cmdline` interprets command-line syntax, so a
selected filename beginning with an apostrophe (for example `'closeall`) was run
as an engine command rather than naming the file — closing every drawing without
the UI's unsaved-change confirmation.

The picked path is attacker-controlled (the picker returns whatever the user
selected, and `relative_to_host` can reduce it to a bare basename). After
starting XATTACH, submit it through `Session::input(Input::Text(path))` so it is
delivered to the command's prompt as literal text and never interpreted as a
command, matching how other picker/dialog bridges already behave.

Addresses finding row 26.
2026-10-22 18:19:13 -04:00
Dylan M. Taylor 07bb604214 security: guard the DXF->DWG conversion input and document decoder limits (CWE-789) (#1847)
The native DWG bridge wraps the third-party `acadrust` decoder, which allocates
tables and section buffers from sizes a file declares and cannot be interrupted
once it starts. The DWG->DXF read path already rejects oversized input before
decoding, caps the DXF output while writing, and runs inside `catch_unwind`. The
DXF->DWG `convert` path had no input-size guard, so a very large DXF went
straight into the dependency's reader.

- `convert` now rejects DXF input larger than `Limits::max_dxf_bytes` before
  calling `DxfReader::read`, symmetric with the read path, and keeps the existing
  `catch_unwind` around the decoder and writer (rows 23, 3, 27, large-input
  variant).
- Documented the residual risk: a small file that declares a huge internal table
  or section can still make the dependency allocate before any size is known.
  Fully fixing that needs an upstream fix in `acadrust` (validate declared sizes
  against a decoded-memory budget) or a separate worker with an OS memory limit;
  the in-crate limits keep the blast radius bounded until then.

Addresses findings rows 3, 23, 27 (bounds the reachable input/output size;
the deeper allocation fix belongs in the unmodified dependency).
2026-10-22 18:18:43 -04:00
Dylan M. Taylorandskylartaylor dc4bbe86f6 security: bound font outline geometry and MTEXT line scanning (CWE-400/407) (#1852)
* security: bound font outline geometry and MTEXT line scanning (CWE-400/407)

Two font/text paths let crafted input monopolise the rendering thread:

- Glyph shaping copied a glyph's full contour set for every placed character
  with no cumulative budget, so a compact CFF/OTF font with a large expanded
  outline, repeated across a short string, could grow the shaped result without
  bound. `shape` now charges retained outline points against a cumulative
  per-line budget and stops placing geometry once it is exhausted (advances
  still accumulate, so the width stays sensible) (row 9).
- Default MTEXT layout recomputed `line.text.chars().count()` before appending
  each segment or space, rescanning the whole accumulated line every time —
  multiplicative on a long line. The line now keeps a running character count,
  updated only from newly appended text (row 20).

New tests cover the MTEXT layout; all font tests pass and render still builds,
clippy clean.

Addresses findings rows 9, 20.

* fix: budget glyph geometry before outline placement

* fix: skip empty outlines without text metadata

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:57:39 -04:00
Dylan M. Taylorandskylartaylor 953a6b3b01 security: bound Lisp callbacks, native comparisons, and local file reads (CWE-400, CWE-407) (#1842)
* security: bound Lisp callbacks, native comparisons, and local file reads (CWE-400, CWE-407)

The command and scripting engine had several unbounded paths a supplied LISP
routine or a selected path could exploit to monopolise the thread or exhaust
memory:

- `call_sync` ran synchronous callbacks (vl-sort comparators, vl-remove-if
  predicates, …) with `u64::MAX` fuel, so a constant-memory infinite loop never
  yielded and bypassed the blocking execution cap. It now drives the callback in
  bounded slices and aborts with an error past a hard step cap (row 2).
- `wcmatch`/`glob` explored `*` placements with only a recursion-depth guard,
  and `equal` re-traversed shared cons subtrees. Both now charge every step
  against a shared work budget and stop when it is exhausted (row 33).
- `setvar` converted a LISP value to JSON unboundedly, so a shared cons DAG
  expanded into gigabytes of owned arrays. Conversion is now depth- and
  element-bounded and rejects over-budget values with a LISP error (row 39).
- OPEN/LOAD/APPLOAD (`read_text_file`), SCRIPT, and native open (`read_file`,
  `run_open`) buffered a path with `std::fs::read`, so an endless device
  exhausted memory before any size check. Reads now go through a new
  `capped_read` helper that rejects non-regular files and caps bytes
  (rows 21, 34).

New tests cover the callback loop, the oversized setvar structure, and the
capped reader. Addresses findings rows 2, 21, 33, 34, 39.

* fix: bound native Lisp scans and nonblocking file reads

* fix: enforce callback fuel before each execution slice

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:57:09 -04:00
Dylan M. Taylorandskylartaylor 8085745a22 security: bound native DXF/SVG/PDF import allocation and quadratic work (CWE-400/407/789) (#1846)
* security: bound native DXF/SVG/PDF import allocation and quadratic work (CWE-400/407/789)

Several native import paths let a crafted drawing cause quadratic CPU work or
unbounded allocation:

- DXF layer decoding scanned the whole layer list for every LAYER record
  (`d.layer_mut`), so many distinct layer names made import quadratic. Keep a
  case-normalised name→index map and update/append in O(1) (row 29).
- ACAD_TABLE cells were materialised per table under a per-table cap, but many
  small tables could still add up. Add a document-wide table-cell budget in
  parse_entities; a table that would overflow it is reduced to empty (row 8).
- DXF image name allocation restarted its `_2, _3…` suffix probe for every
  definition sharing a base name (quadratic). Keep a per-base next-suffix
  counter so probing resumes where it left off (row 13).
- Image resolution cloned each definition's path/name into every referring
  image. Add an aggregate byte budget; once spent, string copies stop while
  geometry fields are still applied (row 42).
- PDF link annotation scanned the whole selected-link vector for every
  primitive. Build a HashSet of linked handles once for O(1) membership (row 15).
- SVG arc/curve flattening retained each flushed run with only a per-run cap, so
  repeated arcs amplified a compact path into unbounded geometry. Add a
  document-wide generated-vertex budget charged in `add` (row 31).

New test `svg_arc_budget` covers the SVG budget. All `cadcraft-io` tests pass;
clippy adds no new warnings.

Addresses findings rows 8, 13, 15, 29, 31, 42.

* fix: share DXF table budgets before allocation

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:35:43 -04:00
Dylan M. Taylorandskylartaylor ca578a8fb7 security: authenticate the local control server with a per-session token (CWE-306) (#1844)
* security: authenticate the local control server with a per-session token (CWE-306)

The optional `--control PORT` server listens on loopback TCP and dispatched any
JSON request without authenticating the peer. Loopback TCP does not distinguish
operating-system users, so another local account could connect and drive the
desktop user's command and file authority (for example reading files through
native Lisp, or create/truncate writes).

Authenticate the peer with an unguessable per-session token:

- New `cadcraft_mcp::control_token` module: `issue(port)` generates a 256-bit
  token and writes it to `cadcraft-control-<port>.token` in the per-user runtime
  directory with owner-only permissions (0600 on Unix; per-user LOCALAPPDATA on
  Windows). `read(port)` reads it; `matches` compares in constant time.
- The control server issues the token at startup and requires every request to
  carry a matching `token` field; requests without one get an `unauthorized`
  reply and the connection is closed before dispatch.
- The MCP bridge (`Remote`) reads the token from the owner-only file — which
  needs the desktop user's own filesystem access — and sends it on every
  request, so the bridge keeps working unchanged for the legitimate user. A
  different local user cannot read the token and cannot authenticate.

Updates `docs/control-protocol.md`. New tests cover token issue/read/compare,
file permissions, and that the server refuses unauthenticated requests while
accepting authenticated ones.

Addresses finding row 48.

* fix: recover control authentication across server restarts

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:35:18 -04:00
Dylan M. Taylorandskylartaylor 916be26ed3 security: bound constraint-engine work and allocation (CWE-400/407) (#1851)
* security: bound constraint-engine work and allocation (CWE-400/407)

The constraint engine let imported geometry or settings cause disproportionate
CPU/memory work on the synchronous analysis thread:

- Auto-constraint inference scanned the whole caller-supplied type list for every
  geometric candidate. Resolve the allowed type names into a set once and use
  O(1) membership per candidate (row 46).
- Rigid-point sampling stopped after collecting points but kept traversing block
  members that contribute none (Text, Ray, …), repeated for every Insert. Count
  every examined member against a bounded budget (row 47).
- Control-mode residual evaluation cloned the whole retained spline, including
  excess imported weights, for each free parameter. Drop weights that do not
  match the control-point count before retaining the template (row 45).
- The DOF analysis budget estimated only matrix-rank work, ignoring the spline
  reconstruction each tangent residual performs during numerical differentiation.
  Add a residual-evaluation budget (rows × free × per-residual cost, including a
  spline-reconstruction term) enforced before building the Jacobian (row 43).

All constraints tests pass; clippy adds no new warnings.

Addresses findings rows 43, 45, 46, 47.

* fix: budget constraint work without changing spline weights

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:12:04 -04:00
Dylan M. Taylorandskylartaylor 2dbc7699a0 security: budget the rendering pipeline against DoS geometry (CWE-400/407/789) (#1849)
* security: budget the rendering pipeline against DoS geometry (CWE-400/407/789)

Several render paths let crafted drawing data spin the rendering thread or
allocate without bound:

- Hatch dash sweeping reset its per-span step counter and used emitted geometry
  as its only limit, so gap-only families (which emit nothing) could multiply
  CPU work. Skip families that cannot draw and charge every dash step against a
  shared per-hatch work budget (row 10).
- Hatch polygon deduplication compared loops with an O(n²) cyclic match and
  every loop against every kept one. Charge vertex comparisons against a shared
  budget and stop deduplicating when spent (row 12).
- Table coverage marked every merge rectangle, so overlapping merges re-marked
  covered cells quadratically. Bound marking to a small multiple of the cell
  count (row 11).
- Broken-table part layout expanded sparse rows to full width before checking
  whether detailed layout is allowed. Only expand when within the cell limit;
  otherwise leave cells sparse and let layout draw an outline (row 17).
- Dimension text substitution copied the base for every `<>` placeholder with no
  size bound. Estimate the expansion and cap it at a fixed text budget (row 32).
- Linetype range generation cycled all-gap patterns forever (nothing emitted, so
  the emit limit never tripped). Return continuous for all-gap patterns and
  bound visited pattern elements (row 38).
- Viewport contents built with a fresh expansion counter, so a layout could far
  exceed the documented block-expansion limit. Share one budget across the whole
  build, seeded with what the enclosing list already spent (row 22).

New tests for the all-gap linetype path; all render tests pass, clippy clean.

Addresses findings rows 10, 11, 12, 17, 22, 32, 38.

* fix: preserve bounded render fallbacks and text output

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:08:25 -04:00
Dylan M. Taylorandskylartaylor 7c72ec45a9 security: bound drawing document-model work and allocation (CWE-400/407) (#1850)
* security: bound drawing document-model work and allocation (CWE-400/407)

Several document-model operations let crafted drawing data cause quadratic or
exponential work, or multiply retained allocations:

- Polyline grip generation rebuilt the whole segment vector inside the loop over
  every vertex, so enumerating one large polyline's grips was quadratic. Compute
  the segments once before the loop (row 35).
- Associative-array name sync searched the whole replacement vector for every
  placement. Index replacements by placement coordinate once (last entry wins),
  turning the per-item lookup O(1) (row 44).
- Dimension-extent bounds recursively expanded the referenced block without the
  shared bounds cache the Insert path uses, so a branching or self-referencing
  dimension block cost one pass per reference. Route it through the same
  `(name, depth)` cache (row 37).
- Dynamic-block parsing parsed every graph-member occurrence into its own owned
  parameter, so a graph repeating a member multiplied one record into gigabytes.
  Deduplicate member handles before resolving them (row 7).
- Stretch-action application linearly searched the vertex list and cloned the
  index vector for every selection occurrence. Index vertices by handle and skip
  handles already handled in the action's selection (row 30).

New tests for polyline grips; all doc tests pass, clippy clean.

Addresses findings rows 7, 30, 35, 37, 44.

* fix: retain first dynamic stretch vertex selection

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:08:02 -04:00
Dylan M. Taylorandskylartaylor 0158712bfd security: bound geometry-kernel degree and work (CWE-407) (#1848)
* security: bound geometry-kernel degree and work (CWE-407)

Several geometry routines let a crafted spline or region cause quadratic or
worse CPU work:

- B-spline basis evaluation is O(degree²) per sample and tessellation takes
  O(degree) samples, so a HATCH/DXF spline edge declaring a very high degree
  (DXF allows up to 100 000) turned a tiny spline into billions of iterations.
  Add `MAX_DEGREE = 64` and treat higher-degree splines as invalid, so
  `eval`/`tessellate` fall back to the control polygon. The render clip boundary
  also rejects such degrees up front (rows 18, 28).
- `Spline::derivative` re-ran the O(knots) validity scan on every call, and
  arc-length integration calls it once per sample, making a valid spline's
  measurement quadratic. Split off `derivative_unchecked` and have integration
  (validated once by its public entry points) use it (row 24).
- `infer_knot_param` matched each fit parameter against the whole knot vector
  from the start. Both are ascending, so replace it with a linear merge (row 16).
- Fillet seed collection did not stop the enclosing run-pair loops when the
  per-call candidate cap was hit, and refined duplicate candidates. Bound total
  seeds across pairs and deduplicate before Newton refinement (row 36).
- Region grid intersection counted only distinct pairs against its budget, so a
  long segment replicated across many cells re-visited the same pair unbounded.
  Charge every candidate-pair visit against a budget (row 41).

New spline degree tests added; all geom and render tests pass, clippy clean.

Addresses findings rows 16, 18, 24, 28, 36, 41.

* fix: preserve spline knot and fillet search behavior

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:05:16 -04:00
Dylan M. Taylorandskylartaylor 683eb5e6e7 security: do not follow directory symlinks in cargo xtask stats (CWE-400) (#1845)
* security: do not follow directory symlinks in `cargo xtask stats` (CWE-400)

The stats walker descended with `Path::is_dir()`, which follows symlinks, and
kept no record of visited directories. A small acyclic graph of directory
aliases planted in a workspace package (for example through a contribution a
developer inspects) therefore caused exponentially repeated enumeration and file
reads, consuming CPU and I/O far beyond the repository's real size.

`walk` now inspects each entry's own `file_type()` and skips symlinks before
descending or reading, so directory aliases are never re-scanned. A traversal
budget (`MAX_ENTRIES`) bounds total work as defense in depth.

Addresses finding row 4.

* fix: report statistics traversal exhaustion

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:04:35 -04:00
Dylan M. Taylorandskylartaylor 345fb27a69 security: write files atomically through an exclusive temp file (CWE-59) (#1840)
* security: write files atomically through an exclusive temp file (CWE-59, CWE-377)

Save, export, plot, autosave and the audit log each wrote their output by
putting bytes in a predictable sibling temporary path (`<path>.cadcraft-tmp`,
`<recovery>.tmp`, or the companion `.adt`) and renaming it over the real file.
Opening that pre-existing temporary path for a truncating write follows a
symlink planted there by another local user, letting them redirect the write
onto any file the victim can write before the rename.

Add a shared `atomic_write` helper that creates a fresh temporary file with
`create_new` (O_CREAT|O_EXCL) in the destination directory, writes through the
retained handle, flushes/syncs, and atomically renames it into place. An
existing entry (symlink or not) makes the exclusive create fail instead of
being followed. Route autosave, save, export, plot and the audit log through it.

The macOS CI cert importer likewise wrote the decoded PKCS#12 container to a
fixed name in a possibly shared temp directory; it now creates a private
per-run directory with `mktemp -d` and creates the file with noclobber.

Addresses findings rows 1, 25, 40 (CWE-59) and 19 (CWE-377).

* fix: preserve permissions during atomic replacement

* fix: restrict temporary permissions during exclusive creation

---------

Co-authored-by: skylartaylor <[email protected]>
2026-10-22 17:03:46 -04:00
Brandon ThomasandClaude Opus 5.5 8f988f630d Release 0.11.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 15:37:25 -04:00
Dylan M. Taylor acd109d97c Use chrono instead of hand-rolled UTC conversion (#1789)
* Use chrono for UTC/calendar conversion instead of hand-rolled copies

Replaces the three civil_from_days copies (logging timestamp, Drawing
Recovery time, parity checklist date) with chrono as a workspace
dependency. Output formats are unchanged and pinned by the existing tests.
AGENTS.md now says time goes through chrono.

Fixes #1785

* Never panic on a clock outside chrono's range; keep 5-digit years unprefixed

chrono's From<SystemTime> unwraps, so a clock past year 262143 panicked
inside the logger. timestamp and xtask's date now use the fallible
DateTime::from_timestamp and read such a clock as the epoch, as the old
saturating code did. xtask's date also clamps a pre-epoch clock to
1970-01-01 again. Years past 9999 are written with {:04} like before,
because %Y would add a '+'. Tests cover all three cases.

* Don't build an unrepresentable SystemTime in the far-future test

UNIX_EPOCH + Duration::from_secs(u64::MAX / 2) overflows Windows'
SystemTime and panicked before timestamp() ran, failing the Windows
test job. Build it with checked_add and only assert where it exists.

* logging/autosave/parity: keep extended-year dates, no epoch fallback

Applies the stricter no-epoch-fallback rule (from wordcraft#3427 / filmcraft#2662,
superseding the earlier epoch-or-last-valid suggestion) so all sibling PRs agree:
a timestamp the old code converted past chrono's year 262143 range must keep its real
proleptic-Gregorian date, not collapse to 1970-01-01. Each site uses the 400-year
Gregorian cycle (146_097 days) with chrono as the only calendar logic: chrono converts
the day within one cycle, whole cycles carry in the year (i128, saturated into i64).
This also removes the panic FredApps flagged — `DateTime::<Utc>::from(SystemTime)` could
panic past chrono's range; `from_num_days_from_ce_opt` within one cycle never does.
Verified the cycle result equals the old formula across a wide range and at the extremes.

- apps/cadcraft/src/logging.rs `timestamp`: cycle `civil_from_days(u64)`; pre-1970 epoch
  clamp and ms/time-of-day format kept. Pins: +10_000_000_000_000 s -> 318857-05-20T17:46:40.000Z
  (was 1970-...); checked_add u64::MAX/2 s -> 292277026596-12-04T15:30:07.000Z (was epoch).
- crates/ui-egui/src/autosave.rs `utc`: cycle converter. Pins: utc(10_000_000_000_000)
  = "318857-05-20 17:46"; utc(u64::MAX) = "584554051223-11-09 07:00" (was "1970-01-01 00:00").
- xtask/src/parity.rs `date`: cycle converter; pre-1970 epoch clamp kept. Pins:
  day(115_740_740) = "318857-05-20"; checked_add u64::MAX/2 s -> "292277026596-12-04" (was epoch).

* Don't build a year-318857 SystemTime unchecked in the logging test

Windows' SystemTime only reaches about year 30828, so
UNIX_EPOCH + Duration::from_secs(10_000_000_000_000) panicked before
timestamp() ran and failed the Windows test job. Build it with
checked_add and assert where the platform can hold it. The year-10000
case fits everywhere and stays unconditional.

* Name the 400-year range extension as the one exception to the time rule

The rule said never to hand-roll calendar math, but the range fix
(shifting by whole 400-year Gregorian cycles so dates past chrono's year
range keep their old output) is cycle arithmetic, so the rule and the code
disagreed. The rule now names that exception: the library still computes
month, day and time, and only whole cycles are carried in the year.

* Say the library computes month and day; time-of-day is plain arithmetic

Narrows the range-extension wording: the date library computes the
calendar fields, and splitting seconds into hours, minutes and seconds
is ordinary arithmetic, which is what the code does.
2026-10-22 14:09:16 -04:00
Antoine Boxho f4e6873130 Merge pull request #1568 from C00kieMonsta/readme-official-source
README: verify official releases and download checksums (fixes #1554)
2026-10-22 14:05:42 -04:00
skylar taylor-barrick e4214f7180 Merge pull request #1677 from MarekSpodBiedry/issue-1644
Write the ACAD_TABLE *T block relative to its insertion point (#1644)
2026-10-22 07:51:40 -06:00
skylar taylor-barrick 35934718ea Merge pull request #1683 from MarekSpodBiedry/issue-1667
Keep a layout's plot window corners when saving DXF (#1667)
2026-10-22 07:51:33 -06:00
skylar taylor-barrick 916d440bed Merge pull request #1718 from oracola91/fix/control-accept-backoff
Control server: wait after a failed accept instead of retrying at once
2026-10-22 07:51:26 -06:00
skylar taylor-barrick 632967aa78 Merge pull request #1336 from midasmatterhorn/fix/r4-dxf-table-record-caps
io: the four symbol tables honour the same record cap as their peers
2026-10-22 07:51:19 -06:00
skylar taylor-barrick f15be2305c Merge pull request #1680 from MarekSpodBiedry/issue-1650
DWG: write the current text style's own handle, so AutoCAD opens with it current (#1650)
2026-10-22 07:51:12 -06:00
skylar taylor-barrick f2dadec23a Merge pull request #1678 from MarekSpodBiedry/issue-1648
Multileader sizes no longer multiplied by DIMSCALE (#1648)
2026-10-22 07:51:06 -06:00
skylar taylor-barrick 00acec952e Merge pull request #1774 from philipp-tch/fix/foreign-handles-above-2-48
DXF: keep foreign objects whose handles are above 2^48 (fixes #1773)
2026-10-22 07:51:00 -06:00
skylar taylor-barrick 78254b4d3f Merge pull request #1480 from Silvertree2010/fix/h2426-polyline-segments-with-a-tiny-no
Treat polyline bulges with a sub-EPS sweep as straight segments
2026-10-22 07:50:53 -06:00
skylar taylor-barrick 8094d7746f Merge pull request #1635 from Hamza0101/entsel-pickbox
AutoLISP: an entsel prompt shows the pick box whatever its message says
2026-10-22 07:50:47 -06:00
skylar taylor-barrick 4ad4f4f598 Merge pull request #1628 from Hamza0101/lisp-eq-symbols
AutoLISP: `=` compares the symbols `type` returns
2026-10-22 07:50:41 -06:00
BFlat 477eec5026 Merge pull request #1894 from storytold/readme/app-icon
README: the app icon above the title
2026-10-22 18:01:10 +07:00
bflatastic 38750c6eb8 README: the app icon above the title 2026-10-22 17:57:20 +07:00
Dylan M. Taylor 75d9d72703 Merge pull request #1837 from storytold/sonar-fix/enforce-https
security: enforce HTTPS on curl downloads (SonarCloud S6506)
2026-10-21 20:13:55 -04:00
Dylan M. Taylor fdcd9610f2 security: enforce HTTPS on curl downloads (SonarCloud S6506)
Add --proto '=https' to curl invocations so redirects cannot downgrade to
plaintext HTTP. Resolves SonarCloud S6506 (shell/docker/githubactions).
2026-10-21 17:06:31 -04:00
Dylan M. Taylor 54d96834d5 ci: add sonar-project.properties for CI-based analysis
Marks the project ineligible for SonarCloud Automatic Analysis, resolving the
CI-vs-automatic-analysis conflict so the SonarCloud workflow succeeds.
2026-10-21 16:00:22 -04:00
Dylan M. Taylor 47a8fb02e7 ci: add SonarCloud scan via shared reusable workflow
Calls storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with secrets: inherit. Adds SonarCloud badge to README where missing and
removes the redundant sonar-project.properties (config now passed by the
reusable workflow).
2026-10-21 15:46:46 -04:00
Dylan M. Taylor 896a390b42 ci: add SonarCloud scan workflow and config 2026-10-21 13:57:30 -04:00
Dylan M. Taylor 345eb60ef3 test 2026-10-21 13:57:10 -04:00
Dylan M. Taylor 0cf3bdea83 Merge pull request #1398 from dylanmtaylor/ci/shared-nix-workflow
ci: switch to shared nix workflow from craft-common-actions
2026-10-21 03:40:18 -04:00
Philipp ThomannandClaude Opus 5.5 82424e47c9 DXF: keep foreign objects whose handles are above 2^48
AutoCAD writes handles above 2^48 (whole drawings whose handles start at 0xDAD1...).
dxf_raw dropped every foreign object with such a handle, so these drawings lost their
dynamic blocks and all other unmodelled objects on read, DXF to DXF as well. DXF handles
are up to 16 hex digits; the whole 64-bit range is now believed (null still is not).
Modelled entities and table records already accepted such handles.

Test: the DOOR fixture with every handle moved above 2^48 keeps its dynamic block
through a save (red before the change).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 07:23:16 +02:00
Brandon ThomasandClaude Opus 5.5 7fef8cbe2f Skip CodeRabbit reviews on Dependabot PRs (#1727)
Adds .coderabbit.yaml so CodeRabbit no longer reviews or comments on PRs opened by dependabot[bot].

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-20 11:39:39 -04:00
Dylan M. Taylor f2b473dc51 docs: add SonarCloud and CodeRabbit badges to README (#1566)
* docs: add SonarCloud and CodeRabbit badges to README

* docs: put SonarCloud and CodeRabbit badges on their own line
2026-10-20 11:32:50 -04:00
oracola91 4d826ed91f Control server: wait after a failed accept instead of retrying at once
The accepting thread dropped failed accepts with incoming().flatten()
and asked again at once. When accepting keeps failing, for example while
the process has no file descriptors left, that loop keeps a core busy
until it recovers.

Wait 100 ms after a failed accept. The loop goes through a small helper
so the wait can be tested without running out of file descriptors.
2026-10-20 14:49:58 +03:00
Brandon ThomasandClaude Opus 5.5 e86eacf094 Release 0.10.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 22:18:26 -04:00
MarekSpodBiedry a7bb28d722 DWG: write the current text style's own handle, so AutoCAD opens with it current (#1650) 2026-10-19 22:33:02 +02:00
MarekSpodBiedry 27bff9cc30 Write the ACAD_TABLE *T block relative to its insertion point (#1644) 2026-10-19 22:29:01 +02:00
MarekSpodBiedry d600a80354 Multileader sizes no longer multiplied by DIMSCALE (#1648) 2026-10-19 22:27:34 +02:00
MarekSpodBiedry 81f0aa53ff Keep a layout's plot window corners when saving DXF (#1667) 2026-10-19 22:27:04 +02:00
Hamza 27861ad0ed Read a prompt's wording only where the engine wrote it
The pick-box heuristic read the message for a leading "Select", and
this branch had widened it past leading whitespace so that a routine's
own message would be read the same way. That makes a plain point prompt
look like a pick: (getpoint "\nSelect a point: ") showed the pick box
and lost its point modifiers, since pointmod refuses them wherever
picks_objects holds.

A routine writes all of its own message (raw), and says through
picks_one when it picks an object, so the wording needs reading only
where the engine wrote it. Covered for both spellings a routine might
use, with and without the leading newline.
2026-10-20 00:31:05 +05:00
Hamza b72680cfb7 AutoLISP: an entsel prompt shows the pick box whatever its message says
Whether the cursor shows the pick box came from `Prompt::picks_objects()`,
which read the prompt's wording: a selection-set prompt, or a point prompt whose
message starts with "Select". An `entsel`/`nentsel` prompt takes a point and is
not a selection set, so it fell to the wording -- and an AutoLISP routine writes
its own message, conventionally starting with a newline:

  (nentsel)                                       "Select object: "   pick box
  (nentsel "\nSelect second line or polyline: ")   starts with "\n"   none
  (entsel  "\nPick a line: ")                     says no such word  none

A prompt now says that it picks one object rather than being read for it, and
`GetRequest::prompt()` sets that for `GetKind::EntSel`, so all three show the
pick box. The wording test is read past leading whitespace as well, so a command
machine's prompt beginning with a newline is not caught by the same thing.

Point modifiers (`.x`, `.y`…) are offered at a point prompt that is not a pick,
so they no longer appear at an `entsel` prompt with a message -- as they never
did at one without.

Fix: #1598
2026-10-19 19:13:23 +05:00
Hamza d9adce038c AutoLISP: = compares the symbols type returns
`(= (type x) 'LIST)` is how an AutoLISP routine tests a type, because `type`
returns a symbol. `=` coerced both of its arguments to numbers, so the symbol
failed the coercion and the routine stopped at its first type test:

  _$ (= (type 1) 'INT)
  bad argument type: numberp: INT

`=` and `/=` now compare numbers and strings as before, and any other atom -- a
symbol, `nil`, an entity name, a selection set, a file handle -- by what it is,
the way `eq` does. Two consequences, both closer to AutoLISP than raising was:
a mismatch of kinds answers `nil` rather than failing, so `(= 1 "1")` and
`(= '(1) '(1))` answer (comparing list structure is `equal`'s job), and
`(= nil nil)` is `T`.

The ordering comparisons still take numbers and strings only, as AutoLISP has
them: `(< 'a 'b)` remains `bad argument type: numberp: A`.

Fix: #1597
2026-10-19 17:26:39 +05:00
Brandon ThomasandClaude Opus 5.5 0b32c2e6a1 i18n(hu): the ViewCube pill's key is now WCS (after #1558)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 03:02:53 -04:00
323f4629eb Add Greek (el) interface localization (#1307)
Co-authored-by: Camthalion77 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 03:02:49 -04:00
c02027abc8 Bound CAL unary minus/plus and ^ chain recursion (#1586)
Found while testing crates/engine/src/cmd/utility/calc.rs:124-140 (Parser::unary recursion, MAX_DEPTH only counted in expr() and '[')

Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:57:52 -04:00
8c249aa722 Menu bar switches to the hovered menu once one is open (fixes #1567) (#1571)
With a menu of the in-window bar open, pointing at another title now
closes the open menu and opens that one. With no menu open, pointing
still opens nothing. Clicking the open title, clicking elsewhere, Esc
or choosing an item close the menu as before.

The bar now draws its titles first, then opens the hovered title's menu
if another bar menu is open, then draws the menus. egui 0.36's MenuBar
has no hover switching of its own.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:57:40 -04:00
a0aa0863bf Turkish interface (Türkçe) (#1529)
Add a Turkish catalog (tr.tsv, 1,330 rows): the union of the existing
catalogs, four menu headings (Ölçülendirme for the Dimension menu, Ölçü for
the object) and single-form counts, since a Turkish noun stays singular after
a number. No marked UI literal falls back to English. Prompts read "… girin"
for Enter and "… belirtin" for Specify; clickable keywords (Top, Zero, Bottom,
_tan to, nX/nXP) keep the spelling the engine accepts.

Register the language (Preference::Turkish, `tr`, Türkçe) and add locale,
preference, count, menu-heading, live-switch, dialog and font tests. Docs,
README and ATTRIBUTION list it; the translation is AI-assisted, the running
app was reviewed by a native speaker, and line-by-line proofreading is still
to do.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:57:28 -04:00
b4509d2368 DWG: leave out orphaned DGN line style components, so DGN-bloated drawings open (fixes #1482) (#1501)
* DWG: leave out orphaned DGN line style components, so DGN-bloated drawings open (fixes #1482)

A DWG that has been through MicroStation can carry hundreds of thousands of
DGN line style components no line style definition uses. In an 82.8 MB site
plan they were 888,483 of 889,053 and made the DXF rendition 1.2 GB, over the
1 GB limit, so the file didn't open. After the failsafe read, components no
LSDEFINITION reaches (through compound and point components) are left out with
their dictionary entries, and a read note says how many.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* contributors: add my real name for the About window credits

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:57:16 -04:00
13a3ebc0d1 AREA: an ellipse's perimeter is its exact length, not a closed-form estimate (#1471)
AREA's Object option reported a full ellipse's perimeter with
Ramanujan's closed-form estimate, which falls short as the ellipse
flattens: 46.0256 for a 10 x 4 ellipse (exactly 46.0262), 39.8741 for a
10 x 0.1 one (exactly 40.0110, 0.34% short). It now integrates the
perimeter with the geometry crate's ellipse arc length, the one LENGTHEN
measures with, so both report the same length for the same ellipse.

Ellipse::arc_length_from halves a panel where it needs it (the same
adaptive Gauss-Legendre as spline arc lengths): with fixed panels a
100:1 ellipse came out 4e-8 long, as it turns sharply at its ends.

Tests check four ellipses (round to 100:1) against the
arithmetic-geometric mean to 1e-9, and the printed AREA line.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:57:04 -04:00
41e0860725 ALIASEDIT opens the Command Aliases dialog (#1381) (#1391)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:56:52 -04:00
0d23cc3cb3 MOCORO: move, copy, rotate and scale a selection from one base point until eXit (#1388)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:56:40 -04:00
81acc9b8e4 Print signed two-digit exponent for scientific units (LUNITS 1) (#1386)
Found while testing crates/engine/src/units.rs:13

Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:56:28 -04:00
397b8e156a MLEDIT Merged Tee: the first multiline's inner elements run on to the second's (#1375)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:56:16 -04:00
12567f14f2 BURST: explode block references with their attribute values as text (#1345)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:56:04 -04:00
95e86caea5 TXT2MTXT: selected TEXT combined into one MTEXT top-down, or one MTEXT per TEXT, with SEttings (#1343)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:55:53 -04:00
7adf8d89cd BREAKLINE: a polyline with a break symbol between two points, with Block, Size and Extension (#1340)
Tools > Express Tools > Break-line Symbol draws one polyline from the first point to the second with a zigzag break symbol at a picked location (the midpoint on Enter), as AutoCAD's Express Tool does. Size scales the symbol (times DIMSCALE), Extension runs the line past both points, and Block takes a block of the drawing whose two points on the Defpoints layer mark where the line meets the symbol. The built-in symbol is our own geometry. One undo step; the options are remembered for the session.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:55:41 -04:00
006f71f650 Keep Z and elevation of the pieces left by BREAK (#1270)
Found while testing crates/engine/src/cmd/modify.rs:1457 (break_entity; helpers `line()`/`arc()`/`lwpoly()` in crates/engine/src/cmd/helpers.rs:10-23)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:55:28 -04:00
b0ed57f1c7 i18n(sv): translate the 95 strings added since the Swedish catalog (#1258)
Covers the Hatch and Gradient dialog, the Block Editor, REFEDIT, multileader
editing, the Options selection settings, the MTEXT editor and recent files.
The Swedish catalog now has every key of the Ukrainian reference catalog.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:55:14 -04:00
30db7296c4 선택 객체 조회 필터와 MCP 연동 추가 (#1253)
## 변경 내용
- entities 명령에 selected 불리언 필터를 추가해 현재 공간의 선택 객체만 조회
- 기존 종류·레이어·영역 필터와 결합하고 필터 적용 후 페이지 처리
- MCP query_entities 스키마와 명령·제어 프로토콜 문서에 옵션 공개
- 빈 선택, 중복·오래된 핸들, 다른 공간 객체, 잘못된 입력 및 조회 전후 상태 보존 회귀 테스트 추가

## 검증
- cargo xtask ci 6단계 통과: fmt, clippy, 테스트 2,012개, assets, layers, wasm
- 별도 .NET 클라이언트와 실제 헤드리스 엔진의 localhost 통합 검증 통과
- 실제 데스크톱 UI 조작 및 고객 DWG 왕복 검증은 수행하지 않음

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:55:02 -04:00
a76775bf2b Holding Shift overrides ortho while it is held, as in AutoCAD (#1198)
At a point prompt with a base point, holding Shift turns ortho on when
ORTHOMODE is off and off when it is on; releasing it restores the setting.
ORTHOMODE itself is never changed. While the override turns ortho on, polar
tracking is off, as with ortho on.

The UI already passed the Shift state to Session::snap_cursor (for POLARMODE
bit 8's Shift to acquire), so the change is in the engine only: snap_cursor
applies the override to its copy of the settings. Window corners (ZOOM
Window) and prompts without a base point are unaffected.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:54:51 -04:00
6576cac1a3 JOIN with a single arc or elliptical arc offers cLose: the arc becomes its circle, the elliptical arc its full ellipse (fixes #1175) (#1197)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:54:39 -04:00
4125b351cd Add HATCHEDIT boundary add and remove (#1156)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:54:28 -04:00
6d15a40f43 Selection cycling: a click over overlapping objects lists them, Shift+Space steps through them (#1149)
* Selection cycling: a click over overlapping objects lists them, Shift+Space steps through them (fixes #1143, fixes #1145)

* canvas: keep viewport_content's doc comment on it

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:54:16 -04:00
5f390e6e6a Constraints: the settings checkboxes show or hide all, dropping per-object exceptions (part of #1134) (#1144)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:54:03 -04:00
00f521858a Dynamic blocks: a grip drag previews the reference in its own colours (#1124)
* Dynamic blocks: a grip drag previews the reference in its own colours

The preview of a dynamic grip drag is the reference re-evaluated at the
cursor. It was drawn in the preview colour, fills left out, so on a filled
label the text was white on white. Commands can now give preview objects
with their own properties (`Interactive::preview_objects`, drawn under the
rubber band); the grip drag gives the block's objects with the properties
they draw with in the reference (layer 0 on its layer, ByBlock its
colour, linetype, lineweight and transparency) and its attributes with their
definitions', fills included in the block's order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Preview: the rubber band is grip blue over objects previewed in their own colours

Over a block previewed in its own colours the rubber band and tick marks,
in the current layer's colour, could vanish on its fill (white on white).
They are drawn in the grip blue there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:53:50 -04:00
bcd0b3745e fix(render): stabilize dashed highlights of filled objects (#1046)
* fix(render): keep filled highlight dash anchors stable

* outline test: as_chunks for clippy

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:53:38 -04:00
ba27f36b58 Inquiry: SHAPES reports closed-shape geometry facts (#1507)
* Inquiry: SHAPES reports closed-shape geometry facts

`shapes` is a read-only command that reports, for every closed shape in the
current space (closed polylines, circles, full ellipses, closed splines),
its perimeter, area, centroid, winding, first self-intersection and
coincident vertices, exact with arcs and bulges. It filters and pages like
`entities` and counts other matches under `skipped` with the reason.

`Polyline::centroid` and `polygon_centroid` give the area centroid.

Fixes #1436.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* shapes: cap the quadratic self-intersection test at 4000 edges

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:53:10 -04:00
9f7a2422ea feat(engine): support AUDITCTL system variable and .adt log generation (gaps F4) (#1504)
* feat(engine): support AUDITCTL system variable and .adt log generation (gaps F4)

* audit: write the .adt log only beside a saved drawing

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:53:04 -04:00
148091aa93 Properties: a dimension's text height, arrow size, overall scale and precision (#1259) (#1473)
* Properties: a dimension's text height, arrow size, overall scale and precision (#1259)

The Properties palette showed only a dimension's text override and style,
so the only way to change its text height was a new dimension style.
It now shows Text height (DIMTXT), Arrow size (DIMASZ), Dim scale overall
(DIMSCALE) and Precision (DIMDEC) with the values the dimension draws
with. Editing one sets a per-dimension override (DIMOVERRIDE) on the
selected dimensions, as AutoCAD's Properties palette does; the style is
left alone. properties.set takes textHeight, arrowSize, dimScale and
precision for dimensions and refuses bad values before changing anything.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* props: keep DIMOVERRIDE's doc comment on dim_override

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:52:59 -04:00
c82d6228ff i18n:Add missing translations for the print dialog and page settings. (#1289)
* i18n:Add missing translations for the print dialog and page settings.

* i18n:Add missing translations for the print dialog and page settings.

* i18n(zh): drop rows that repeat existing keys and the unused 'Page setup of'

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:52:53 -04:00
786c8c46e4 Wrap format_angle to zero when rounding reaches a full turn (#1256)
* Wrap format_angle to zero when rounding reaches a full turn

Found while testing crates/engine/src/units.rs:63-66,87-88,102

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* units: wrap a full turn by the formatted value, so ties round as {:.*} does

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-19 02:52:48 -04:00
NetterSilverandClaude Haiku 5.5 62329310d7 Reject non-hex characters such as '+' in Rgb::parse_hex (#1601)
Found while testing crates/color/src/lib.rs:23-29

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:33:35 -04:00
Antoine Boxho 6bd09ea468 docs: customizing and automating CADCraft (for #1561) (#1569)
A short guide for people porting add-ons: what runs today (LISP routines
and startup files, .scr scripts, .pgp alias files, the JSON control
channel, MCP, cadcraft-cli), what doesn't yet (Visual LISP ActiveX, DCL,
reactors, compiled plug-ins), and where each is documented. The README's
automation section links to it.
2026-10-19 02:33:28 -04:00
FilforandClaude Opus 5.5 0440fa77ff fix(viewcube): draw the WCS pill's arrow instead of a "⌄" glyph (fixes #1541) (#1558)
The pill under the ViewCube was the text "WCS ⌄". U+2304 is missing from some
UI fonts, so it showed as a box ("WCS □"). The pill now paints the translated
label and a down chevron drawn as lines, in the pill's ink, so it no longer
depends on the font. The catalog key becomes "WCS" in every language; Korean,
which spelled the arrow out as "WCS 선택", is now "WCS" next to the chevron.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:33:21 -04:00
Gert Pellin - GPE 471478868d cadcraft-cli: --help / -h / help exit 0 and print the usage to stdout (#1526)
A help request is not a failure: --version already goes to stdout with
exit 0, and now --help, -h and help do the same. Bare cadcraft-cli
keeps reporting on stderr with exit 1, like git.

Fixes #1525
2026-10-19 02:33:15 -04:00
aldozarandClaude Opus 5.5 0f833358b9 ID, DIST and LIST report Z (#1509)
ID always printed Z = 0, DIST's Delta Z and angle from the XY plane were
0, and LIST printed Z = 0 for lines, circles, arcs and polyline vertices,
though the drawing kept every Z: a topographic drawing's levels could not
be read in CADCraft.

Points reach these commands in 2D, so the Z is that of what is drawn at
the point, as AutoCAD reports a snapped point's: the object a pick finds
there (a point, a 3D line or 3D polyline interpolated, a polyline's
elevation, down Z for a mirrored one, a circle, arc, text, block or the
plane of a 3D face), else the current elevation (ELEVATION). A Z given
with a JSON point wins. DIST gives the 3D distance, Delta Z and the angle
from the XY plane; LIST the Z of lines, circles, arcs and text, a line's
3D length and deltas, and a polyline's elevation.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:33:10 -04:00
mattlafyandClaude Opus 5.5 64e55f903c Options: an interface scale preference (#1508)
interfaceScale (0.5-3, default 1) in the OPTIONS JSON form and the Display
tab scales every menu, palette, dialog and the command line through egui's
zoom factor, and is kept in the profile.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:33:04 -04:00
NetterSilverandClaude Haiku 5.5 94aad92f1d Scale SVG export precision and point size to the drawing's extents (#1495)
Found while testing crates/io/src/svg.rs:50-60 (export_list: viewBox, stroke-width, circle r and coordinates all formatted with {:.6})

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:32:58 -04:00
NetterSilverandClaude Haiku 5.5 1738d3805e Offset elliptical arcs towards the picked side (#1475)
Found while testing crates/engine/src/cmd/modify.rs:584-597 (offset_kind, EntityKind::Ellipse branch)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:32:52 -04:00
Rusu Alex bf6d9fd46a Make Properties layer menu scrollable (#1467) 2026-10-19 02:32:47 -04:00
Rusu Alex f17be3d7ad Fix Properties palette color swatch (#1466) 2026-10-19 02:32:39 -04:00
NetterSilverandClaude Haiku 5.5 582d9535b6 Strip the UTF-8 BOM when reading a data link CSV file (#1457)
Found while testing crates/engine/src/cmd/table/breaks.rs:167 (parse_csv), fed by read_link at :236 (String::from_utf8_lossy, no BOM removal)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:32:33 -04:00
Marco Arnulfo 2a3b0c2626 A wide polyline thinner than a pixel keeps every side on screen (fixes #1434) (#1453) 2026-10-19 02:32:27 -04:00
NetterSilverandClaude Haiku 5.5 abce3a718b Reject lone '-' or '"' in parse_distance instead of reading 0 (#1444)
Found while testing crates/engine/src/units.rs:107-132

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:32:21 -04:00
Kostykandkostyk348 acb28313c6 Layer Off: stay active until Enter or Esc (#1418) (#1426)
LAYOFF ended after a single pick, so turning off five layers took five command
invocations. AutoCAD's Layer Off keeps prompting: you pick object after object
and the command ends on Enter or Esc only.

`SelectRun` grows a `repeat` mode next to the existing single-pick and plain
select modes: `SelectRun::repeat(..)` acts on every pick, seeds the next prompt
straight away, and finishes on Enter (or Esc through the usual cancel path).
The non-repeating paths are untouched — a repeating run must not let one pick
end the command, so `sel.single` is disabled for it and Enter is handled before
the selection machine's own keywords.

The whole run stays a single undo step, because the command body is still
called once per pick but the running command records one step, as before.

Tests: `crates/engine/tests/layoff_repeat.rs`
  cargo test -p cadcraft-engine --test layoff_repeat   -> 4 passed
  - keeps asking until Enter, two layers off, one undo takes both back
  - Esc ends it and keeps what was already turned off
  - an empty pick ("0 found") keeps it running
  - pickfirst and JSON calls are unchanged

Co-authored-by: kostyk348 <[email protected]>
2026-10-19 02:32:14 -04:00
william-wwh 2be9d00796 fix(arc): hold Ctrl to switch the arc direction (#1422)
ARC advertised "hold Ctrl to switch direction" but the engine never saw modifier
keys: the UI dropped `mods` when building `Input::Point`. PR #407 recorded this as
a known limit.

The UI now writes `Session::ctrl_down` every frame (next to the cursor update, not
only while a command prompts, so previews see it too) and the two ARC paths read it:

- Continue: negating the start tangent makes `arc_sed` pick the mirror arc through
  the same two endpoints.
- Center,Start,End: swapping the start/end angles walks the other way around the
  same circle; its end-point prompt now carries the same Ctrl hint.

Tests: crates/engine/tests/arc_ctrl_direction.rs.
2026-10-19 02:32:08 -04:00
NetterSilverandClaude Haiku 5.5 286d3de0aa Drop minus sign from dimension text that rounds to zero (#1403)
Found while testing crates/render/src/units.rs:139-160 (format_linear, unit 3 and 4 arms) and feet_inches at :101

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:32:01 -04:00
NetterSilverandClaude Haiku 5.5 cd3e8478d6 Fix AutoLISP real printing of subnormals and mantissa round-up (#1334)
Found while testing crates/engine/src/lisp/value.rs:401-410 (real_text)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:31:56 -04:00
NetterSilverandClaude Haiku 5.5 12d0235b2c Fix table formula range shifting for one-cell and reversed ranges (#1328)
Found while testing crates/engine/src/cmd/table/formula.rs:660

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:31:50 -04:00
NetterSilverandClaude Haiku 5.5 1ac2ebaad2 Keep line and arc elevation when lengthening with LENGTHEN (#1313)
Found while testing crates/engine/src/cmd/modify2.rs:764

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:31:44 -04:00
wstockandClaude Fable 5.1 a3b3e1281f render: the even-odd fill cuts a slab at the crossings inside it (#927) (#1308)
Slabs ran between vertex rows and paired the active edges by their
order at the slab's middle, so two edges crossing inside a slab (a
bowtie, two loops crossing) were paired across the crossing and the
trapezoids covered the wrong side of it. A slab with such a crossing is
now cut again at that y and each part paired on its own, under a cut
budget so hostile input stays bounded. Tests check coverage against an
even-odd parity oracle for a bowtie, an off-centre bowtie, two crossing
loops and the plain cases; the three crossing cases fail on main.


Claude-Session: https://claude.ai/code/session_011K1peyrh5MdZ6ttHkVq8Gh

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-10-19 02:31:39 -04:00
Galeno ca5a34be12 UI: let the Chinese and Arabic language gates accept an embedded craft-fonts face (#1294)
can_show only asked the installed-font lookups for those two languages, and
both lookups hard-code None on wasm32, where there are no system fonts. The
Korean gate already falls back to a craft-fonts face (korean_font), but the
web build embeds a Jpan CJK face and an Arabic face precisely as the web's
only fonts, so a Chinese or Arabic interface could never be selected on it,
however complete the catalog; the embedded Arabic face was also never added
to the UI font families (the embedded filter only kept Jpan/Han faces).

Give both gates the embedded-face path the Korean one has:
- can_show("zh"/"ar") answers true when this build embeds a Regular face of
  Hans/Hant or Arab, in addition to an installed font.
- install_fonts picks embedded faces via embedded_ui_faces: every CJK face
  still loads in every language for CJK drawing names (#513), the face of a
  zh interface leads (a Japanese face lacks the simplified-only 图 园 测),
  and an Arabic interface appends its Arabic face.

Nothing changes for a build without CRAFT_FONTS_DIR (CRAFT_FONTS empty):
Chinese still rides on an installed CJK font and Arabic on an installed one.
2026-10-19 02:31:34 -04:00
c400d6d48c Properties: a rotation shows and is typed as the drawing measures directions (#1275)
AutoCAD's Properties shows a block reference's or text's rotation as it shows
any direction: from ANGBASE, clockwise when ANGDIR is 1 (a block turned 2.23°
shows as 87.77 in a drawing measured clockwise from north). CADCraft showed
the raw angle from +X. Properties and Quick Properties now show it that way
and read a typed rotation back the same way (`AngleSettings::shown`,
`unshown`); properties.set still takes the angle from +X counterclockwise.

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:31:29 -04:00
NetterSilverandClaude Haiku 5.5 e635248b1e Carry engineering distance rounding into the next foot (#1255)
Found while testing crates/engine/src/units.rs:14-20

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-19 02:31:24 -04:00
Marco Arnulfo 739e083f4b Drafting Settings: polar increment angle no longer shows 15 decimals (fixes #1237) (#1239) 2026-10-19 02:31:18 -04:00
3fa7275e4f DXF: $ANGBASE is in degrees (#1234)
AutoCAD writes $ANGBASE in degrees (a drawing whose angles run clockwise from
north has 90.0); CADCraft read and wrote it as radians, so such a drawing's
angle base came in as 90 radians (about 116.6 degrees), turning typed angles,
polar tracking and angles shown in Properties. The reader now converts to
radians (the variable's unit), the writer back, and the DWG reader's hand-off
of the value in DXF form gives degrees.

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:31:12 -04:00
Marco Arnulfo aba903dbb3 CLI: convert to an image warns about the entities it can't draw (#1212)
* CLI: convert to an image warns about the entities it can't draw (fixes #1208)

* CLI: the undrawn-entities warning lists its counts like the skipped-records one
2026-10-19 02:31:06 -04:00
Marco Arnulfo 493addc2dd DXF files that declare no units stay unitless when saved again (fixes #1209) (#1210) 2026-10-19 02:31:01 -04:00
Marco Arnulfo a2bee8b49e LTSCALE typed at the command line asks for the scale factor (fixes #1194) (#1199) 2026-10-19 02:30:56 -04:00
Marco Arnulfo c68420221c New metric drawings get metric Standard multileader and table styles (fixes #1171) (#1195) 2026-10-19 02:30:51 -04:00
Marco Arnulfo a5fa5ca064 Select objects accepts keywords with a leading underscore (_L, _ALL, _W…) (fixes #1172) (#1193) 2026-10-19 02:30:46 -04:00
Marco Arnulfo ef599e58e0 BREAK opens a closed polyline instead of refusing it (fixes #1173) (#1191) 2026-10-19 02:30:41 -04:00
Marco Arnulfo 27fd074f54 AutoLISP entity lists hold angles in radians, as entget does in AutoCAD (fixes #1165) (#1190) 2026-10-19 02:30:36 -04:00
Marco Arnulfo 2db6ab069a DIMRADIUS/DIMDIAMETER: a location outside the circle puts the text at that point (fixes #1170) (#1189) 2026-10-19 02:30:31 -04:00
Marco Arnulfo d33a6e634a AREA, Object: an open polyline's perimeter is its length, without the closing side (fixes #1168) (#1188) 2026-10-19 02:30:26 -04:00
Antoine Boxho 0bfe609567 Add Antoine Boxho to contributors list with GitHub sync (#1186) 2026-10-19 02:30:21 -04:00
Antoine BoxhoandClaude Fable 5.1 7e830044ab BLOCK: a keep value other than convert, retain or delete is an error (fixes #935) (#1160)
make_block erased the selected objects for every `keep` value except
"retain" and only converted them for "convert", so a misspelt value such
as "retian" removed the objects from the drawing without a reference to
the new block.

`keep` is now parsed into an enum before anything is touched; a value
that is not documented is an error naming the three accepted values. The
documented values are accepted in any case. BLOCK and -BLOCK share the
check.

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-10-19 02:30:15 -04:00
Marco Arnulfo 6546f0eecd Parameters Manager: double-click a name to rename the parameter and every expression that uses it (part of #1134) (#1142) 2026-10-19 02:30:10 -04:00
Marco Arnulfo 15b5395c06 Angular constraint between two lines holds the angle it draws, whichever way the lines run (part of #1134) (#1140) 2026-10-19 02:30:05 -04:00
Marco Arnulfo cdc61f32b5 A fixed point stays put when its grip is dragged: Fix locks the position it had before the edit (part of #1134) (#1139) 2026-10-19 02:29:59 -04:00
Marco Arnulfo d4bacce885 Tool Sets: the Parametric category offers Fix, Symmetric, the dimensional constraints and Delete Constraints (part of #1134) (#1138) 2026-10-19 02:29:54 -04:00
Marco Arnulfo 9aea9b16c4 Dynamic Input: the CIRCLE radius prompt shows one distance field, not X/Y (fixes #1135) (#1137) 2026-10-19 02:29:48 -04:00
Marco Arnulfo 9e3f584a68 Status bar toggles don't cancel the running command, as F7-F12 don't (fixes #1108) (#1111) 2026-10-19 02:29:43 -04:00
Marco Arnulfo 3bd7510f2b ARC continuation starts from the last picked end of a clockwise arc (fixes #1107) (#1110) 2026-10-19 02:29:37 -04:00
Marco Arnulfo b464a947ec MEASUREGEOM typed at the command line asks for the option, then the points (fixes #1103) (#1104) 2026-10-19 02:29:31 -04:00
Marco Arnulfo f76ca751cc Collapsed Tool Sets leave a strip on the left edge that expands them again (fixes #1095) (#1101) 2026-10-19 02:29:26 -04:00
Marco Arnulfo e0ad0ef33e DWG dimensions: text at its default position unless it was moved, and bit 32 kept (fixes #1094) (#1096) 2026-10-19 02:29:19 -04:00
56d73ceb21 Dynamic blocks: show a distance's grip only at an end an action follows, and the grips of parameters a visibility state lists (#1090)
* Dynamic blocks: a distance's grip shows only at an end an action follows

A linear parameter's grip at an end no action is attached to moves nothing,
and AutoCAD doesn't show it on the reference: a stretch that follows only the
end's change (EndXDelta, EndYDelta) leaves the base without a grip, and the
other way round. A connection to the distance itself follows both ends, as
does a distance measured from its midpoint; a parameter no action is attached
to keeps the grips the block gives it. (A block saved with one grip has no
base grip at all, which was already honoured.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic blocks: a visibility state that lists a parameter shows its grips

AutoCAD shows a parameter's grips in a visibility state that lists the
parameter, though the state doesn't list the grips themselves (a label block's
Label state lists Position1 and Distance2 but not their grips, and AutoCAD
shows the square and the arrow). A grip now shows when the state lists it or
its parameter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:29:13 -04:00
aldozarandClaude Opus 5.5 691bdbe0b8 Layouts in millimetres plot in millimetres whatever MEASUREMENT says (#1058) (#1085)
Paper-space units followed the drawing's MEASUREMENT only, so a layout
whose page setup is in millimetres (plot paper units 1), common in
drawings from AutoCAD with MEASUREMENT 0, was taken as inches: its PDF
drew everything 25.4 times too large, off the page.

PageSetup gains `paper_mm`, read from LAYOUT group 72 = 1; 72 = 0 still
leaves the units to MEASUREMENT, since earlier CADCraft versions wrote 0
for every layout. The layout's sheet, its PDF/raster plots, PREVIEW and
the pens of what its viewports show use the layout's units, and the
writer stores 72 = 1 for layouts in millimetres (it wrote 0 always).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:29:03 -04:00
aldozarandClaude Opus 5.5 162d5c6820 DWG: entities of a second layout stay on it in AutoCAD (#1057) (#1080)
acadrust writes every paper-space entity with entity mode 1 ("paper
space"), including those of *Paper_Space0, *Paper_Space1… and relies on
each block's entity list; AutoCAD reads mode 1 as the *Paper_Space
block's, so what was drawn on a second layout (and its viewports, in
drawings from AutoCAD with several layouts) landed on the first one, and
the second stayed empty. The DWG bridge now writes those entities owned
by their block (entity mode 0 with the owner handle), as the public DWG
specification describes; the first layout's entities stay mode 1.

The io tests read CADCraft's DWG back with acadrust (a dev-dependency,
the same version as cadcraft-dwg's) to check the modes as written.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:28:58 -04:00
aldozarandClaude Opus 5.5 632c2d4f1f DIMASSOC: reference polyline vertices by segment, as AutoCAD does (#1049) (#1064)
* DIMASSOC: no standard reference to a polyline's vertex or segment (#1049)

A dimension on a polyline vertex was written with an AcDbOsnapPointRef
naming the polyline but no subentity (groups 73 and 91 both 0); AutoCAD
then resolved it to the polyline's first segment when it regenerated
the dimension, and the value changed without warning (210 became 5).
Such points (LWPOLYLINE, 3D polyline, MLINE, also as the second object
of an intersection) are now left out of the DIMASSOC object, as the
report suggests: AutoCAD sees them as non-associative and the values
stay right. CADCraft keeps every link through its own xdata, and
references to single-curve objects (lines, arcs, circles, points) are
written as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DIMASSOC: reference polyline vertices by segment, as AutoCAD does

Following the black-box observation of AutoCAD 2026 in the PR review: a
polyline vertex is referenced as an end of one of its segments,
subentity type 73 = 2 (edge) and the 1-based segment in 91 (segment k
runs from vertex k-1 to vertex k; a closed polyline's closing segment is
the last), with osnap 1 / parameter 1.0 for a segment's end and 13 / 0.0
for its start. Vertex 0 is written as the start of segment 1, vertex k
as the end of segment k, falling back to the other neighbour when that
one is an arc; a vertex between two arcs (where AutoCAD writes an angle
parameter, not yet tested) still gets no reference, nor do 3D polylines
and multilines.

Reading uses the segment and osnap for polylines: AutoCAD leaves the
reference point at 0,0, so the nearest-vertex fallback attached
AutoCAD's associative dimensions on polylines to the vertex nearest the
origin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:28:52 -04:00
aldozarandClaude Opus 5.5 f0e4fef003 AutoCAD interop: justified text, DIMPOST, current dimension style, *D block colours (#1062)
* AutoCAD interop: justified text, DIMPOST, current dimension style, *D block colours

What AutoCAD takes from CADCraft's DWG/DXF as it is:

- Justified TEXT/ATTRIB/ATTDEF (#1050): group 10 is now where the
  baseline starts, from the alignment point and the text's width, not
  the alignment point itself; AutoCAD drew centred and right-aligned
  text from DWG starting at its alignment point. A stored point close to
  CADCraft's own (AutoCAD's, exact for its fonts) is kept.
- DIMPOST (#1053) is written even when empty: the DWG bridge defaulted a
  missing one to "<>", and AutoCAD then dropped the "R" of radius
  dimensions when it regenerated them.
- The current dimension style (#1051): the DXF header now carries its
  DIM* variables (AutoCAD draws new and updated dimensions from them);
  the DWG bridge points $DIMSTYLE at the style by name (its handle was
  renumbered, so the writer fell back to Standard), and reading a DWG
  gives the current dimension and text styles their names back.
- *D blocks (#1052): lines, arrows, extension lines and text take the
  style's DIMCLRD/DIMCLRE/DIMCLRT instead of ByBlock.

#1054 (group 42 of a rotated linear dimension) was already fixed on
main by #855; acad_interop.rs keeps it covered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Test: angular dimensions store their angle in radians (group 42)

Three-point (60°, 174°) and two-line (120°) angular dimensions, read back
from the DWG as DXF. Already right on main since #855; this guards it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Justified text made here: Left Middle and Left Bottom write their baseline start too

text_insert kept a stored insertion point that was within 0.1 x an
estimated width + 0.5 x height of CADCraft's baseline start, taking it for
AutoCAD's own. The width was estimated from the alignment point's offset,
which for Left Middle is only h/2 (vertical), so a text made here, whose
stored point is the alignment point, passed and kept it: AutoCAD drew it
half a height high (Left Bottom: a third). Reported with a test by
@lee-cyrille-maskell.

A stored point equal to the alignment point is now always stale. Otherwise
the offset is split along and across the baseline: along it the same slack
as before (a tenth of the text's width plus half its height, as fonts and
their substitutes differ most in width), across it a fifth of the height.
Multiline attribute values keep the distance-only check, since their lines
are placed by the embedded MTEXT.

On 12 drawings made in AutoCAD (1,055 justified texts) the insertion points
written are the same as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-19 02:28:47 -04:00
leonardopbatista 7164b6b5b1 feat(options): save a two-click selection window preference (#1032) 2026-10-19 02:28:41 -04:00
Bihacsy László 38fdfa4ac4 i18n: add Hungarian (hu) interface translation (#1027)
A complete 1,326-entry Hungarian catalog: every key of the Ukrainian reference catalog and the
four menu headings (Méretezés, Rajzolás, Módosítás, Nézet). Written from the meaning of
CADCraft's English strings in general technical drawing vocabulary; no other product's
localization and no other catalog was used. The interface addresses the user informally;
command-line keywords, system variables and osnap tokens stay English.

- Preference::Hungarian (hu); hu-HU and hu_HU.UTF-8 select it. Counts take one form, as a
  Hungarian numeral is followed by the singular (plural_ko, plural_forms: 1).
- hu in REPORTED; tests for locales, saved preference and plurals, menu headings, a live
  switch, dialogs and the Hungarian letters (ő, ű) in the bundled fonts. No gaps are reported
  for Hungarian.
- ATTRIBUTION, README, docs/localization.md, docs/localization-parity.md,
  docs/control-protocol.md and the options doc comment.
2026-10-19 02:28:35 -04:00
Gert Pellin - GPE baa9c00fb7 SVG import: name what was left out instead of dropping it silently (#627) (#1016)
Text, raster images, <use> copies, <style> sheets and rounded rectangle
corners aren't read yet. They were dropped without a word; the reader now
counts them and adds one read note (the channel DWG reading already uses),
which OPEN echoes and returns as a warning. Content that isn't drawn (in
<defs> or hidden) isn't counted.
2026-10-19 02:28:29 -04:00
Dylan M. Taylor 0cc66ad306 ci: configure Dependabot for Cargo and GitHub Actions
Co-authored-by: Dylan M. Taylor <[email protected]>
2026-10-18 12:30:54 -06:00
Dylan M. Taylor 3370a91fe9 docs: drop references to competing commercial software (#1545) 2026-10-18 10:39:39 -04:00
Brandon ThomasandClaude Opus 5.5 b23d362f6a Release 0.9.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 21:43:25 -04:00
Brandon ThomasandClaude Opus 5.5 714111d528 Release 0.8.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 17:20:02 -04:00
skylar taylor-barrick ff6cc8b3fc Merge pull request #1518 from skylartaylor/control-input
Bound control-port input, and follow stored paths only on this computer or the drawing's share
2026-10-17 12:14:01 -06:00
skylar taylor-barrick 98d22f0c68 Build: take craft-docpath from the merged craft-libs rev
craft-libs#169 is merged, so the fork pin is no longer needed. Pinned to
storytold/craft-libs 82a24b006eefa036b43c09a67fb9a3fbd17ffe63 (main after the merge) rather than the older 12281d07,
which predates resolve_absolute and the Windows colon refusal.
2026-10-17 12:04:10 -06:00
NetterSilverandClaude Haiku 5.5 4c75b0c458 Treat polyline bulges with a sub-EPS sweep as straight segments
Found while testing crates/geom/src/curve.rs:435 (bulge_to_arc) together with crates/geom/src/lib.rs:45-48 (ccw_sweep)

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-17 04:43:01 +00:00
aiongg ba02572b31 Build: use craft-docpath from craft-libs 2026-10-17 02:20:57 +00:00
aiongg 8fe7c421ea Xrefs and data links: follow stored paths only on this computer or the drawing's share
Xref paths saved in a drawing (on open, on Reload, in the External
References list, XOPEN, nested xrefs) and table data-link paths re-read by
DATALINKUPDATE go through doc_path::resolve (craft-docpath): relative
paths resolve beside the drawing that stores them, and paths to other
computers, devices and URLs are not opened. Such an xref is Unresolved
with the reason, unless a file of its name is beside the host drawing.
Paths given to XATTACH, -XREF Path and DATALINK are used as given.

One load of xrefs reads at most 1 GB from referenced files in total.
2026-10-16 17:18:34 +00:00
aiongg 972ae7888c Close control connections on the first line that is not a request; bound idle time, writes and queued requests
A line that is not a JSON object with a string method, including an HTTP
request line, gets one error reply and the connection closes before
anything after it is read. Connections time out after 10 minutes idle or
30 seconds blocked on a write, and at most 64 requests wait for the app;
more are answered busy.
2026-10-16 16:07:25 +00:00
Dylan M. Taylor ea6d7beca2 ci: switch to shared nix workflow from craft-common-actions 2026-10-15 23:58:01 -04:00
skylar taylor-barrick 9b2308b138 Merge pull request #1382 from dylanmtaylor/ci/add-platform-checks
ci: add shared FreeBSD, Windows ARM64, and nix checks
2026-10-15 21:26:48 -06:00
Dylan M. Taylor 69fc442ea6 ci: add shared FreeBSD, Windows ARM64, and nix checks 2026-10-15 20:47:50 -04:00
Marco Arnulfo be3ce73895 fix(engine): preserve rectangle area with ortho enabled (#1117) 2026-10-15 18:34:36 -06:00
midasmatterhorn 8a2b8f4bdf io: the four symbol tables honour the same record cap as their peers
LAYER, LTYPE, STYLE and DIMSTYLE records were appended with no cap while
the VIEW, UCS and VPORT arms of the same loop guard at MAX_OBJECTS — so
a hostile DXF could grow the layer table (each record found by a linear
case-insensitive name scan) without bound. The same guard now applies to
all seven table kinds.

Behaviour is unchanged for every legal drawing: no drawing approaches a
million table records, so no regression test can reach the cap at unit
scale (the same reason the peer guards shipped without one). The
quadratic cost of the name lookups themselves is a separate, larger
change (resolving table names through a map while reading) deliberately
left to the maintainers.
2026-10-15 17:43:04 +03:00
Brandon ThomasandClaude Opus 5.5 fc4e98315a Release 0.7.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 09:34:27 -04:00
Brandon ThomasandClaude Opus 5.5 e707ab4d7c cargo fmt after the #903 merge
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 06:58:50 -04:00
8cd0d46d58 Zoom and pan regenerate in the background instead of freezing the window (#903)
* Zoom and pan regenerate in the background instead of freezing the window

A rebuild that only the view asks for (a new 2x zoom band, a pan out of the
built area) now runs on a worker thread while the canvas keeps drawing the
previous display list, scaled by the view uniform. The worker builds the list,
converts it to vertex data and creates the GPU buffers, so the frame that swaps
it in only swaps buffers. One build runs at a time; a result from an older
drawing revision is dropped. Edits, the first build and the web build (no
threads) still rebuild synchronously.

ZOOM no longer calls touch(): it changes the view, not the drawing, and the
bumped revision made every typed zoom a full blocking rebuild (wheel zoom
never did). REGEN, REGENALL and layout switches still touch.

ui.screenshot waits (up to 6 s) for a background rebuild so agents capture
the new view; ui.inspect perf reports "building".

On a hatched 12k-entity DWG (~340k primitives) the longest UI stall per zoom
went from 2-4.5 s to 26-64 ms.

Also: cargo fmt of a comment in engine/src/prompt.rs that was failing the fmt
gate on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Cancel a background rebuild when the view moves on

A view that needs a different display list now cancels the build in flight
and starts one for itself, instead of waiting for the outdated build to land
and only then starting the next. A long scroll through many zoom bands builds
only for where it stops: the list lands about one build after the last step
(2.0-2.3 s on a hatched 12k-entity DWG) instead of up to two, and an outdated
build no longer keeps a core busy.

cadcraft_render::Options gains `cancel` (an Arc<AtomicBool>); a set flag stops
the build at the next entity (block contents included) and the hatch sweep at
its next pattern line, returning a partial list the caller discards. The
canvas's Job sets its flag when dropped, so replacing or dropping a job
cancels it; a cancelled worker sends nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* cargo fmt: crates/doc/src/dynblock.rs (fails the fmt gate on main)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:58:16 -04:00
1e075f76c5 Arabic (العربية) UI translation: language switching + font fallback (#798)
* Show Thai file names and text in the interface with an installed Thai font

A drawing whose file name is Thai showed boxes in its file tab and in the
window title: the interface loaded one Latin system font (plus a CJK font for
the Chinese interface), and neither has Thai.

install_fonts now also adds an installed Thai font (Thonburi, Leelawadee UI,
Noto Sans Thai, Loma...) after the Latin one, in any interface language, since
file names and drawing text are Thai whatever the interface is in. No font is
bundled; without one installed nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Korean interface localization and Hangul font support

* Add Arabic (العربية) interface translation

A full ar.tsv catalog for the CAD interface — every menu label, tool,
palette, dialog and status message in the repo's three-column TSV
format, written from the plain meaning of the English with the
Arabic AutoCAD vocabulary its users know (أمر، إزاحة، تدوير، قص،
استدارة، طبقة…), with the six CLDR plural forms for the counts.
Registers ar in LANGUAGES with plural_arabic and the font chain
(Noto Sans Arabic first on Linux, Segoe UI/Tahoma on Windows, Geeza
Pro on macOS) so the UI families paint Arabic.

The shell itself still lays out left-to-right: egui 0.36 has no
global direction switch and no bidi, so mirroring is left for a
later pass; this PR is the catalog, the registry entry and the
fonts.

* i18n: start the Swedish (sv) interface catalog

Header only, not registered yet: the catalog is filled and the language registered in this
branch, translated from the meaning of CADCraft's English strings and reviewed by a native
Swedish speaker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n: add Swedish (sv) interface translation

A complete 1,235-entry Swedish catalog: every key of the Spanish catalog, Run Script... and the
four menu headings (Visa, Rita, Måttsättning, Ändra). Written from the meaning of CADCraft's
English strings; no other product's localisation and no other catalog was used. AI-assisted; the
terminology and the running app were reviewed by a native speaker. Command-line keywords, system
variables and osnap tokens stay English.

- Preference::Swedish (sv); sv-SE, sv-FI and sv_SE.UTF-8 select it; one|other plurals (the
  English rule).
- sv in REPORTED; tests for locales, saved preference and plurals, menu headings, a live switch,
  dialogs and the Swedish letters in the bundled fonts. No gaps are reported for Swedish.
- ATTRIBUTION, README, docs/localization.md, docs/localization-parity.md,
  docs/control-protocol.md, the options doc comment and a contributors/people.toml entry for
  @holmbom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Chanthawat Kiriyadee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: huk082 <[email protected]>
Co-authored-by: hasan-sdaif <[email protected]>
Co-authored-by: Erik Holmbom <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:54:40 -04:00
7fc29b056e i18n: add Swedish (sv) interface translation (#882)
* Show Thai file names and text in the interface with an installed Thai font

A drawing whose file name is Thai showed boxes in its file tab and in the
window title: the interface loaded one Latin system font (plus a CJK font for
the Chinese interface), and neither has Thai.

install_fonts now also adds an installed Thai font (Thonburi, Leelawadee UI,
Noto Sans Thai, Loma...) after the Latin one, in any interface language, since
file names and drawing text are Thai whatever the interface is in. No font is
bundled; without one installed nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Korean interface localization and Hangul font support

* i18n: start the Swedish (sv) interface catalog

Header only, not registered yet: the catalog is filled and the language registered in this
branch, translated from the meaning of CADCraft's English strings and reviewed by a native
Swedish speaker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n: add Swedish (sv) interface translation

A complete 1,235-entry Swedish catalog: every key of the Spanish catalog, Run Script... and the
four menu headings (Visa, Rita, Måttsättning, Ändra). Written from the meaning of CADCraft's
English strings; no other product's localisation and no other catalog was used. AI-assisted; the
terminology and the running app were reviewed by a native speaker. Command-line keywords, system
variables and osnap tokens stay English.

- Preference::Swedish (sv); sv-SE, sv-FI and sv_SE.UTF-8 select it; one|other plurals (the
  English rule).
- sv in REPORTED; tests for locales, saved preference and plurals, menu headings, a live switch,
  dialogs and the Swedish letters in the bundled fonts. No gaps are reported for Swedish.
- ATTRIBUTION, README, docs/localization.md, docs/localization-parity.md,
  docs/control-protocol.md, the options doc comment and a contributors/people.toml entry for
  @holmbom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Chanthawat Kiriyadee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: huk082 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:53:31 -04:00
aed2ae9615 Add Korean interface localization and Hangul font support (#857)
* Show Thai file names and text in the interface with an installed Thai font

A drawing whose file name is Thai showed boxes in its file tab and in the
window title: the interface loaded one Latin system font (plus a CJK font for
the Chinese interface), and neither has Thai.

install_fonts now also adds an installed Thai font (Thonburi, Leelawadee UI,
Noto Sans Thai, Loma...) after the Latin one, in any interface language, since
file names and drawing text are Thai whatever the interface is in. No font is
bundled; without one installed nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Korean interface localization and Hangul font support

---------

Co-authored-by: Chanthawat Kiriyadee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:52:26 -04:00
033ee15e01 Fix double-clicking layout viewports creating persistent selection rectangle (#830)
Double-clicking a viewport to enter MSPACE or sheet to enter PSPACE triggers a primary click on the first click that starts an idle selection window (pending_window). When the second click triggers dbl_primary, the handler executed an early return, leaving pending_window open and rendering an unwanted crossing/window rectangle across the screen. Reset pending_window and drag_window on double clicks and suppress primary click dispatch.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 06:16:24 -04:00
Brandon ThomasandClaude Opus 5.5 4a9dd31a58 Context menu test: a block reference offers both the Block Editor and REFEDIT (#818, #824)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 06:13:49 -04:00
26179f7428 Draw object transparency on screen, in exports and in plots (#764)
* Draw object transparency on screen, in exports and in plots

Transparency was read and saved (entity group 440, layer xdata, ByLayer and
ByBlock) but never drawn. Display lists now carry each object's effective
transparency (its own, its layer's, or the block reference's), and:

- the canvas (GPU and CPU paths), ui.render and PNG/SVG exports blend it;
  TRANSPARENCYDISPLAY turns it off on screen and is now on by default, as in
  AutoCAD (initial value 1);
- plots draw it only when "Plot transparency" is on: a page setup option
  (PAGESETUP `plotTransparency`, a checkbox in the Page Setup Manager and the
  Plot dialog), overridable per plot, with PLOTTRANSPARENCYOVERRIDE (0 never,
  1 the setting, 2 always). PDF gets /ExtGState alpha, PNG plots blend, SVG
  uses opacity. Plots without it are byte-identical to before.

The public DXF Reference has no plot layout flag for plot transparency, so
the option is kept in the session and in JSON, not in DXF/DWG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Transparency fixes: attributes, PDF overlaps, drag previews

- Attributes draw with their own transparency (their definition's, layer 0
  meaning the reference's layer, ByBlock the reference's) instead of the
  block reference's.
- PDF plots stroke overlapping transparent objects one by one, so they build
  up where they cross as in PNG plots; opaque output is unchanged.
- Drag and rubber-band previews follow TRANSPARENCYDISPLAY.
- Effective transparency is worked out only when it is drawn, reusing the
  layer the property lookup already found.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Transparency: one PDF stroke per transparent primitive; opaque rebuilt previews

- PDF plots never batch two transparent primitives into one path. Block and
  viewport contents share their reference's handle, so the per-object flush
  missed them; each primitive now blends on its own, as in PNG plots and on
  screen. Opaque output is unchanged.
- Previews the session rebuilds with the current properties (rubber bands,
  copies of objects) are drawn opaque again: they carry CLAYER's
  transparency, not the objects'. The GPU drag of the objects themselves
  keeps following TRANSPARENCYDISPLAY.
- Tests for attributes on a transparent reference layer, attributes without a
  definition, and the drag cache across the TRANSPARENCYDISPLAY toggle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Selection like AutoCAD: colour highlight and the Options Selection tab

Selecting or hovering an object outlined each filled primitive (TrueType
glyphs, dimension and leader arrowheads, solid hatches, wide polylines)
by the rectangle around its triangles, and dashed everything else. A
selected dimension's text became a row of dashed boxes, one per glyph,
and its closed arrowheads small rectangles.

Selected objects are now redrawn in the selection colour: lines solid,
fills filled half see-through (so the lines and text on a highlighted
hatch stay visible), and the whole object reads as selected, text and
arrowheads included. A wipeout is always outlined, since filling it would
hide the drawing under it.

The Options dialog's Selection tab is laid out as AutoCAD's, with the
settings CADCraft can act on, each one AutoCAD's variable, kept in the
user profile:

- Selection modes: noun/verb selection (PICKFIRST), Shift to add
  (PICKADD), Object grouping (PICKSTYLE bit 1, now saved in the profile).
- Selection effect color (selectionColor, an interface preference; null
  is the theme's).
- Grips: Show grips (GRIPS) and the object selection limit for display of
  grips (GRIPOBJLIMIT, 100; 0 no limit): grips are neither drawn nor
  picked beyond it.
- Selection preview (SELECTIONPREVIEW): the object under the cursor is
  highlighted when a command is active (2) and when none is (1).
- Visual Effect Settings: the selection area effect (SELECTIONAREA,
  WINDOWAREACOLOR 150, CROSSINGAREACOLOR 100, SELECTIONAREAOPACITY 25)
  and the Selection Preview Filter (PREVIEWFILTER 3: 1 objects on locked
  layers, 2 xrefs, 4 tables, 8 multiline text, 16 hatches, 32 groups).

As in AutoCAD these are typed, not on the dialog: HIGHLIGHT (0 shows only
the grips of selected objects; not saved, so every session starts
highlighted), SELECTIONEFFECT (1 the selection colour, 0 dashed lines with
fills outlined along their real boundary) and PREVIEWEFFECT (the preview
dashed 0, thicker 1 or both 2).

Left for later, as CADCraft lacks what they control: lasso, grip tips and
menus, group grips, grips within blocks, associative hatch selection,
command and property preview, PICKDRAG, PICKAUTO and PROPOBJLIMIT.

DisplayList::fill_outlines returns the boundary of the region a filled
primitive covers as closed polylines (edges only one triangle has; the
slab filler's horizontal cuts, which need not line up between trapezoids,
are split at every x on their line and kept where an odd number cover
them), falling back to the bounding box over 600,000 vertices. The GPU
and CPU highlight paths and the drawing comparison overlay share the same
looks.

The new labels have Ukrainian rows (the required catalog); other
languages fall back to English.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: EP995LAB <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:12:48 -04:00
261d46adcf Selection like AutoCAD: colour highlight and the Options Selection tab (#808)
Selecting or hovering an object outlined each filled primitive (TrueType
glyphs, dimension and leader arrowheads, solid hatches, wide polylines)
by the rectangle around its triangles, and dashed everything else. A
selected dimension's text became a row of dashed boxes, one per glyph,
and its closed arrowheads small rectangles.

Selected objects are now redrawn in the selection colour: lines solid,
fills filled half see-through (so the lines and text on a highlighted
hatch stay visible), and the whole object reads as selected, text and
arrowheads included. A wipeout is always outlined, since filling it would
hide the drawing under it.

The Options dialog's Selection tab is laid out as AutoCAD's, with the
settings CADCraft can act on, each one AutoCAD's variable, kept in the
user profile:

- Selection modes: noun/verb selection (PICKFIRST), Shift to add
  (PICKADD), Object grouping (PICKSTYLE bit 1, now saved in the profile).
- Selection effect color (selectionColor, an interface preference; null
  is the theme's).
- Grips: Show grips (GRIPS) and the object selection limit for display of
  grips (GRIPOBJLIMIT, 100; 0 no limit): grips are neither drawn nor
  picked beyond it.
- Selection preview (SELECTIONPREVIEW): the object under the cursor is
  highlighted when a command is active (2) and when none is (1).
- Visual Effect Settings: the selection area effect (SELECTIONAREA,
  WINDOWAREACOLOR 150, CROSSINGAREACOLOR 100, SELECTIONAREAOPACITY 25)
  and the Selection Preview Filter (PREVIEWFILTER 3: 1 objects on locked
  layers, 2 xrefs, 4 tables, 8 multiline text, 16 hatches, 32 groups).

As in AutoCAD these are typed, not on the dialog: HIGHLIGHT (0 shows only
the grips of selected objects; not saved, so every session starts
highlighted), SELECTIONEFFECT (1 the selection colour, 0 dashed lines with
fills outlined along their real boundary) and PREVIEWEFFECT (the preview
dashed 0, thicker 1 or both 2).

Left for later, as CADCraft lacks what they control: lasso, grip tips and
menus, group grips, grips within blocks, associative hatch selection,
command and property preview, PICKDRAG, PICKAUTO and PROPOBJLIMIT.

DisplayList::fill_outlines returns the boundary of the region a filled
primitive covers as closed polylines (edges only one triangle has; the
slab filler's horizontal cuts, which need not line up between trapezoids,
are split at every x on their line and kept where an odd number cover
them), falling back to the bounding box over 600,000 vertices. The GPU
and CPU highlight paths and the drawing comparison overlay share the same
looks.

The new labels have Ukrainian rows (the required catalog); other
languages fall back to English.

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:09:39 -04:00
e74b276dfd In-place MTEXT editor with formatting toolbar and indent/tab ruler (#532) (#792)
The MTEXT text entry opens a text box on the canvas at the text's location and
width instead of a dialog: font, height, bold, italic, underline, overline,
colour, paragraph alignment, lists, tab and special characters, plus a ruler for
the paragraph's indents and tab stops. Text, per-character formats and paragraph
properties live in engine::mtext_edit (parse and write MTEXT codes, opaque codes
kept verbatim), tested headlessly.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:07:55 -04:00
d826450e03 Block Editor on the current drawing; a drawing with authoring elements offers it (stacked on #833) (#885)
* Block Editor: BEDIT, BSAVE, BSAVEAS and BCLOSE for static blocks

BEDIT opens a block definition in the drawing's own tab with its base point
at the origin, and the block's objects are edited with the ordinary commands.
BSAVE writes them back into the definition, so every reference in the drawing
updates (one undo step in the drawing); BSAVEAS saves under a new name;
BCLOSE goes back to the drawing, asking whether to save unsaved changes.

- The drawing waits untouched while the editor is open (blockedit.rs): its
  undo history, selection and views come back on BCLOSE. Objects left
  unchanged are saved back exactly, so no coordinate drifts.
- Files save the drawing outside the editor; autosave keeps the editor's
  unsaved changes in the block; the close/quit prompt's Save puts them into
  the block first.
- Right-click a selected block reference: Block Editor. In the editor the
  canvas is tinted, the base point is marked, and a bar offers Save Block,
  Save Block As and Close Block Editor (also in the right-click menu). The
  Block tool set's Block Editor button is now live. BLOCKEDITOR sysvar.
- Layout and paper-space commands are refused while the editor is open; a
  block can't be saved to contain a reference to itself.
- Dynamic blocks: their data is kept; the editor says it can't edit their
  parameters yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit Block Definition dialog; BEDIT can start a new block

BEDIT typed or started from a menu or the Tool Sets with no block reference
selected opens the Edit Block Definition dialog: the drawing's blocks sorted
by name, a preview and the description. OK opens the Block Editor on the
block named; a name no block has yet starts a new block, which BSAVE creates
(`bedit {name, create: true}`). A selected block reference still opens at
once, and JSON calls never open the dialog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit Block Definition: centred window, list box; gaps.md F3

The dialog opens centred on the window, the blocks are a full-width list
in a list box of fixed height, and gaps.md F3 mentions the dialog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* BEDIT: find dynamic block data on the block's BLOCK_RECORD

A dynamic block's ACAD_ENHANCEDBLOCK dictionary hangs off its BLOCK_RECORD
table entry, not the BLOCK entity, so the "parameters are kept" note never
showed for AutoCAD files. Regression test with the data laid out as an
AutoCAD DXF has it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* BEDIT: a dynamic block reference opens its dynamic block

A dynamic block reference with values of its own shows an anonymous block
(`*U12`), so the right-click Block Editor (and BEDIT on a picked or selected
reference) refused it and asked for a name. The anonymous block's record
names its dynamic block in AcDbBlockRepBTag xdata; BEDIT now opens that, as
AutoCAD does. Regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Block Editor on the current drawing; opening a drawing with authoring elements offers it

A dynamic block's own drawing (model space with authoring elements: its
block record's ACAD_ENHANCEDBLOCK) opened from the UI asks, as AutoCAD does,
"<file> contains authoring elements. Open in Block Editor?" Yes / No /
Cancel. Yes opens the Block Editor on <Current Drawing>: the drawing's own
objects, edited where they are; BSAVE keeps them, BCLOSE without saving puts
the drawing back. <Current Drawing> heads the Edit Block Definition list.
BSAVEAS is not available there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:02:48 -04:00
Brandon ThomasandClaude Opus 5.5 abe352564e docs: drop stale duplicate rows merges brought back (dynamic block data, foreign xdata, hatch)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 06:01:02 -04:00
Brandon ThomasandClaude Opus 5.5 d80920cc25 docs: drop stale F1, F2 and F13 rows a merge brought back
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 06:00:42 -04:00
43972c82e8 Edit Block Definition dialog; BEDIT can start a new block (stacked on #824) (#833)
* Block Editor: BEDIT, BSAVE, BSAVEAS and BCLOSE for static blocks

BEDIT opens a block definition in the drawing's own tab with its base point
at the origin, and the block's objects are edited with the ordinary commands.
BSAVE writes them back into the definition, so every reference in the drawing
updates (one undo step in the drawing); BSAVEAS saves under a new name;
BCLOSE goes back to the drawing, asking whether to save unsaved changes.

- The drawing waits untouched while the editor is open (blockedit.rs): its
  undo history, selection and views come back on BCLOSE. Objects left
  unchanged are saved back exactly, so no coordinate drifts.
- Files save the drawing outside the editor; autosave keeps the editor's
  unsaved changes in the block; the close/quit prompt's Save puts them into
  the block first.
- Right-click a selected block reference: Block Editor. In the editor the
  canvas is tinted, the base point is marked, and a bar offers Save Block,
  Save Block As and Close Block Editor (also in the right-click menu). The
  Block tool set's Block Editor button is now live. BLOCKEDITOR sysvar.
- Layout and paper-space commands are refused while the editor is open; a
  block can't be saved to contain a reference to itself.
- Dynamic blocks: their data is kept; the editor says it can't edit their
  parameters yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit Block Definition dialog; BEDIT can start a new block

BEDIT typed or started from a menu or the Tool Sets with no block reference
selected opens the Edit Block Definition dialog: the drawing's blocks sorted
by name, a preview and the description. OK opens the Block Editor on the
block named; a name no block has yet starts a new block, which BSAVE creates
(`bedit {name, create: true}`). A selected block reference still opens at
once, and JSON calls never open the dialog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Edit Block Definition: centred window, list box; gaps.md F3

The dialog opens centred on the window, the blocks are a full-width list
in a list box of fixed height, and gaps.md F3 mentions the dialog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* BEDIT: find dynamic block data on the block's BLOCK_RECORD

A dynamic block's ACAD_ENHANCEDBLOCK dictionary hangs off its BLOCK_RECORD
table entry, not the BLOCK entity, so the "parameters are kept" note never
showed for AutoCAD files. Regression test with the data laid out as an
AutoCAD DXF has it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* BEDIT: a dynamic block reference opens its dynamic block

A dynamic block reference with values of its own shows an anonymous block
(`*U12`), so the right-click Block Editor (and BEDIT on a picked or selected
reference) refused it and asked for a name. The anonymous block's record
names its dynamic block in AcDbBlockRepBTag xdata; BEDIT now opens that, as
AutoCAD does. Regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 06:00:15 -04:00
767576ec9e Block Editor: BEDIT, BSAVE, BSAVEAS and BCLOSE for static blocks (#824)
* Block Editor: BEDIT, BSAVE, BSAVEAS and BCLOSE for static blocks

BEDIT opens a block definition in the drawing's own tab with its base point
at the origin, and the block's objects are edited with the ordinary commands.
BSAVE writes them back into the definition, so every reference in the drawing
updates (one undo step in the drawing); BSAVEAS saves under a new name;
BCLOSE goes back to the drawing, asking whether to save unsaved changes.

- The drawing waits untouched while the editor is open (blockedit.rs): its
  undo history, selection and views come back on BCLOSE. Objects left
  unchanged are saved back exactly, so no coordinate drifts.
- Files save the drawing outside the editor; autosave keeps the editor's
  unsaved changes in the block; the close/quit prompt's Save puts them into
  the block first.
- Right-click a selected block reference: Block Editor. In the editor the
  canvas is tinted, the base point is marked, and a bar offers Save Block,
  Save Block As and Close Block Editor (also in the right-click menu). The
  Block tool set's Block Editor button is now live. BLOCKEDITOR sysvar.
- Layout and paper-space commands are refused while the editor is open; a
  block can't be saved to contain a reference to itself.
- Dynamic blocks: their data is kept; the editor says it can't edit their
  parameters yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* BEDIT: find dynamic block data on the block's BLOCK_RECORD

A dynamic block's ACAD_ENHANCEDBLOCK dictionary hangs off its BLOCK_RECORD
table entry, not the BLOCK entity, so the "parameters are kept" note never
showed for AutoCAD files. Regression test with the data laid out as an
AutoCAD DXF has it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* BEDIT: a dynamic block reference opens its dynamic block

A dynamic block reference with values of its own shows an anonymous block
(`*U12`), so the right-click Block Editor (and BEDIT on a picked or selected
reference) refused it and asked for a name. The anonymous block's record
names its dynamic block in AcDbBlockRepBTag xdata; BEDIT now opens that, as
AutoCAD does. Regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:58:12 -04:00
62fb5ae79a Attributes keep Verify, Preset and Lock position (stacked on #854) (#876)
* Multiline attributes: read, draw and save their text

A multiline attribute (DXF attribute type 2, or 4 for a definition) has its
text as embedded MTEXT after its own groups (`101 Embedded Object`); its own
group 1 is empty. CADCraft read only the own groups, so the attribute drew
nothing, and a save wrote it back empty: its text was lost.

- `Attrib::multiline` keeps the multiline text; `text.value` holds its plain
  text, which ATTEDIT and the other value editors change; an edited value
  replaces the contents (`Attrib::multiline_text`).
- DXF read: ATTRIB and ATTDEF split at the marker; the MTEXT parsing is
  shared with MTEXT entities (`mtext_from`).
- Drawn as multiline text; ZOOM Extents counts it.
- DXF write (2007 and later; earlier versions get one line): attribute type,
  alignment point and the embedded MTEXT, only what differs from unrotated
  text, as AutoCAD writes it.
- INSERT and ATTSYNC give references the definition's multiline text placed
  with them; MOVE/ROTATE/SCALE, Properties rotation and scale, annotative
  scaling and FLATTEN carry it.
- Tests: synthetic multiline ATTDEF and ATTRIB (read, drawn, saved, edited,
  pre-2007 save, damaged embedded groups); engine INSERT, MOVE, ATTEDIT and
  ATTSYNC.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Multiline attributes: read MTEXT direction from its own groups (#667, as #834 does)

#834 moves these lines' fix into the MTEXT reader; the same fix in the shared
mtext_from keeps the two compatible.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Attributes keep Verify, Preset and Lock position

ATTDEF/ATTRIB flags 4 (verify) and 8 (preset) and Lock position (group 280
after the tag, DXF 2007 and later) were dropped on save. Without Lock
position AutoCAD lets an attribute be dragged out of its reference, and its
dynamic block actions no longer carry it. A reference's attributes take Lock
position from their definitions, as AutoCAD saves them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:56:05 -04:00
3199de4951 Multiline attributes: read, draw and save their text (they were lost on save) (#854)
* Multiline attributes: read, draw and save their text

A multiline attribute (DXF attribute type 2, or 4 for a definition) has its
text as embedded MTEXT after its own groups (`101 Embedded Object`); its own
group 1 is empty. CADCraft read only the own groups, so the attribute drew
nothing, and a save wrote it back empty: its text was lost.

- `Attrib::multiline` keeps the multiline text; `text.value` holds its plain
  text, which ATTEDIT and the other value editors change; an edited value
  replaces the contents (`Attrib::multiline_text`).
- DXF read: ATTRIB and ATTDEF split at the marker; the MTEXT parsing is
  shared with MTEXT entities (`mtext_from`).
- Drawn as multiline text; ZOOM Extents counts it.
- DXF write (2007 and later; earlier versions get one line): attribute type,
  alignment point and the embedded MTEXT, only what differs from unrotated
  text, as AutoCAD writes it.
- INSERT and ATTSYNC give references the definition's multiline text placed
  with them; MOVE/ROTATE/SCALE, Properties rotation and scale, annotative
  scaling and FLATTEN carry it.
- Tests: synthetic multiline ATTDEF and ATTRIB (read, drawn, saved, edited,
  pre-2007 save, damaged embedded groups); engine INSERT, MOVE, ATTEDIT and
  ATTSYNC.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Multiline attributes: read MTEXT direction from its own groups (#667, as #834 does)

#834 moves these lines' fix into the MTEXT reader; the same fix in the shared
mtext_from keeps the two compatible.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:54:25 -04:00
48352f2baf Dynamic block grips: show and drag a dynamic reference's grips (stacked on #878) (#883)
* Dynamic blocks: read parameters and actions from AutoCAD files

A dynamic block's evaluation graph (kept as foreign data since #528) is read
into a typed model, `cadcraft_doc::dynblock`, without changing the kept
data: parameters (linear with value sets, point, visibility states,
lookup, base point; polar, XY, rotation, alignment and flip by geometry)
and actions (stretch with its frame and moved vertices, lookup tables;
move, scale, rotate, flip, array, polar stretch by kind), each with its
graph id and the parameters it follows.

- `blocks.dynamic {name}` returns the model as JSON (handles as hex);
  `blocks.list` marks dynamic blocks.
- Counts and values come from the file: capped by the groups present,
  non-finite numbers and missing members skipped.
- Tests: a synthetic DOOR block (visibility, linear list, stretch, lookup),
  its survival through a save, damaged data, and the engine commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: their values and custom properties

A dynamic block reference's extension dictionary says which dynamic block it
shows (AcDbBlockRepresentation ▸ AcDbRepData) and the values it was given
(AppDataCache ▸ ACAD_ENHANCEDBLOCKDATA, one XRECORD per parameter graph id).
`dynblock::reference` reads them; a reference to the dynamic block itself
has the block's values.

- `dynblock::custom_properties`: the Properties palette's Custom section, in
  parameter order, only parameters shown in Properties: visibility state,
  lookup value worked out from the lookup tables (their "no match" name, e.g.
  Custom, when the inputs match no row), distances and point positions in
  drawing units (block units × the reference's scale), with the choices of
  each (states, lookup values, a distance's list).
- Properties: a dynamic block reference shows its dynamic block's name
  instead of its anonymous block's, and a read-only Custom section.
- `blocks.reference {handle}` returns the definition, values and properties.
- Tests: synthetic references (own values, an anonymous block scaled 2, a
  width no lookup row has), survival through a save, the engine command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: change the visibility state

Choosing a visibility state (or a lookup value whose tables set only
visibility states) in Properties ▸ Custom, or `blocks.reference.set
{handle, name, value}`, changes a dynamic block reference as AutoCAD does:

- The reference gets a new anonymous block: its current one with the
  state's objects shown and the parameter's other objects hidden (matched
  to the dynamic block's objects by their AcDbBlockRepETag element tags).
  The old anonymous block goes when nothing else uses it.
- AutoCAD's link data is written: the new block's record carries
  AcDbBlockRepBTag (the dynamic block's record), copied objects keep their
  element tags, and the reference's AcDbBlockRepresentation data records the
  value (an existing value record is updated; a new one copies another
  reference's record for the same parameter when there is one).
- An attribute whose definition the state hides is written hidden (60).
- Changes CADCraft can't make yet (distances, positions, lookups that set
  them) are refused with a message and change nothing; Properties shows
  only what can change as a dropdown (`CustomProperty::editable`).
- Tests: the synthetic DOOR references (own values and an anonymous block),
  survival through a save, refusals, and the engine command with undo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: distances, positions, stretch and move actions, lookup chaining

Linear distances (snapped to their value sets) and point positions can be
changed; the stretch and move actions that follow them run (listed vertices
or whole objects, multiplier and angle offset), parameters in an action's
selection are carried along, associative hatches refill from their
stretched outlines and the reference's attributes move with their
definitions. Lookup tables run both ways (a changed input gives its table's
lookup value, which sets the other tables' inputs). Connections are read in
either group order. Checked against AutoCAD's own references (*U10, *U12).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: record changes in the history as AutoCAD does; full value data for new references

A changed reference's ACAD_ENHANCEDBLOCKHISTORY says what was done to it: a
visibility state or lookup value by property name, a distance or position as
the drag of its grips (GRIPLOC, how far each grip is from where the dynamic
block has it). A reference that had no data gets a record for everything
other references of the same dynamic block have, with its own values.
Templates come only from references of the same dynamic block; anonymous
copies have no units; boundary reactors follow the copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block history: record only the grips a change moves

AutoCAD's history holds the user's own drags; a grip that only moved with
another parameter (a stretch carrying it) gets no entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block history: a distance by name, as typed in Properties

AutoCAD records a distance typed in Properties as the parameter's name and
value in block units (1071 id, 300 Distance2, 40 40.0), replacing drags of
its grips; positions stay grip drags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: dynamic block lookup parameters keep their name and lookup action

AutoCAD writes a lookup parameter's subclass marker as
AcDbBlockLookUpParameter; the DWG bridge reads AcDbBlockLookupParameter and
matches it exactly, so the parameter's name (303) and lookup action (94)
were lost in DWG files and AutoCAD's lookups stopped working (a visibility
change no longer resized the block). The bridge DXF now uses its spelling.

Found by driving AutoCAD on CADCraft's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic blocks: carried parameter points are in a stretch frame where the block has them

AutoCAD evaluates actions from the dynamic block itself, so a parameter point
another action has moved out of a stretch frame still follows it. Testing the
current position instead changed a stretched label's width when its
visibility changed (Distance2 183.75 became 184.45; AutoCAD keeps 183.75).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block grips: show and drag a dynamic reference's grips as AutoCAD does

A selected dynamic block reference shows its grips: an arrow at each end of a
distance, a square at a position, a down-pointing triangle for a visibility
or lookup list, only those its visibility state lists. Dragging an arrow
changes the distance along the parameter (snapped to its values; a typed
number sets it), a square moves the position, a list grip offers its
choices; actions and lookups follow, with a live preview.

doc: dynblock::grips, drag_grip; grip objects by graph id.
engine: blocks.reference.grips, blocks.reference.grip, Session::start_dyn_grip.
ui: canvas dynamic grips (GRIPDYNCOLOR-like token), list popup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: read the shared DOOR fixture with LF line ends whatever the checkout gives

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic blocks: carried parameter points are in a stretch frame where the block has them

AutoCAD evaluates actions from the dynamic block itself, so a parameter point
another action has moved out of a stretch frame still follows it. Testing the
current position instead changed a stretched label's width when its
visibility changed (Distance2 183.75 became 184.45; AutoCAD keeps 183.75).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic grips: Ukrainian labels for the new commands; copy the hot grip instead of cloning

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:47:27 -04:00
0d138c2954 Dynamic block references: distances, positions, stretch and move actions, lookups both ways (stacked on #860) (#878)
* Dynamic blocks: read parameters and actions from AutoCAD files

A dynamic block's evaluation graph (kept as foreign data since #528) is read
into a typed model, `cadcraft_doc::dynblock`, without changing the kept
data: parameters (linear with value sets, point, visibility states,
lookup, base point; polar, XY, rotation, alignment and flip by geometry)
and actions (stretch with its frame and moved vertices, lookup tables;
move, scale, rotate, flip, array, polar stretch by kind), each with its
graph id and the parameters it follows.

- `blocks.dynamic {name}` returns the model as JSON (handles as hex);
  `blocks.list` marks dynamic blocks.
- Counts and values come from the file: capped by the groups present,
  non-finite numbers and missing members skipped.
- Tests: a synthetic DOOR block (visibility, linear list, stretch, lookup),
  its survival through a save, damaged data, and the engine commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: their values and custom properties

A dynamic block reference's extension dictionary says which dynamic block it
shows (AcDbBlockRepresentation ▸ AcDbRepData) and the values it was given
(AppDataCache ▸ ACAD_ENHANCEDBLOCKDATA, one XRECORD per parameter graph id).
`dynblock::reference` reads them; a reference to the dynamic block itself
has the block's values.

- `dynblock::custom_properties`: the Properties palette's Custom section, in
  parameter order, only parameters shown in Properties: visibility state,
  lookup value worked out from the lookup tables (their "no match" name, e.g.
  Custom, when the inputs match no row), distances and point positions in
  drawing units (block units × the reference's scale), with the choices of
  each (states, lookup values, a distance's list).
- Properties: a dynamic block reference shows its dynamic block's name
  instead of its anonymous block's, and a read-only Custom section.
- `blocks.reference {handle}` returns the definition, values and properties.
- Tests: synthetic references (own values, an anonymous block scaled 2, a
  width no lookup row has), survival through a save, the engine command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: change the visibility state

Choosing a visibility state (or a lookup value whose tables set only
visibility states) in Properties ▸ Custom, or `blocks.reference.set
{handle, name, value}`, changes a dynamic block reference as AutoCAD does:

- The reference gets a new anonymous block: its current one with the
  state's objects shown and the parameter's other objects hidden (matched
  to the dynamic block's objects by their AcDbBlockRepETag element tags).
  The old anonymous block goes when nothing else uses it.
- AutoCAD's link data is written: the new block's record carries
  AcDbBlockRepBTag (the dynamic block's record), copied objects keep their
  element tags, and the reference's AcDbBlockRepresentation data records the
  value (an existing value record is updated; a new one copies another
  reference's record for the same parameter when there is one).
- An attribute whose definition the state hides is written hidden (60).
- Changes CADCraft can't make yet (distances, positions, lookups that set
  them) are refused with a message and change nothing; Properties shows
  only what can change as a dropdown (`CustomProperty::editable`).
- Tests: the synthetic DOOR references (own values and an anonymous block),
  survival through a save, refusals, and the engine command with undo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: distances, positions, stretch and move actions, lookup chaining

Linear distances (snapped to their value sets) and point positions can be
changed; the stretch and move actions that follow them run (listed vertices
or whole objects, multiplier and angle offset), parameters in an action's
selection are carried along, associative hatches refill from their
stretched outlines and the reference's attributes move with their
definitions. Lookup tables run both ways (a changed input gives its table's
lookup value, which sets the other tables' inputs). Connections are read in
either group order. Checked against AutoCAD's own references (*U10, *U12).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: record changes in the history as AutoCAD does; full value data for new references

A changed reference's ACAD_ENHANCEDBLOCKHISTORY says what was done to it: a
visibility state or lookup value by property name, a distance or position as
the drag of its grips (GRIPLOC, how far each grip is from where the dynamic
block has it). A reference that had no data gets a record for everything
other references of the same dynamic block have, with its own values.
Templates come only from references of the same dynamic block; anonymous
copies have no units; boundary reactors follow the copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block history: record only the grips a change moves

AutoCAD's history holds the user's own drags; a grip that only moved with
another parameter (a stretch carrying it) gets no entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block history: a distance by name, as typed in Properties

AutoCAD records a distance typed in Properties as the parameter's name and
value in block units (1071 id, 300 Distance2, 40 40.0), replacing drags of
its grips; positions stay grip drags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: dynamic block lookup parameters keep their name and lookup action

AutoCAD writes a lookup parameter's subclass marker as
AcDbBlockLookUpParameter; the DWG bridge reads AcDbBlockLookupParameter and
matches it exactly, so the parameter's name (303) and lookup action (94)
were lost in DWG files and AutoCAD's lookups stopped working (a visibility
change no longer resized the block). The bridge DXF now uses its spelling.

Found by driving AutoCAD on CADCraft's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic blocks: carried parameter points are in a stretch frame where the block has them

AutoCAD evaluates actions from the dynamic block itself, so a parameter point
another action has moved out of a stretch frame still follows it. Testing the
current position instead changed a stretched label's width when its
visibility changed (Distance2 183.75 became 184.45; AutoCAD keeps 183.75).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:45:56 -04:00
f8521ab299 Dynamic block references: change the visibility state (stacked on #853) (#860)
* Dynamic blocks: read parameters and actions from AutoCAD files

A dynamic block's evaluation graph (kept as foreign data since #528) is read
into a typed model, `cadcraft_doc::dynblock`, without changing the kept
data: parameters (linear with value sets, point, visibility states,
lookup, base point; polar, XY, rotation, alignment and flip by geometry)
and actions (stretch with its frame and moved vertices, lookup tables;
move, scale, rotate, flip, array, polar stretch by kind), each with its
graph id and the parameters it follows.

- `blocks.dynamic {name}` returns the model as JSON (handles as hex);
  `blocks.list` marks dynamic blocks.
- Counts and values come from the file: capped by the groups present,
  non-finite numbers and missing members skipped.
- Tests: a synthetic DOOR block (visibility, linear list, stretch, lookup),
  its survival through a save, damaged data, and the engine commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: their values and custom properties

A dynamic block reference's extension dictionary says which dynamic block it
shows (AcDbBlockRepresentation ▸ AcDbRepData) and the values it was given
(AppDataCache ▸ ACAD_ENHANCEDBLOCKDATA, one XRECORD per parameter graph id).
`dynblock::reference` reads them; a reference to the dynamic block itself
has the block's values.

- `dynblock::custom_properties`: the Properties palette's Custom section, in
  parameter order, only parameters shown in Properties: visibility state,
  lookup value worked out from the lookup tables (their "no match" name, e.g.
  Custom, when the inputs match no row), distances and point positions in
  drawing units (block units × the reference's scale), with the choices of
  each (states, lookup values, a distance's list).
- Properties: a dynamic block reference shows its dynamic block's name
  instead of its anonymous block's, and a read-only Custom section.
- `blocks.reference {handle}` returns the definition, values and properties.
- Tests: synthetic references (own values, an anonymous block scaled 2, a
  width no lookup row has), survival through a save, the engine command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: change the visibility state

Choosing a visibility state (or a lookup value whose tables set only
visibility states) in Properties ▸ Custom, or `blocks.reference.set
{handle, name, value}`, changes a dynamic block reference as AutoCAD does:

- The reference gets a new anonymous block: its current one with the
  state's objects shown and the parameter's other objects hidden (matched
  to the dynamic block's objects by their AcDbBlockRepETag element tags).
  The old anonymous block goes when nothing else uses it.
- AutoCAD's link data is written: the new block's record carries
  AcDbBlockRepBTag (the dynamic block's record), copied objects keep their
  element tags, and the reference's AcDbBlockRepresentation data records the
  value (an existing value record is updated; a new one copies another
  reference's record for the same parameter when there is one).
- An attribute whose definition the state hides is written hidden (60).
- Changes CADCraft can't make yet (distances, positions, lookups that set
  them) are refused with a message and change nothing; Properties shows
  only what can change as a dropdown (`CustomProperty::editable`).
- Tests: the synthetic DOOR references (own values and an anonymous block),
  survival through a save, refusals, and the engine command with undo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: dynamic block lookup parameters keep their name and lookup action

AutoCAD writes a lookup parameter's subclass marker as
AcDbBlockLookUpParameter; the DWG bridge reads AcDbBlockLookupParameter and
matches it exactly, so the parameter's name (303) and lookup action (94)
were lost in DWG files and AutoCAD's lookups stopped working (a visibility
change no longer resized the block). The bridge DXF now uses its spelling.

Found by driving AutoCAD on CADCraft's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:44:18 -04:00
73b8edac61 Dynamic block references: custom properties in Properties (stacked on #838) (#853)
* Dynamic blocks: read parameters and actions from AutoCAD files

A dynamic block's evaluation graph (kept as foreign data since #528) is read
into a typed model, `cadcraft_doc::dynblock`, without changing the kept
data: parameters (linear with value sets, point, visibility states,
lookup, base point; polar, XY, rotation, alignment and flip by geometry)
and actions (stretch with its frame and moved vertices, lookup tables;
move, scale, rotate, flip, array, polar stretch by kind), each with its
graph id and the parameters it follows.

- `blocks.dynamic {name}` returns the model as JSON (handles as hex);
  `blocks.list` marks dynamic blocks.
- Counts and values come from the file: capped by the groups present,
  non-finite numbers and missing members skipped.
- Tests: a synthetic DOOR block (visibility, linear list, stretch, lookup),
  its survival through a save, damaged data, and the engine commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic block references: their values and custom properties

A dynamic block reference's extension dictionary says which dynamic block it
shows (AcDbBlockRepresentation ▸ AcDbRepData) and the values it was given
(AppDataCache ▸ ACAD_ENHANCEDBLOCKDATA, one XRECORD per parameter graph id).
`dynblock::reference` reads them; a reference to the dynamic block itself
has the block's values.

- `dynblock::custom_properties`: the Properties palette's Custom section, in
  parameter order, only parameters shown in Properties: visibility state,
  lookup value worked out from the lookup tables (their "no match" name, e.g.
  Custom, when the inputs match no row), distances and point positions in
  drawing units (block units × the reference's scale), with the choices of
  each (states, lookup values, a distance's list).
- Properties: a dynamic block reference shows its dynamic block's name
  instead of its anonymous block's, and a read-only Custom section.
- `blocks.reference {handle}` returns the definition, values and properties.
- Tests: synthetic references (own values, an anonymous block scaled 2, a
  width no lookup row has), survival through a save, the engine command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: dynamic block lookup parameters keep their name and lookup action

AutoCAD writes a lookup parameter's subclass marker as
AcDbBlockLookUpParameter; the DWG bridge reads AcDbBlockLookupParameter and
matches it exactly, so the parameter's name (303) and lookup action (94)
were lost in DWG files and AutoCAD's lookups stopped working (a visibility
change no longer resized the block). The bridge DXF now uses its spelling.

Found by driving AutoCAD on CADCraft's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:42:37 -04:00
fbc7037a10 Dynamic blocks: read parameters and actions from AutoCAD files (#838)
* Dynamic blocks: read parameters and actions from AutoCAD files

A dynamic block's evaluation graph (kept as foreign data since #528) is read
into a typed model, `cadcraft_doc::dynblock`, without changing the kept
data: parameters (linear with value sets, point, visibility states,
lookup, base point; polar, XY, rotation, alignment and flip by geometry)
and actions (stretch with its frame and moved vertices, lookup tables;
move, scale, rotate, flip, array, polar stretch by kind), each with its
graph id and the parameters it follows.

- `blocks.dynamic {name}` returns the model as JSON (handles as hex);
  `blocks.list` marks dynamic blocks.
- Counts and values come from the file: capped by the groups present,
  non-finite numbers and missing members skipped.
- Tests: a synthetic DOOR block (visibility, linear list, stretch, lookup),
  its survival through a save, damaged data, and the engine commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: dynamic block lookup parameters keep their name and lookup action

AutoCAD writes a lookup parameter's subclass marker as
AcDbBlockLookUpParameter; the DWG bridge reads AcDbBlockLookupParameter and
matches it exactly, so the parameter's name (303) and lookup action (94)
were lost in DWG files and AutoCAD's lookups stopped working (a visibility
change no longer resized the block). The bridge DXF now uses its spelling.

Found by driving AutoCAD on CADCraft's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dynamic blocks: a work budget on the record cursor, so counts promising missing groups can't make nested loops rescan a hostile record (with regression test)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:40:12 -04:00
e773d93164 HATCHEDIT: refuse an explicit bad scale or angle before editing anything (#724) (#777)
* HATCHEDIT: refuse an explicit bad scale or angle before editing anything (#724)

run_hatchedit read `scale` and `angle` leniently (a non-positive scale or a
non-numeric value was skipped), so such a request reported success, added an
undo step and cleared the redo history, applied its valid companion property
or recreated the boundary. HATCH already refuses a non-positive scale. The
numbers are now checked first with the same size_param rule; `angle` must be
a number; absent and null still mean "leave it".

* Docs: update the progress docs for this change

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:37:45 -04:00
a2b6c9ac4a Animation effects follow the operating system's setting; View ▸ Accessibility ▸ Animation Effects (#759)
With Windows set to show no animations (Settings ▸ Accessibility ▸ Visual
effects ▸ Animation effects), dialogs and menus still faded in and wheel
input glided. All of that motion is egui's default behaviour, and nothing
asked the operating system.

- crates/ui-egui/src/animation.rs: AnimationPref (System, On, Off). Off sets
  egui's animation_time to 0 and scroll_animation to none (window, menu,
  tooltip and popup fades, collapsing sections, scroll bars, scroll-to
  glides), hands each wheel notch to scroll areas whole, and lets
  Cmd/Ctrl+wheel zoom reach its zoom in one step.
- System, the default, follows the OS live: UISettings::AnimationsEnabled on
  Windows, NSWorkspace's Reduce motion on macOS, the XDG Desktop Portal's
  reduced-motion (then GNOME's enable-animations) on Linux and the BSDs,
  prefers-reduced-motion on the web.
- View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting / On / Off,
  the same choice in Options ▸ Display, and `ui.animations`, `options` and
  `ui.set` {"animations"}; `ui.inspect` reports whether animations show.

Drafting behaviour is untouched: tracking's acquisition pause, the
time-sensitive right-click, previews, the caret blink, realtime pan and
zoom. Plain wheel zoom already moved a whole notch per frame (#692).

macOS and Linux are compile-checked (clippy -D warnings for
aarch64-apple-darwin and x86_64-unknown-linux-gnu), not run.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:34:56 -04:00
8abc0909f3 MCP: render one area of the drawing, and read its texts (find_text) (#757)
A render of a large drawing (a set of sheets in model space) fits every
sheet in one image, too small to read. `render` takes `window`
[[x0,y0],[x1,y1]]: just that area, 1600 px wide with the window's shape
unless sized (the app's and the headless `ui.render` both; the display list
is built for that view only). `View::of_window` sizes it.

`find_text` (engine command `texts`, read-only) returns the readable text of
TEXT, MTEXT (formatting removed), block attributes and multileaders with
insertion point, height, rotation, style, layer and handle, filtered by
content, layer and a window. FIND selects and can replace; this only
reports, so an agent can find room names, sheet numbers and titles without
reading all the geometry.

On a 39,600-object permit set: 5,861 texts in 0.02 s; one 90 x 59.4 sheet
rendered at 2400 x 1584 in 0.5 s.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:34:34 -04:00
8166e4a809 AutoLISP: load and run .lsp routines (fixes #758) (#855)
* AutoLISP: load and run .lsp routines (#758)

CADCraft runs AutoLISP routines. `.lsp` files load with APPLOAD, (load)
or by dropping them on the window, and at startup from the support folder
(acad.lsp once per session or per drawing with ACADLSPASDOC, acaddoc.lsp
per drawing, then S::STARTUP; never from a drawing's own folder).
(defun c:NAME …) defines commands, (autoload) defers loading to first
use, and (expression) and !variable work at the command line and at
prompts. docs/autolisp.md lists what is supported.

The interpreter (crates/engine/src/lisp) reads source with its own
stack and evaluates on an explicit-stack machine, so a routine can stop
for input (getpoint, pause in command) and carry on later on one thread,
deep recursion is an error rather than a crash, and long loops run a
slice per frame (Esc stops them). It follows AutoLISP: 32-bit wrapping
integers, dynamic scope, *error*, vl-catch-all-apply, AutoLISP's error
wording. About 200 built-ins cover the language, command (with pause and
commands left open), entity lists (entget/entmake/entmod/entdel/entlast/
entnext/handent, through the DXF reader and writer's groups, exposed by
cadcraft-io and handed to the engine through a hook), ssget with modes
and filters, tables, system variables, get… input with initget, and
units. A routine is one undo step; each drawing has its own symbols.

Also: keywords typed as _KEYWORD match at prompts; TEXT run by a
routine's command takes one line; DIMENSION records carry their
measurement (42); Prompt::raw shows a get… prompt as written; the
interface asks Session::prompting() (a command's or a routine's prompt)
where it asked whether a command runs, so clicks, right-click and Delete
work at a routine's prompts; getcorner and based get… prompts drag a
rubber band.

Tests: the language, errors, startup files, interactive input, hostile
input (lisp/tests.rs); the #648 corpus, 18/18, when CADCRAFT_LISP_CORPUS
points at it (tests/lisp_corpus.rs); drop, frames and canvas clicks in
the app (ui-egui/tests/lisp_files.rs).

* AutoLISP: bound memory, drop nested values iteratively, guard the per-frame tick

- Cons cells drop with a work list over both car and cdr (and function
  bodies), so a list nested a million deep in its car no longer overflows
  the stack when it goes away.
- Memory caps so a runaway routine fails with a LISP error instead of an
  uncatchable out-of-memory abort: at most 5,000,000 live cons cells
  (counted in Value::cons / Drop, checked every step; cells the drawing's
  variables already held at the run's start don't count against it), no
  string a built-in makes longer than 8 MiB (strcat checks before joining,
  printed text is cut), and a 2 GiB per-run budget for new strings,
  printed text and files read.
- Session::lisp_tick runs under catch_unwind, and so does every slice of
  the LISP machine: a panic ends the routine with "internal error", puts
  the drawing back and leaves the session usable.
- Regression tests for each (deep car nesting, nested functions, the cell
  cap, string length and budget, a panicking built-in in a blocking run
  and in a ticked one).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:33:57 -04:00
dc92f38772 DXF: count the records the reader can't place; info reports them, convert warns (part of #865) (#872)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:31:58 -04:00
1c4d0a543f Open damaged DWGs partially and say what was left out (#800) (#859)
Bump acadrust to 0.6.4 and read DWG in its failsafe mode: an object
record the reader can't decode is skipped instead of failing the whole
file. The drawing's new read_notes (never saved) say how many records
were left out and of which types; OPEN echoes them, returns them as
`warnings`, and the app shows the first in the status bar. A file whose
objects stream can't be read at all is still an error.

acadrust 0.6.4 writes a merged table cell's anchor with 173=0 and the
span, so the DXF reader now takes a merge from the span alone. Unknown
records the DWG writer can't write back are dropped before writing.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:30:18 -04:00
Brandon ThomasandClaude Opus 5.5 ef9898d57f zh: drop two duplicate rows left by merging #870 and #884
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 05:29:13 -04:00
33fe98a6dc Update Chinese translations in zh.tsv (#884)
* Add Chinese language support to preferences

* Add Chinese language support to preferences

* Chinese: register it as a reported language and draw it with an installed CJK font

The catalog didn't compile (Self::SimplifiedChinese) and egui's bundled
fonts have no Chinese glyphs, so the interface would have shown boxes.
Fonts are never bundled: the interface now looks for an installed CJK
font (PingFang, Microsoft YaHei, Noto Sans CJK, WenQuanYi...) and adds it
after the Latin fonts when Chinese is shown. Without one the interface
stays in English and says why. ATTRIBUTION row; language lists updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Update Chinese translations in zh.tsv

* zh: drop a stray 外形 from the array limit message

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:24:22 -04:00
5630529464 Properties palette: numeric fields take feet and inches, show lengths in the drawing's units, and report what they can't read (fixes #849) (#870)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:23:59 -04:00
3b16f2d516 Engine: run the post-command passes from one place (#856)
`execute` and the interactive `finish` each called the group, constraint and
associativity passes in sequence, with slightly different arguments. They now
both call `Session::after_command(before, uid, ok)`, which lists the passes
once, so a pass cannot be added on one path and missed on the other. The
arguments each path passed are unchanged: `execute` passes the document uid and
`undoable && ok`; `finish` passes no uid and `true`.

tests/post_command_passes.rs pins that MOVE and ERASE, run through `execute`
and typed, prune groups, purge/re-solve constraints and update an associative
hatch identically, in one undo step that undo fully reverses.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:23:39 -04:00
2f5bbbd68d doc: Space::tab_name / layout / is_paper replace repeated hand-written matches (#888)
* doc: Space::is_paper/layout/tab_name helpers replace hand-written matches

Twenty-seven call sites in 15 files across engine, io and ui-egui matched Space by hand to get
"is this a layout", "which layout" or "Model or the layout's name". Route them
through three small helpers on Space instead. No behaviour change.

This also makes adding a space kind a few-file change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* doc: keep Space::Model comparisons that no helper shortens; test the helpers

Only the sites that repeated the same match (tab name, layout name,
paper lineweights) go through the helpers; plain Model comparisons and
plot_window's match on (space, plotArea) stay as they were.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:21:19 -04:00
76b0ef8897 Select: pick a solid hatch inside its fill, islands left out, not its bounding rectangle (follow-up to #747) (#763)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:20:39 -04:00
966356545d ACAD_TABLE from other writers: keep style text height, read cell text height, lay out cell text as MTEXT (#802) (#806)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:18:23 -04:00
4257674dfa Fix polyline offset arc bulge after joining moved endpoints (#817) (#825)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:17:25 -04:00
64b7825d08 Property-based and hostile-input tests for geometry numerics (gaps.md S6) (#733)
* Property-based and hostile-input tests for geometry numerics (gaps.md S6)

A deterministic xorshift64* generator (no new dependency) drives a few
thousand cases per property in crates/geom/src/property_tests.rs:

- line/line: hits lie on both lines, parameters reproduce the point,
  swapping the operands gives the same point, finite results agree with
  the infinite parameters
- line/circle and circle/circle: hits lie on both curves, results are
  symmetric, properly crossing circles match the closed form; hostile
  inputs (NaN, infinities, subnormals, raw bit patterns, 1e300) never
  panic and the guarded functions return only finite hits or none
- segments: extending only adds hits
- closest points: fixed point of closest, perpendicular inside the
  segment, endpoints outside
- arcs: at(0)/at(1) are the endpoints at radii from 1e-6 to 1e6; the
  three-point arc keeps {start, end} = {p1, p3} and contains p2 (the
  CCW-only storage swaps the pair when p2 is on the clockwise side, as
  DXF stores arcs) and matches the circumradius closed form; collinear
  inputs are rejected
- bounds and vector identities
- known answers at 1e6-1e7 coordinates hold to 1e-9 relative

gaps.md S6 removed and geometry-parity.md's Tests section updated in
the same change.

* docs: drop the sentence the new numerics tests make stale

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:16:44 -04:00
d2a9159e51 PDFBOOK: plot sheet frames in model space into one PDF per row of frames (#896)
* PDFBOOK: plot sheet frames in model space into one PDF per row of frames

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* PDFBOOK: no Cmd+Shift+P shortcut (AutoCAD's Quick Properties toggle); simpler uk label

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: simanov <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:15:56 -04:00
678ff555ae MTEXT: paragraph indents and tab stops are in drawing units (#895)
* MTEXT: paragraph indents and tab stops are in drawing units

AutoCAD writes \pi, \pl, \pr and tab stops in drawing units, not multiples of the text
height. A file with \pi27.485 on 6-high text in a 120-wide box laid out with a 165-unit first
line indent: the first line vanished and wrapped words landed elsewhere. The JSON mtext
parameters indent, firstIndent, rightIndent and tabs follow (a list's default indent is now
3 text heights, in drawing units).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* MTEXT editor: list indent of three text heights in drawing units, matching the new \p units

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: simanov <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:13:16 -04:00
d0438577ed Fonts: use the TrueType typeface from a style's xdata and find families by first word (#894)
AutoCAD stores a TrueType text style's family (e.g. "GOST type A") in the style's ACAD xdata
and leaves the font file name empty. Styles without a file now take that family.

Family-name lookups also look in files whose name starts with the family's first word, so
"GOST type A" finds GOST.TTF (the stem shares only 4 characters with the family name).

Co-authored-by: simanov <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 05:12:33 -04:00
63b448bee9 Extents: count the visible attributes of a reference to a missing block (fixes #707) (#746)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:12:00 -04:00
7b767ddab9 Plot: model-space PNG and SVG plots honour fit: false without a scale, at 1:1 like PDF (fixes #713) (#744)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:10:52 -04:00
79efd97515 MTEXT: annotative scaling and SCALE on multileader text scale the text width and columns too (fixes #708, fixes #709) (#743)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:10:24 -04:00
cddcbe7a2a Dimensions: a jogged radius with a NaN or infinite radius draws no lines instead of panicking (fixes #712) (#742)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:09:44 -04:00
b209bb53e9 Geometry: param_at_length checks spline validity before clamping to the domain (fixes #704) (#741)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:09:01 -04:00
5d39f8710c HATCHEDIT: choosing SOLID on a gradient hatch makes it a plain solid fill (fixes #721) (#740)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:07:46 -04:00
6394c7c6f3 JOIN: an elliptical arc named twice is one object, so the joined result stays (fixes #725) (#739)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:07:02 -04:00
2483993218 HATCH: a pattern name with no definition is refused instead of drawn as ANSI31 (fixes #722) (#736)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:06:15 -04:00
cc57dff527 POLYGON: a typed radius of zero or less, or a radius point on the centre, is refused and asked again (fixes #720) (#735)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:05:37 -04:00
724c18c6af Constraint point names: s2 names segment 2, as documented (fixes #710) (#734)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:04:26 -04:00
8e0b867f6c BREAK, BREAKATPOINT and JOIN: leave objects on locked layers alone (fixes #727) (#730)
BREAK and BREAKATPOINT (break_entity) and line/arc/polyline JOIN
(modify::join) removed their source objects and added replacements
without checking the source layer's lock, so a locked line could be cut
or merged into a polyline. ERASE, MOVE, TRIM, FILLET, EXPLODE and the
ellipse/spline JOIN already guard against this.

Both now refuse with the same errors the sibling commands use:
"The object is on a locked layer." (BREAK, BREAKATPOINT, like FILLET)
and "An object is on a locked layer." (JOIN, like the ellipse/spline
join). JOIN refuses the whole request when any selected object is
locked, so a mixed-layer pair keeps its locked original in either
order. The guards sit in the shared functions, so JSON calls with
explicit handles or the selection, the interactive prompts and the
command line all reach them. The interactive commands report the
refusal on the command line.

Tests (crates/engine/tests/break_join_locked_layers.rs, red before the
fix): BREAK and BREAKATPOINT on a locked line by handle and by
selection; BREAK on a locked arc and circle; JOIN of locked lines and
of a locked/unlocked pair in both orders; interactive BREAK and JOIN.
Each checks the drawing is unchanged while locked, and that the same
edit works unlocked (BREAK also undoes and redoes).

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:03:16 -04:00
36f938e90a Performance: restrict object-snap intersections to cursor aperture (#701)
* Snap: pin finite and apparent intersection behavior

* Snap: skip finite intersections outside the aperture

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 05:02:28 -04:00
Brandon ThomasandClaude Opus 5.5 636b041a4e DXF writer: resolve the #827/#871 merge (W keeps both the layer handles and the hatch reactors)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 04:51:37 -04:00
Brandon ThomasandClaude Opus 5.5 bb7e1046be docs: gaps F1/F2 rows after the STRETCH and REFEDIT merges (one row each)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 04:47:56 -04:00
f807e65e30 STRETCH: polygon and fence selection (#892)
At "Select objects", CP and WP take a polygon (Enter closes it) whose
inside marks the vertices that move, as a crossing window does; F takes a
fence, and what it crosses moves whole, like objects picked one at a
time. BOX works too, Undo takes back the last point, and the polygon or
fence is drawn while its points are placed.

The JSON form takes `polygon` or `fence` in place of `window`; both are
capped at the selection modes' point limit and refuse non-finite points.

Co-authored-by: Chanthawat Kiriyadee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 04:47:19 -04:00
69f2b9724a Save xref layer overrides with the host, in DXF and DWG (fixes #886) (#889)
A colour or freeze set in the host on an xref's layers (xref|layer) was lost on save:
the saved view dropped every xref-dependent symbol, layers included, and the DWG save goes
through the same DXF tags. The reader already keeps such layers when the xref loads.

The xref's layers are now written as xref-dependent LAYER records (DXF Reference, LAYER
group 70: 16 externally dependent, 32 resolved), as AutoCAD does with VISRETAIN = 1, with
the xref linetypes they use (same flags): without them a DWG falls back to Continuous.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:46:45 -04:00
28b8160407 DXF: associative hatches in blocks keep their boundary; boundaries carry the hatch reactor (#871)
A hatch inside a block was written with no source objects (the writer looked
for them in model and paper space only), and no boundary object carried the
hatch as a persistent reactor. AutoCAD keeps the two linked both ways; without
it a stretched dynamic block in AutoCAD moved the outline but not the fill.

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 04:46:29 -04:00
5b037b8f92 DXF: write viewport frozen layers as group 341 layer handles too (#827)
A layout VIEWPORT's frozen layers were saved only as CADCraft's own
1001 CADCRAFT / 1000 VPFROZEN xdata. Other programs ignore that, so in
any third-party viewer every viewport showed every layer.

The writer now also emits the standard group 341: one soft pointer per
frozen layer to its LAYER table record handle, after 90/340 and before
the xdata. A frozen name with no LAYER record is skipped for 341 only
(the xdata still carries it). The reader keeps preferring the xdata; a
VIEWPORT without it (a file from another program) resolves its 341
handles through the LAYER records' group-5 handles, ignoring unknown
handles and keeping the 341 order.

Not covered: the DXF-to-DWG converter does not carry group 341 yet, so
a DWG keeps per-viewport freezing only through the CADCraft xdata.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 04:46:15 -04:00
5fd23f75fc Command line: a bare system variable name runs SETVAR on it (part of U10) (#799)
* Command line: a bare system variable name runs SETVAR on it (part of U10)

Typing ORTHOMODE, PICKADD and the like at the command line returned
"unknown command". Session::start now falls back to SETVAR with the name
already entered when the text is not a command but is a known variable;
dash, dot and underscore prefixes never mean a variable, and real
commands still win. Read-only variables print their value, and the
transparent form ('OSMODE) resumes the interrupted command.

Checked: fmt, clippy, test, assets, layers and wasm pass; also driven
through the control channel in the running app.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Tests: every variable name, command collisions and hostile input for bare SETVAR

Covers each variable SETVAR lists: a name that is not a command starts SETVAR
(or prints a read-only value), a name that is also a command keeps the command,
and odd input (lone apostrophes, NUL, wide characters, a 1 MiB name) never
panics and leaves the session usable. Disabling the fix makes all three new
and old tests fail.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
2026-10-13 04:46:00 -04:00
a6200fa34f i18n(pt-BR): complete the Brazilian Portuguese catalog (#791)
Add the 238 rows that still fell back to English, taking the catalog to
1,231 rows: it now covers the reference catalog and every marked UI
literal (commands, menus, tool groups and tooltips, object snaps,
drafting prompts, dialogs and Preferences), so the i18n tests report no
remaining gaps for pt-BR.

The translations follow the terminology already used in the catalog
(cota, hachura, camada, pinça, janela gráfica, referência a objetos) and
preserve placeholders ({n}, {name}) and trailing ellipses exactly.

Also add a bundled-font glyph test for the catalog's accented letters,
mirroring the German and Ukrainian ones, and record the completion in
docs/localization-parity.md (status line and revision history) and
docs/localization.md.

Written from CADCraft's English strings; no proprietary localization
resources were copied.

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:45:43 -04:00
25e4900fcd Recent files: the Start page and File ▸ Open Recent list the drawings opened last (fixes #858) (#864)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:44:44 -04:00
4efb01332e Canvas: every click places a point while drawing, however fast (fixes #815) (#835)
Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:42:53 -04:00
mattlafyandClaude Opus 5.5 d134079f11 Xdata travels with its object: COPY, MIRROR, ARRAY and paste keep it (#890)
Other applications' xdata on an entity was kept beside the drawing,
keyed by handle, so a copy (new handle) lost it: a copied hyperlink
(PE_URL) had no link, third-party tags stayed on the original only.
In AutoCAD xdata is part of the object.

Move entity xdata onto the entity as Common::xdata (the same raw
groups); every copy path already clones Common. The DXF reader puts it
there (handle references still noted for remapping), the writer takes
it from the entity, PDF hyperlinks come from the entities. EXPLODE's
pieces of an object don't inherit its xdata. Table record and block
xdata stay in Foreign.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:38:34 -04:00
ZaxaerithandZaxaerith 591692a264 docs: clarify engine commands in control protocol (#845) (#873)
Co-authored-by: Zaxaerith <[email protected]>
2026-10-13 04:38:29 -04:00
Marco Arnulfo 50246683c3 DXF: read every ENTITIES section, not only the last (fixes #865) (#869) 2026-10-13 04:38:24 -04:00
Marco Arnulfo 2effc8bf3e Double-click on text, mtext or an attribute definition starts TEXTEDIT on it (part of #842) (#868) 2026-10-13 04:38:18 -04:00
Marco Arnulfo 5b0238fc26 Dynamic Input and grip fields show distances in the drawing's UNITS (fixes #841) (#867) 2026-10-13 04:38:13 -04:00
Marco Arnulfo 7b723b7bc0 Viewport scale list: add engineering scales for imperial drawings (fixes #851) (#866) 2026-10-13 04:38:08 -04:00
aldozarandClaude Opus 5.5 a10e43cb2a CJK text: big-font cells in SHX text, CJK interface fonts in every language (#861)
Drawing (#674): in stroke-font (SHX) text, East Asian wide characters
from a fallback font fill a square cell from the baseline to the text
height, as a big font's do, instead of being scaled by the fallback
font's Latin cap height (about 1.3-1.5x too large and too widely spaced,
so CJK labels overran their space). A line no longer ends with the
stroke font's letter gap after a fallback glyph.

Interface (#513): a CJK font is installed after the Latin one in every
interface language, not only Chinese, so Japanese or Chinese file,
layout and layer names stop showing as boxes. A Japanese font comes
first unless the interface is Chinese; a craft-fonts face embedded in
the build comes last, for systems (and the web build) without one.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:38:03 -04:00
Marco Arnulfo 7e38081b54 Control channel: control.methods lists the methods, ping answers (fixes #843) (#852)
A client could only learn the top-level methods from docs/control-protocol.md;
help, methods, ping and the like all came back as "unknown method". The app
and the headless backend now answer control.methods with each method they
serve ({method, params, description}) and ping with "pong", and an unknown
method's error points to control.methods. A test keeps the app's list equal
to the doc table and checks every listed method is dispatched.
2026-10-13 04:37:57 -04:00
Marco Arnulfo 3f709bed2e Desktop: a bare --control keeps the CADCRAFT_CONTROL_PORT port (fixes #844) (#848)
`--control` as the last argument read `args.next()` as None and reset the
port taken from CADCRAFT_CONTROL_PORT, without logging anything, so
`CADCRAFT_CONTROL_PORT=47321 cadcraft --control` started no control
channel. A bare `--control` now keeps the variable's port and logs a
warning either way; a port given on the command line still wins. The
precedence is documented in docs/control-protocol.md.
2026-10-13 04:37:52 -04:00
Ray caad180e98 fix(dxf): MTEXT direction ignores the embedded object's insertion point (#667) (#834)
An R2018+ MTEXT can carry an embedded object (group 101) in which 10 is the
X-axis direction and 11 the insertion point. AutoCAD writes one for MTEXT with
column settings, and so does the DWG bridge. The reader took the first group 11
anywhere in the entity as the direction, so such text turned towards its own
insertion point. Read 11/21 and 50 from the MTEXT's own groups only.
2026-10-13 04:37:47 -04:00
Valentin KleinandClaude Sonnet 5.5 80ec2dcc60 Ctrl+Z / U during LINE, PLINE... removes the last segment instead of the whole command (#750) (#831)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:42 -04:00
46ab40d211 Keep the layout tabs inside the status bar (#821)
* Keep the layout tabs inside the status bar

With many layouts or long layout names the tabs ran under the coordinates and
the drafting toggles and off the window.

The tabs now stop before the right-hand controls, leaving room for the
coordinates: Model and "+" stay, then the run of layouts that fits, always
holding the current one. A name wider than 150 px is cut with "…" and shows in
full on hover. When some layouts don't fit, a button after the last tab lists
them all; the "Layout list" button at the left of the bar opens the same list
(it did nothing before).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Status bar test: expect the other layout tabs only when the bar has room

At 900 pt the layout tabs that don't fit move into the layout list (d2fe40b), so
only the current tab is painted there. The test still required "Layout2" at
every size and failed on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Chanthawat Kiriyadee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:37:37 -04:00
Valentin KleinandClaude Sonnet 5.5 9464945f82 REFEDIT, REFSET and REFCLOSE: edit block references in place (#818)
* REFEDIT, REFSET and REFCLOSE: edit block references in place (#813)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Move REFEDIT translation lines into the middle of the catalogs (avoids PR merge conflicts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:31 -04:00
Valentin KleinandClaude Sonnet 5.5 3dd678ff3d MLEADEREDIT, MLEADERALIGN, MLEADERCOLLECT (#816)
* MLEADEREDIT, MLEADERALIGN and MLEADERCOLLECT (#812)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Move MLEADER translation lines away from the end of the catalogs (avoids PR merge conflicts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:26 -04:00
Valentin KleinandClaude Sonnet 5.5 ea768ee92a docs: gaps.md FF14 lists what is left of SVG import (#814)
SVG import landed in #636 but its row still said it was missing.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:21 -04:00
5ce44acfb2 Pick dimensions and multileaders anywhere on their text (#807)
Plain TEXT and MTEXT are picked anywhere inside their box, but a
dimension or multileader was only found near its lines: its hit geometry
is built without text. Hovering or clicking the words of a dimension found
nothing (on a survey plan, 2 of 34 letters of a dimension's text).

A point inside the box around the words, turned with the text, now picks
the object. A dimension with a block, as AutoCAD saves them, is drawn
from that block, so its text box comes from the TEXT and MTEXT in the
block, not from the text the dimension's own geometry would place (on the
same plan that was a different place, eight times smaller). A
multileader's text box comes from its MTEXT layout.

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:37:16 -04:00
Valentin KleinandClaude Sonnet 5.5 853b2915b6 Compare hatch pattern lines with a tolerance in normal_zoom_pattern_is_unchanged (#804) (#805)
The view-limited path differs from full detail by ~3e-16 on Windows (float noise from the rotated-frame round trip); the test now compares structure exactly and coordinates within 1e-9.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:11 -04:00
Valentin KleinandClaude Sonnet 5.5 0b92b59fcd Open drawings on a worker thread with an Opening... indicator (#694) (#797)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:06 -04:00
Valentin KleinandClaude Sonnet 5.5 f26588a357 PEDIT: pre-selected line or arc asks to turn it into a polyline (#745) (#796)
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:37:01 -04:00
Valentin KleinandClaude Sonnet 5.5 8073453d86 BOUNDARY: cap point list and aggregate output per call (#723) (#795)
* BOUNDARY: cap point list and aggregate output per call (#723)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* BOUNDARY: a call over the output budget restores the drawing

The session does not roll back a command that returns an error, so the
polylines created before the cap was hit stayed in the drawing.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-10-13 04:36:56 -04:00
Jason Brashear 89c834155d Geometry: keep vector midpoints finite at coordinate extremes (#793) 2026-10-13 04:36:51 -04:00
Marco Arnulfo 14343212a9 Zoom Window: the opposite corner ignores ortho, so the window stays a rectangle (fixes #787) (#790) 2026-10-13 04:36:46 -04:00
bottelliemanuele-makerandClaude Fable 5.1 ecdb8f96b2 i18n: Italian interface catalog (it.tsv) (#789)
Adds Italian as an interface language: 1,227 rows written from the
English strings with Italian desktop-CAD vocabulary (Disegna,
Tratteggio, Quota, Direttrice, layer, spazio modello/carta). Two
`menu` entries keep the menu-bar headings apart from the command and
tool-group labels: View → Visualizza (object label: Vista) and
Modify → Edita (tool group: Modifica). Italian integer plurals follow
the English rule (one, other).

Registered in i18n::LANGUAGES and Preference (code `it`), reported in
the catalog tests, with a locale/preference/plural/menu/font test;
attributed in ATTRIBUTION.md; README, ROADMAP, docs/localization.md,
docs/localization-parity.md, docs/control-protocol.md and the Options
doc comment list the language.

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-10-13 04:36:40 -04:00
4c63ba1470 LINE: resolve deferred TAN first point with typed @distance<angle> (#788)
* LINE: resolve deferred TAN first point with typed @distance<angle>

* LINE: collapse the nested if-let (clippy collapsible_if)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:36:35 -04:00
c0335161c3 Geometry: spline arc length converges on tight bends, so LENGTHEN shortens to the target (#786)
* Geometry: spline arc length converges on tight bends, so LENGTHEN shortens to the target (fixes #705)

* Geometry: cap adaptive spline quadrature (depth 10, 1e-10 relative) so a hostile spline can't make LENGTHEN slow

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:36:28 -04:00
Marco Arnulfo 419d8848d6 MTEXT: Exactly line spacing keeps the pitch when a line has taller text (fixes #711) (#784) 2026-10-13 04:35:52 -04:00
aldozarandClaude Opus 5.5 c781169b95 Don't give entities made while reading handles the file still uses (#783)
Another program's file can name a $HANDSEED below handles it uses (a DWG
read through the bridge did: its seed was under the handles of its
dimension blocks). The faces a polyface mesh becomes were numbered from the
seed while reading, so they could take handles of records further on in
other lists (another block); within one list duplicates were already
renumbered. A DWG keeps one object per handle, so saving one lost the
duplicates: 15 faces of a block's mesh in a permit set.

Before entities are read, every handle a file uses is now reserved. A file
CADCraft wrote names its own next handle (#495), above which its rebuilt
records are numbered, so it is left to that and resaves stay identical.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:35:44 -04:00
aldozarandClaude Opus 5.5 f314d3a591 Write an unedited dimension's block as it was read (#782)
Saving regenerated every dimension's anonymous block, even dimensions read
from another program's file and never touched: the definition points went
and other programs then showed CADCraft's drawing of each dimension (a
dimension line split around its text came back whole, for instance).

A dimension still linked to the block it was read with hasn't changed
since: every edit drops the link, and the screen draws that block while it
is there. Its block is now written as read, under its name and handles;
edited and new dimensions are generated as before.

On a 1,013-dimension permit set saved DWG -> CADCraft -> DWG, every
dimension's block now matches the original (before: none).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:35:38 -04:00
aldozarandClaude Opus 5.5 e9d8462828 Keep the ACIS geometry of 3D solids, regions and bodies on save (ACDSDATA) (#781)
From AutoCAD 2013 on, a 3DSOLID, REGION or BODY doesn't carry its ACIS
geometry: the binary SAB lives in the file's data store section (ACDSDATA),
one ACDSRECORD per entity bound by a 320 handle. CADCraft kept those
entities (as unknown entities, with their handles) but dropped the section,
so a drawing saved as DWG or DXF had empty solids, and saving reported them
as not saved.

- doc: Foreign::data_store keeps the section's groups as read;
  data_store_entities() lists the entities it has records for.
- io: the reader keeps the section; the writer puts it back for files of
  2013 and later (and in the DXF the DWG bridge converts, which acadrust
  reads into the DWG), without the records of entities no longer written.
  Nothing is written for older files or when no record's entity remains.
- engine: not_saved_as(d, version): from 2013 a solid, region or body with a
  data store record isn't reported; saves and document.bytes pass the version
  being written.

On a 39,600-object permit set with 625 3D solids and 2 regions, DWG ->
CADCraft -> DWG now keeps all 627 bodies with byte-identical SAB (before:
none), and the save no longer reports them.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:35:31 -04:00
Marco Arnulfo 6ab800e64c Engine: NEW and OPEN end a command left running in the previous drawing (fixes #715) (#780)
A command started in one drawing kept running after a programmatic NEW or OPEN made another
drawing current. Finishing it there recorded an undo step holding the first drawing, so undo in
the new drawing brought the other drawing back. Session::new_drawing and open_drawing now end a
running command before the new drawing becomes current, as CLOSE and document.switch already do
and as starting NEW from the command line did: its undo step lands in the drawing it started in.
With no command running, nothing changes (the previous drawing keeps its selection).
2026-10-13 04:35:26 -04:00
Marco Arnulfo 565cadaa51 Extents: cache block bounds per depth so a deep visit can't hide a shallow reference (fixes #706) (#778) 2026-10-13 04:35:20 -04:00
Marco Arnulfo bca698a588 SPLINE: cap programmatic control points like spline.cv (fixes #719) (#776) 2026-10-13 04:35:14 -04:00
Marco Arnulfo 5de2324973 Selection: rebuild the spatial index when a layer used inside blocks is hidden or shown (fixes #716) (#775) 2026-10-13 04:35:08 -04:00
Marco Arnulfo 266ee7e6ea Autosave: a write that failed is tried again without another change (fixes #717) (#774)
The planner marked a drawing as autosaved when it dispatched the write, and the background
worker only logged a failure. An unchanged drawing whose write failed was then never written
again, even once the folder became writable. The worker now reports whether the file was
written; on a failure (or a thread that could not be spawned) the drawing is no longer counted as
autosaved, so the next plan restarts its SAVETIME clock and tries again.
2026-10-13 04:35:02 -04:00
Marco Arnulfo 045212139a Geometry: fit splines with too many points use them as control points instead of a dense solve (fixes #702) (#773) 2026-10-13 04:34:56 -04:00
Marco Arnulfo 6772150bc4 Constraints: an arc solved with a negative radius is stored turned half a turn, so its points stay put (fixes #703) (#772) 2026-10-13 04:34:51 -04:00
NetterSilver b2ba585251 TRIM: a pick after a closed polyline's last cut keeps only the complementary run (#726) (#771)
* TRIM: a pick after a closed polyline's last cut keeps only the complementary run (#726)

With no cutting intersection past the pick, trim_polyline used the first cut
plus the perimeter as the end of the piece and then kept the run from the
first cut to the last cut plus a whole perimeter, so one extra circuit of the
outline stayed (a 4 x 4 square became an open polyline of length 24 instead of
8). The kept run now ends at the last cut before the pick.

* Docs: update the progress docs for this change
2026-10-13 04:34:46 -04:00
Books 7fcdc6e3bc Active viewport highlight: selection on the GPU, hover cached apart, kept inside a clipped outline (#770)
* Active viewport: redraw while panning and zooming inside it, without rebuilding the layout (#688)

Inside an active MSPACE viewport, middle-drag, trackpad pan and wheel or
pinch zoom change the viewport's view through set_view_quiet, which makes
no new revision. The layout's display list, which draws model space
through each viewport, was cached on (drawing, revision, zoom band), so it
kept showing the old view until a command such as ZOOM rebuilt it: the
viewport froze, or appeared to ignore the zoom.

The active viewport's contents are now drawn apart from the layout's list,
the way model space itself is drawn. They are built once for an area
around the viewport (half its larger side of margin all round), then moved
and scaled to the current view on the GPU and drawn under the layout's own
objects. They are rebuilt when the drawing changes, when the zoom has
moved 2x from the view they were built for, when the view leaves the built
area, and once a zoom comes to rest, so dash lengths and curve detail
follow the viewport's scale again. A pan step takes about 1 ms with 70,000
polylines, where rebuilding the layout takes about 140 ms per frame.

Rectangular viewports are clipped with the scissor rectangle. A clipped
viewport's outline is drawn into a stencil buffer as a triangle fan that
flips a bit (even-odd, as the outline clips on the CPU), and its contents
draw only where the bit is set; the native window now asks eframe for an
8-bit stencil buffer, and every canvas pipeline names its format. Where
there is no stencil buffer (the CPU canvas, the web runner), a clipped
viewport's contents stay in the layout's list, whose cache now follows the
viewport's view.

Render: Options::skip_viewport leaves a viewport's contents out of a
layout, and viewport_content builds them for any area. Viewport contents
are built on all cores, like model space (130 ms to 37 ms for 70,000
polylines).

* Active viewport highlight: selection on the GPU, hover cached apart, kept inside a clipped outline

Inside an active MSPACE viewport the selection highlight was drawn as
dashed egui shapes on the CPU every frame, about 8-13 ms per frame with
7,000 polylines selected, and its geometry was cached together with the
hover, so moving the cursor over objects tessellated the whole selection
again. The selection and the hover are now cached apart, and the
selection goes through the GPU highlight path model space already uses:
about 0.1 ms per frame. In a clipped viewport it is kept inside the
outline with the stencil mask its contents use; before, it was only cut
to the outline's bounding rectangle.
2026-10-13 04:34:40 -04:00
b19188919d DXF/DWG: write the Model layout's plot type as extents, not "Layout information" (#765)
The Model layout was written with the default page setup, whose "layout"
plot area is plot type 5, "Layout information" (DXF Reference, PLOTSETTINGS
group 74). That means nothing for model space: opened in AutoCAD 2027, a
drawing saved by CADCraft had a blank "What to plot", no preview and no scale
in the Plot dialog for Model. Model space now gets what PLOT does for it: the
drawing extents scaled to fit (74 = 1, 75 = 0). DWG saves go through the same
writer; the reader already ignores the Model layout's plot settings.

Co-authored-by: EP995LAB <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:34:35 -04:00
Books 488308a2de Hatch: a view covering a pattern hatch leaves its lines exactly as they are (#762)
With a view, each span of a pattern line was cut to the view's extent
intersected with the boundary's. Spans already lie within the boundary,
and the boundary extent comes from rotating the corners directly while a
span end comes from interpolating along an edge, so where a line passes
through a corner the two differ by a rounding error and the cut moved the
end (by 3e-16 on Windows, whose sin/cos round differently). The spans are
now cut to the view's extent only, so normal_zoom_pattern_is_unchanged
holds on every platform.
2026-10-13 04:34:30 -04:00
Marco Arnulfo f5d58913cc CIRCLE: a radius point on the centre is refused and asked again (follow-up to #735) (#761) 2026-10-13 04:34:25 -04:00
Marco Arnulfo 5ce1ea3dfc POLYGON: an Edge second endpoint on the first is refused and asked again (follow-up to #735) (#760) 2026-10-13 04:34:19 -04:00
aldozarandClaude Opus 5.5 483a9304ca cadcraft-cli mcp: --lazy and --launch for clients that start before the app (#756)
MCP clients start their servers when they start, usually before CADCraft is
open, and `--connect` refuses to start then. `--lazy` starts the bridge
anyway and reaches the app at the first tool call; until the app answers,
each call fails with how to open it. `--launch` (implies --lazy) opens
CADCraft on macOS with that control port at a call that finds nothing, and
waits up to 30 s. Neither falls back to a headless session (#103).

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:34:14 -04:00
5183f63bc5 Hatch and Gradient dialog (create and edit) (#753)
* HATCH/GRADIENT: points and objects in one call; GRADIENT name and centered

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* HATCHEDIT: gradient parameter (make or change a gradient fill)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* HATCHPICK: pick hatch boundaries, an origin or hatches for the dialog

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch dialog: state, defaults and the OK command call

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch dialog: pick points, objects, origin or hatch and come back

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch and Gradient dialog window (pattern swatches, gradient, origin, boundaries, options)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* HATCH, GRADIENT and HATCHEDIT open the hatch dialog; double-click a hatch to edit; HPDLGMODE

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch dialog: keep the window to its content (OK and Cancel stayed off screen); double-click test

A vertical separator between the two columns took the height available, so the window grew
every frame until its buttons left the screen. Found in the running app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Docs: hatch dialogs in gaps, target-app parity and UI parity

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch dialog review fixes

- Double-clicking a hatch at its centre opened the dialog and also started a grip edit.
- Edit mode no longer clamps an out-of-range scale or angle into a change nobody made.
- HPORIGINMODE outside 1-5 means the current origin, as HATCH reads it.
- Picks made in one space are dropped when the dialog comes back in another (layout tab).
- A gradient hatch's Pattern tab offers the current pattern (HPNAME), not SOLID.
- Ukrainian: "Default to boundary extents" said "outside the boundary".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: lloyd <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-13 04:34:09 -04:00
cyfung1031 bcd6322ee9 Plotting: honor model-space center and X/Y offsets (#751)
* plot: add bounded model-space paper placement

* plot: expose center and paper offset parameters

* ui: add model-space Plot offset controls
2026-10-13 04:34:04 -04:00
Marco Arnulfo e71e17a8df View: refuse a view that maps to an infinite viewport view, keeping the viewport (fixes #714) (#749) 2026-10-13 04:33:59 -04:00
Marco Arnulfo 08cfbd5dd7 Select: pick a SOLID inside its fill, not its bounding rectangle (fixes #718) (#747) 2026-10-13 04:33:52 -04:00
Brandon ThomasandClaude Opus 5.5 00c7613f1a Release 0.6.2: rebuild with the fixed shared release workflow
The previous release build failed in craft-common-actions, not in this
repo: riscv64 packaging got --formats deb,rpm,tar (fixed in
craft-common-actions#3), Linux jobs lacked the ALSA headers
(craft-common-actions#5), and Windows signing needed the AZURE_* secrets
listed in the caller.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 11:11:19 -04:00
Brandon ThomasandClaude Opus 5.5 0ecffdab4a Release workflow: pass the Azure signing secrets so Windows builds are signed (#647)
Since the release workflow moved to storytold/craft-common-actions, it has
passed only the Apple and WINDOWS_CERTIFICATE secrets. The signing job reads
values from the release environment, but only for names the caller lists, so
the AZURE_* names that Trusted Signing uses came through empty and Windows
builds would ship unsigned. Same fix as storytold/craft-launcher#174.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 11:08:09 -04:00
Brandon ThomasandClaude Opus 5.5 4cb9e8a535 Release 0.6.1: check out craft-fonts in release builds
The shared release workflow sets CRAFT_FONTS_DIR with CRAFT_FONTS_REQUIRED=1
but only checks craft-fonts out when craft-fonts-ref is given. Since #321
cadcraft-fonts reads that directory, so every native release job failed
with "fonts/manifest.txt: No such file or directory". Pin craft-fonts
3d9ab3a (current main, with the Arabic faces the web build embeds).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 06:06:24 -04:00
Brandon ThomasandClaude Opus 5.5 a12c85c585 Release prep: 0.6.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 05:44:20 -04:00
cyfung1031andClaude Opus 5.5 890f7f1c6f Performance: reuse nearby snap geometry for tracking acquisition (#698)
Squash of PR #698 by @cyfung1031.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:35:13 -04:00
mayloglogandClaude Opus 5.5 4bb3acb913 Add Chinese language support to preferences (#684)
Squash of PR #684 by @mayloglog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:28:17 -04:00
aldozarandClaude Opus 5.5 0675648de8 Hatch: pick the pattern from swatches instead of typing its name (fixes #669) (#679)
Squash of PR #679 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:21:49 -04:00
aldozarandClaude Opus 5.5 c2f8782cc2 Plot dialog: device, plot style table, Window <, and a preview of its settings (#673)
Squash of PR #673 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:21:33 -04:00
aldozarandClaude Opus 5.5 d365b60704 MIRROR and PASTE previews on the GPU; GPU previews in layouts too (#655)
Squash of PR #655 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:21:18 -04:00
aldozarandClaude Opus 5.5 cf797cbafe Build the screen's model-space display list on all cores; read-write locks for glyph caches (#654)
Squash of PR #654 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:21:04 -04:00
LionandClaude Opus 5.5 935cb98eed SCRIPT command: run .scr files from the command line, menus and JSON (gaps.md E2) (#693)
Squash of PR #693 by @Lion-1209.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:13:51 -04:00
Diego OspinaandClaude Opus 5.5 0178858e79 i18n(es): add 219 missing rows, fix mistranslations and terms (#680)
Squash of PR #680 by @diegozpy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:13:36 -04:00
rangoDJandClaude Opus 5.5 875f99d26f Deduplicate identical boundary loops to prevent empty hatch fills (#671)
Squash of PR #671 by @rangoDJ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:13:20 -04:00
MarekSpodBiedryandClaude Opus 5.5 69ea207617 Cache active viewport highlights per zoom band so zoom and pan stay smooth (#687) (#695)
Squash of PR #695 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:13:04 -04:00
BooksandClaude Opus 5.5 546eefc58a Zoom the canvas by each mouse-wheel notch in the frame it arrives (#692)
Squash of PR #692 by @SBaksa.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:12:49 -04:00
SteamSmithandClaude Opus 5.5 61c018845a control server: bound request lines and concurrent connections (#678)
Squash of PR #678 by @SteamSmith.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:12:34 -04:00
rangoDJandClaude Opus 5.5 9a0d1b3a62 Prioritize command aliases in autocomplete and display shortcut match (#656)
Squash of PR #656 by @rangoDJ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:12:17 -04:00
aldozarandClaude Opus 5.5 507c5e5b34 File tabs: cut long drawing names short with an ellipsis (#657)
Squash of PR #657 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:11:59 -04:00
Jason BrashearandClaude Opus 5.5 bc6dc997ef AUNITS: degrees/minutes/seconds angles round at the displayed precision (#672)
Squash of PR #672 by @webdevtodayjason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:11:42 -04:00
aldozarandClaude Opus 5.5 6ca8cec97d BRICK: draw each vertical joint once (#664)
Squash of PR #664 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:11:25 -04:00
CaseyKleinmanandClaude Opus 5.5 f8cb50eaa3 DXF: write kept application data groups as read, not as handle lists (#681)
Squash of PR #681 by @CaseyKleinman.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:11:09 -04:00
markmonkeyandClaude Opus 5.5 b6f2e86f78 Show block insertion XYZ in Properties Inspector (#682)
Squash of PR #682 by @markmonkey.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 03:10:53 -04:00
aldozarandClaude Opus 5.5 c57879a5c8 GPU errors and device loss: keep running, autosave at once, tell the user (#652)
Squash of PR #652 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:42:45 -04:00
PedroGuilleandClaude Opus 5.5 2404719c3b Fix filled text zoom freezes with cached glyph meshes (#651)
Squash of PR #651 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:42:29 -04:00
rangoDJandClaude Opus 5.5 90cd443000 Add regression tests for Plot Preview toolbar button (fixes #442) (#653)
Squash of PR #653 by @rangoDJ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:42:14 -04:00
PedroGuilleandClaude Opus 5.5 ac9483c9c1 Add raw-HID SpaceMouse 2D navigation (#650)
Squash of PR #650 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:29:48 -04:00
pechnikov2026-starandClaude Opus 5.5 ade5469a24 i18n: add Russian, Spanish, French, Portuguese and German interfaces (#624)
Squash of PR #624 by @pechnikov2026-star.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:22:47 -04:00
Daniel LošákandClaude Opus 5.5 6d7c652b65 i18n: add Czech (cs) interface language (#639)
Squash of PR #639 by @Losminek.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:11:51 -04:00
Valentin KleinandClaude Opus 5.5 3aeedf4856 docs: refresh gaps.md and parity docs for landed features (#625)
Squash of PR #625 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:11:37 -04:00
Gert Pellin - GPEandClaude Opus 5.5 f7c6293d09 feat: SVG import — read SVG and SVGZ into native entities (#636)
Squash of PR #636 by @switch87.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:11:22 -04:00
Valentin KleinandClaude Opus 5.5 89064fd82a Drafting/plot/UI follow-ups: PolarSnap over isometric snap, MVIEW Restore, plot margins, PNG/SVG pens, PE_URL links, OPTIONS settings (part of #626) (#633)
Squash of PR #633 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:11:06 -04:00
aldozarandClaude Opus 5.5 1e1f68bf40 Fix fatal wgpu buffer overflow; draw MOVE/COPY/ROTATE/SCALE previews and the selection highlight on the GPU (#642)
Squash of PR #642 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:10:51 -04:00
STE1200andClaude Opus 5.5 244feb6e89 Render: level of detail and view clipping for pattern hatches on screen (fixes #544) (#638)
Squash of PR #638 by @STE1200.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:10:37 -04:00
aldozarandClaude Opus 5.5 135c928fea Hatches: draw the pattern definition stored in the file; scale library patterns in metric drawings (#643)
Squash of PR #643 by @aldozar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:54:18 -04:00
Valentin KleinandClaude Opus 5.5 9477f37503 File-format follow-ups: version-gated MULTILEADER and DIMSTYLE groups, kept $DWGCODEPAGE, PURGE multiline styles (#632)
Squash of PR #632 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:54:03 -04:00
Fabio LussiandClaude Opus 5.5 370150186b Linux: Theme > System follows the desktop's light/dark setting (#641)
Squash of PR #641 by @itrycodinganditsbad.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:53:48 -04:00
MuhiandClaude Opus 5.5 2fa967db65 fix(io): write DXF CLASS instance counts and preserve current leader style (#635)
Squash of PR #635 by @The-Great-Nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:53:33 -04:00
Gert Pellin - GPEandClaude Opus 5.5 4e276db858 Tool Sets: the gear on a category header opens that category's options (#620)
Squash of PR #620 by @switch87.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:53:19 -04:00
rangoDJandClaude Opus 5.5 9b3674e01f Make right palette collapse arrow interactive (fix #617) (#640)
Squash of PR #640 by @rangoDJ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:53:05 -04:00
MarekSpodBiedryandClaude Opus 5.5 c5ebf4d1cd Keep inter-word spaces in stroke-font MTEXT (#628) (#644)
Squash of PR #644 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:52:51 -04:00
MarekSpodBiedryandClaude Opus 5.5 83b8a84050 Add PTYPE as an alias of the Point Style command (#622) (#645)
Squash of PR #645 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 19:52:37 -04:00
PedroGuilleandClaude Opus 5.5 54ea5e743a Spanish translation (#610)
Squash of PR #610 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:42:39 -04:00
arekownandClaude Opus 5.5 d7f3e48362 Add German (de) interface language (#573)
Squash of PR #573 by @arekown.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:36:40 -04:00
PedroGuilleandClaude Opus 5.5 f967dc7aca Persist SNAPUNIT and GRIDUNIT in DXF (fix #607) (#614)
Squash of PR #614 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:28:56 -04:00
Valentin KleinandClaude Opus 5.5 e1e61a13b5 feat(modify): SPLINEDIT Join, Edit vertex Add and Elevate order (#559)
Squash of PR #559 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:28:41 -04:00
MarekSpodBiedryandClaude Opus 5.5 5ef32b3afa Select: pick pattern hatches on their visible strokes (#489) (#599)
Squash of PR #599 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:28:14 -04:00
MarekSpodBiedryandClaude Opus 5.5 04aa716920 Page Setup: report unsupported layout plot areas as not available yet (#491) (#597)
Squash of PR #597 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:28:00 -04:00
MarekSpodBiedryandClaude Opus 5.5 5e71a75383 Web: ?cpu selects the CPU canvas instead of installing the GPU canvas (#500) (#592)
Squash of PR #592 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:27:46 -04:00
MarekSpodBiedryandClaude Opus 5.5 d431b485bd STYLE typed with no arguments opens the Text Style dialog instead of an error (#535) (#590)
Squash of PR #590 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:27:32 -04:00
MarekSpodBiedryandClaude Opus 5.5 41c3c83fb9 AREA: refuse an open elliptical arc instead of measuring the whole ellipse (#487) (#601)
Squash of PR #601 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:04:40 -04:00
MarekSpodBiedryandClaude Opus 5.5 5cb54c3969 Include multileader text in its bounds so zoom, window selection and viewports keep the whole text (#488) (#600)
Squash of PR #600 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:04:24 -04:00
MarekSpodBiedryandClaude Opus 5.5 0b5a0a2eb8 Plot: apply an explicit scale to non-fitted layout plots (#490) (#598)
Squash of PR #598 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:04:10 -04:00
MarekSpodBiedryandClaude Opus 5.5 73c91cbac5 Command line keyboard input works while the command line is hidden (#497) (#595)
Squash of PR #595 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:03:55 -04:00
MarekSpodBiedryandClaude Opus 5.5 d51971b6d7 Parameters Manager: keep a pending expression when the window loses focus (#498) (#594)
Squash of PR #594 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:03:40 -04:00
MarekSpodBiedryandClaude Opus 5.5 0fcf46d487 OFFSET: full ellipse copy goes to the side of the picked point (#501) (#591)
Squash of PR #591 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:03:24 -04:00
MarekSpodBiedryandClaude Opus 5.5 f1919e31a5 Text style rename: update text inside block definitions (#472) (#588)
Squash of PR #588 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:03:07 -04:00
MarekSpodBiedryandClaude Opus 5.5 6ef1e62755 Properties: turn a block reference's attribute text with its Rotation edit (#473) (#587)
Squash of PR #587 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:02:52 -04:00
MarekSpodBiedryandClaude Opus 5.5 9e22617679 layer.delete: clear the deleted layer from viewport freeze and colour overrides (#474) (#586)
Squash of PR #586 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:02:36 -04:00
MarekSpodBiedryandClaude Opus 5.5 c245e1de35 INSERT with explode records one undo step (#475) (#585)
Squash of PR #585 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:02:21 -04:00
MarekSpodBiedryandClaude Opus 5.5 f59b32cac7 properties.set rejects a linetype that is not loaded (#476) (#584)
Squash of PR #584 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:02:06 -04:00
MarekSpodBiedryandClaude Opus 5.5 3f781c3395 Align Text > Angle asks for the angle instead of failing with a missing-parameter error (#478) (#582)
Squash of PR #582 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:01:51 -04:00
MarekSpodBiedryandClaude Opus 5.5 b23b45e976 Properties: reject a malformed lineweight instead of setting 0.25 mm (#480) (#580)
Squash of PR #580 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:41:25 -04:00
MarekSpodBiedryandClaude Opus 5.5 fc30f2c2ea Properties: changing a block's scale moves and resizes its attributes (#481) (#579)
Squash of PR #579 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:41:10 -04:00
MarekSpodBiedryandClaude Opus 5.5 63a0ab4a32 dimstyle.rename and delete: cover dimensions inside block definitions (#482) (#578)
Squash of PR #578 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:40:55 -04:00
MarekSpodBiedryandClaude Opus 5.5 d3ae8f3a8b Dimension Space asks for the base, the dimensions and the spacing instead of failing (#483) (#577)
Squash of PR #577 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:40:39 -04:00
MarekSpodBiedryandClaude Opus 5.5 3363d4a78c SETVAR keeps text variables such as CLAYER as text, so a layer named 10 can be selected (#484) (#576)
Squash of PR #576 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:40:25 -04:00
MarekSpodBiedryandClaude Opus 5.5 a5a9e3ef63 SETVAR accepts point objects for SNAPBASE, LIMMIN, LIMMAX and INSBASE (#485) (#575)
Squash of PR #575 by @MarekSpodBiedry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:40:10 -04:00
PedroGuilleandClaude Opus 5.5 40aa4fbf49 Fix OFFSET distance clicks and source picking (#618)
Squash of PR #618 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:39:55 -04:00
PedroGuilleandClaude Opus 5.5 a181bbd609 Fix Measure Distance snapping through layout viewports (#616)
Squash of PR #616 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:39:39 -04:00
PedroGuilleandClaude Opus 5.5 ce1cc631d5 Windows: use FXC by default for DirectX 12 startup (#613)
Squash of PR #613 by @PedroGuille.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:39:24 -04:00
Valentin KleinandClaude Opus 5.5 b6383b5f3c feat(file): COMPARE drawings with overlay and change areas (fixes #563) (#572)
Squash of PR #572 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:25:17 -04:00
Valentin KleinandClaude Opus 5.5 74e72c93f8 Plotters: device configurations with paper sizes and printable areas (fixes #564) (#570)
Squash of PR #570 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:25:00 -04:00
Valentin KleinandClaude Opus 5.5 7e437cb62d feat(ui): QuickCalc palette; CAL points, vector functions, unit conversion (part of #563) (#569)
Squash of PR #569 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:24:46 -04:00
Gert Pellin - GPEandClaude Opus 5.5 18b4a8d0dd CLI: cadcraft-cli exits quietly when stdout is closed early (#568)
Squash of PR #568 by @switch87.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:24:30 -04:00
Valentin KleinandClaude Opus 5.5 7a13ca7d05 PDF export: real text in embedded TrueType subsets (part of #560) (#571)
Squash of PR #571 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:24:14 -04:00
Valentin KleinandClaude Opus 5.5 70b0cce997 PDF export: layers as PDF layers (OCG), several sheets per file, hyperlinks (part of #560) (#567)
Squash of PR #567 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:23:59 -04:00
Tasos SangiotisandClaude Opus 5.5 a880f8a4b0 DXF: keep full-circle, spline and clockwise ellipse hatch edges (fixes #492, #493, #494) (#549)
Squash of PR #549 by @tsangiotis.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:23:45 -04:00
Valentin KleinandClaude Opus 5.5 8f59410c33 Plot styles: apply line end, join and fill styles (part of #564) (#566)
Squash of PR #566 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:13:32 -04:00
Valentin KleinandClaude Opus 5.5 0bab712575 feat(inquiry): COUNT across layouts and nested blocks, COUNTLIST, COUNTTABLE (part of #563) (#565)
Squash of PR #565 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:13:18 -04:00
Valentin KleinandClaude Opus 5.5 c4cc40355a feat(drafting): isometric snap/grid, ISODRAFT, ISOPLANE, ELLIPSE Isocircle (#561)
Squash of PR #561 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:13:02 -04:00
Valentin KleinandClaude Opus 5.5 d2fda54e8a feat(modify): PEDIT Edit vertex Break/Straighten/Tangent/Regen, SPLINEDIT fit data and vertex options, closed-spline fit tolerance (part of #554) (#558)
Squash of PR #558 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:12:46 -04:00
Valentin KleinandClaude Opus 5.5 d0dd5cfe16 Support files: DWT templates for NEW/QNEW, SAVEAS .dwt, user alias files (fixes #552) (#562)
Squash of PR #562 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:12:32 -04:00
Valentin KleinandClaude Opus 5.5 9fd1b8988d Support files: user .lin linetypes and .pat hatch patterns (part of #552) (#557)
Squash of PR #557 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:12:17 -04:00
Brandon ThomasandClaude Opus 5.5 52015c0b17 CONSTRAINTINFER test: make the array of copies explicitly non-associative (#621)
Arrays are associative by default since #455, so arrayrect makes one
block reference; the test wants many separate objects.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-11 12:49:35 -04:00
Valentin KleinandClaude Opus 5.5 0135e793f7 Constraints: CONSTRAINTINFER while drawing and editing, DOF status on the canvas (fixes #546) (#555)
Squash of PR #555 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:48:06 -04:00
Valentin KleinandClaude Opus 5.5 58eefa8432 Constraints: DOF report, G2 Smooth, ellipse/spline/block geometry (part of #546) (#550)
Squash of PR #550 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:47:53 -04:00
Valentin KleinandClaude Opus 5.5 9ca0dcf7d4 Tables: table breaking and CSV data links (fixes #534) (#553)
Squash of PR #553 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:47:39 -04:00
Valentin KleinandClaude Opus 5.5 784a7937ef Tables: cell styles, formulas, TABLEDIT and TABLEEXPORT (part of #534) (#548)
Squash of PR #548 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:47:25 -04:00
Valentin KleinandClaude Opus 5.5 8005201db9 feat(text): MTEXT paragraph formatting (indents, tabs, lists) and columns (#547)
Squash of PR #547 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:47:12 -04:00
Valentin KleinandClaude Opus 5.5 a4504cc098 DXF: keep what we don't model on save — unknown entities and objects, foreign xdata, extension dictionaries, reactors, colour books (fixes #528) (#545)
Squash of PR #545 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:46:58 -04:00
Wladmir JúniorandClaude Opus 5.5 235ef4f9ab Add Brazilian Portuguese (pt-BR) interface language (#539)
Squash of PR #539 by @WladmirJunior.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:34:47 -04:00
Valentin KleinandClaude Opus 5.5 b13f1e6fa4 OPTIONS: preferences dialog, JSON form and a user profile that survives restarts (fixes #23) (#531)
Squash of PR #531 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:34:34 -04:00
Valentin KleinandClaude Opus 5.5 afae36cb60 REGION: region entity, UNION/SUBTRACT/INTERSECT, MASSPROP (fixes #510) (#526)
Squash of PR #526 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:12:09 -04:00
Valentin KleinandClaude Opus 5.5 bc7744b27b Xrefs: External References palette and XREF (fixes #525) (#533)
Squash of PR #533 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:11:52 -04:00
Valentin KleinandClaude Opus 5.5 0230250bf5 Xrefs: XATTACH, -XREF, XBIND, XOPEN; load at open, save only the reference (part of #525) (#530)
Squash of PR #530 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:11:37 -04:00
Valentin KleinandClaude Opus 5.5 c390364a16 Grip dimensional input: length, angle and radius fields while stretching a grip, DYNDIVIS/DYNDIGRIP (part of #519, stacked on #440) (#527)
Squash of PR #527 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:11:22 -04:00
Valentin KleinandClaude Opus 5.5 57f70b6b46 QDIM: Staggered, Baseline, Ordinate, Radius, Diameter, datumPoint and Edit (fixes #507) (#524)
Squash of PR #524 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:11:07 -04:00
Valentin KleinandClaude Opus 5.5 8ca4265627 Dynamic Input options menu (DYNPROMPT), second-value lock; INS on ATTDEF/MLEADER, GCEN on closed splines (part of #519) (#523)
Squash of PR #523 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:10:52 -04:00
Valentin KleinandClaude Opus 5.5 c334fedf31 Dimension edits: DIMEDIT Oblique/New/Rotate/Home, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMINSPECT (part of #507) (#522)
Squash of PR #522 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:10:38 -04:00
Valentin KleinandClaude Opus 5.5 b7b37e29cd HELIX: helix entity drawn as a spline (part of #510) (#521)
Squash of PR #521 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:10:24 -04:00
Jason BrashearandClaude Opus 5.5 63af07f782 Dimension text: degrees/minutes/seconds angles round at the displayed precision (#520)
Squash of PR #520 by @webdevtodayjason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:10:11 -04:00
Valentin KleinandClaude Opus 5.5 fa0ce3c70f Shortcut menus: command line, drawing and layout tabs, Layers and Properties palettes (fixes #512) (#518)
Squash of PR #518 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:09:56 -04:00
Dylan M. Taylor 48cce34a52 ci: refactor workflows to use storytold/craft-common-actions (#605)
* ci: refactor workflows to use reusable artcraft-common-actions

* ci: point reusable workflows to storytold/craft-common-actions

* ci: pin storytold/craft-common-actions to commit 27a978f and pass secrets explicitly

* ci: use @main (unpinned) for craft-common-actions with explanation comment
2026-10-11 11:51:11 -04:00
Valentin KleinandClaude Opus 5.5 289855aa67 MLINE: multiline entity, MLSTYLE and MLEDIT (part of #510) (#517)
Squash of PR #517 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:48:27 -04:00
Valentin KleinandClaude Opus 5.5 997aef85d5 Shortcut menus: command menu while a command runs, selection menu with object edits (part of #512) (#515)
Squash of PR #515 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:48:12 -04:00
Valentin KleinandClaude Opus 5.5 836badce4c Dimension styles: fit, text movement, suppressed halves, fixed extension lines, linetypes and lineweights and more DIM variables (part of #507) (#514)
Squash of PR #514 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:47:57 -04:00
Valentin KleinandClaude Opus 5.5 43958b537e DXF: read pre-2007 files in their $DWGCODEPAGE (CJK, Cyrillic, Central European…) (fixes #505) (#511)
Squash of PR #511 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:47:42 -04:00
CyberFox-81andClaude Opus 5.5 7dead193e4 Web: opt-in embedding bridge for host pages (?host=parent) (#509)
Squash of PR #509 by @CyberFox-81.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:47:27 -04:00
Valentin KleinandClaude Opus 5.5 78944a8341 DXF: reopen-and-save keeps one *D block per dimension and stable handles (fixes #495) (#508)
Squash of PR #508 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:47:11 -04:00
Valentin KleinandClaude Opus 5.5 7ecac5fb66 Tiled model viewports: VPORTS, saved viewport configurations, DXF VPORT table (part of #463) (#504)
Squash of PR #504 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:43:11 -04:00
Valentin KleinandClaude Opus 5.5 c9c3031de9 Named views (VIEW), Zoom Realtime and Dynamic, ZOOMFACTOR (part of #463) (#503)
Squash of PR #503 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:42:56 -04:00
Valentin KleinandClaude Opus 5.5 b4b62e4cf0 FILLET and CHAMFER with polyline segments (fixes #466) (#502)
Squash of PR #502 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:42:41 -04:00
Valentin KleinandClaude Opus 5.5 8e07de0f4e Annotative scaling: DXF and status bar annotation scale list (fixes #468) (#506)
Squash of PR #506 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:42:27 -04:00
Valentin KleinandClaude Opus 5.5 e7bb447d58 Annotative scaling: scale list, CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE (part of #468) (#486)
Squash of PR #486 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:42:13 -04:00
Valentin KleinandClaude Opus 5.5 c0a19dfb9e FILLET with elliptical arcs and splines (part of #466) (#470)
Squash of PR #470 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:41:59 -04:00
Valentin KleinandClaude Opus 5.5 ea0f866c7c EXTEND, JOIN and LENGTHEN on elliptical arcs and splines (part of #466) (#469)
Squash of PR #469 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:41:45 -04:00
Valentin KleinandClaude Opus 5.5 10f7a9b2a3 SETVAR/GETVAR: header variables the commands keep, TRANSPARENCYDISPLAY, dimension variables in SETVAR ? (fixes #461) (#467)
Squash of PR #467 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:36:59 -04:00
Valentin KleinandClaude Opus 5.5 0371c448f6 DXF: native MULTILEADER read and write instead of LEADER + MTEXT (fixes #459) (#465)
Squash of PR #465 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:36:45 -04:00
Valentin KleinandClaude Opus 5.5 f3553783a0 UNDO Mark/Back, BEgin/End, Auto and Control; MREDO; UNDOCTL (part of #461) (#464)
Squash of PR #464 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:36:30 -04:00
Valentin KleinandClaude Opus 5.5 6aa7c03fad Status bar: viewport scale list and lock toggle (fixes #453) (#462)
Squash of PR #462 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:36:16 -04:00
Valentin KleinandClaude Opus 5.5 d42313cde2 ARRAYEDIT and ARRAYCLOSE for associative arrays (fixes #448) (#460)
Squash of PR #460 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:36:02 -04:00
Valentin KleinandClaude Opus 5.5 61a8a5f984 Viewports: polygonal, object and clipped viewports, VPCLIP, MVIEW ON/OFF/Lock/Restore (part of #453) (#458)
Squash of PR #458 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:35:46 -04:00
Valentin KleinandClaude Opus 5.5 d6aa802c75 Hatch: HPGAPTOL, pattern origin, separate hatches, island style; HATCHEDIT options and -HATCHEDIT (fixes #451) (#457)
Squash of PR #457 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:29:05 -04:00
Valentin KleinandClaude Opus 5.5 bd2a7597c5 Associative arrays: ASsociative, Levels and polar ROWs (part of #448) (#455)
Squash of PR #455 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:28:48 -04:00
Valentin KleinandClaude Opus 5.5 e02d1ebd08 Hatch: associative hatches follow their boundary objects; DXF 97/330 source objects (part of #451) (#454)
Squash of PR #454 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:28:33 -04:00
Valentin KleinandClaude Opus 5.5 61812b25de OVERKILL: tolerance, ignored properties, overlapping and end-to-end lines and arcs, polyline segments (fixes #439) (#452)
Squash of PR #452 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:28:18 -04:00
Valentin KleinandClaude Opus 5.5 6f1ca71e98 PolarSnap, relative polar angles, Extension on ellipse and spline ends, tracking options in Drafting Settings (fixes #441) (#450)
Squash of PR #450 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:28:02 -04:00
Valentin KleinandClaude Opus 5.5 a652c57537 MATCHPROP: source/destination picker and Settings (part of #439) (#449)
Squash of PR #449 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:27:48 -04:00
Valentin KleinandClaude Opus 5.5 151722feb0 DATAEXTRACTION and EATTEXT: block and attribute data to rows, CSV and a table (fixes #433) (#447)
Squash of PR #447 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:24:14 -04:00
Valentin KleinandClaude Opus 5.5 9b136d6c19 Draw order: DRAWORDER Above/Under objects, TEXTTOFRONT, HATCHTOBACK, SORTENTSTABLE read (part of #439) (#446)
Squash of PR #446 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:23:59 -04:00
Valentin KleinandClaude Opus 5.5 9427b77209 Temporary tracking point TT and tracking TK at every point prompt (part of #441) (#445)
Squash of PR #445 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:23:45 -04:00
Valentin KleinandClaude Opus 5.5 77de6af455 BATTMAN: edit, remove and reorder attribute definitions; references follow (part of #433) (#444)
Squash of PR #444 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:23:32 -04:00
Valentin KleinandClaude Opus 5.5 7429e7dcbe Grips: multifunctional grip menus for polylines, lines and arcs (fixes #425) (#440)
Squash of PR #440 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:23:18 -04:00
Valentin KleinandClaude Opus 5.5 25c9658908 Select objects: BOX, AUto, SIngle, Multiple, Group and Undo keywords (fixes #428) (#438)
Squash of PR #438 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:23:03 -04:00
Valentin KleinandClaude Opus 5.5 608aa225a7 Grips: hot-grip options (Base point/Copy/Undo/Reference/eXit) and multiple hot grips (part of #425) (#435)
Squash of PR #435 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:22:48 -04:00
Valentin KleinandClaude Opus 5.5 65d5ee48d3 SELECTSIMILAR and object isolation: ISOLATEOBJECTS, HIDEOBJECTS, UNISOLATEOBJECTS (part of #428) (#434)
Squash of PR #434 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:20:02 -04:00
Valentin KleinandClaude Opus 5.5 b3a73626b2 SAVEAS version and binary DXF, default save version (fixes #421) (#431)
Squash of PR #431 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:19:47 -04:00
Valentin KleinandClaude Opus 5.5 9e3379882f TOLERANCE: GD&T feature control frames (fixes #420) (#427)
Squash of PR #427 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:19:32 -04:00
Valentin KleinandClaude Opus 5.5 139d98bf6f DXF/DWG at a chosen version 2000–2018 and binary DXF (part of #421) (#426)
Squash of PR #426 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:19:18 -04:00
Valentin KleinandClaude Opus 5.5 475a70e573 Groups: PICKSTYLE group selection, Ctrl+Shift+A and -GROUP options (fixes #417) (#424)
Squash of PR #424 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:19:04 -04:00
Valentin KleinandClaude Opus 5.5 64eed455e5 Autosave (SAVETIME, SAVEFILEPATH) and Drawing Recovery after a crash (fixes #406) (#416)
Squash of PR #416 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:18:49 -04:00
Valentin KleinandClaude Opus 5.5 b4777fa8b3 fonts: embed craft-fonts when built with CRAFT_FONTS_DIR (#321)
Squash of PR #321 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:13:43 -04:00
Valentin KleinandClaude Opus 5.5 d74f7a4108 Right-to-left drawing text: bidi and Arabic-script shaping (Persian, Arabic, Urdu) (#315)
Squash of PR #315 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:13:29 -04:00
Valentin KleinandClaude Opus 5.5 becb109cc1 Scripts and the command line read a trailing or double space as Enter (fixes #227) (#229)
Squash of PR #229 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:13:15 -04:00
Valentin KleinandClaude Opus 5.5 6900110291 Select objects: W, C, F, WP and CP selection modes (fixes #224) (#226)
Squash of PR #226 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:13:01 -04:00
Valentin KleinandClaude Opus 5.5 4e505a6adb Transparent 'ZOOM/'PAN run nested and resume the interrupted command (fixes #220) (#221)
Squash of PR #221 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:12:47 -04:00
Valentin KleinandClaude Opus 5.5 c35a952271 Print opens a Plot dialog (#160) (#200)
Squash of PR #200 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:12:34 -04:00
Valentin KleinandClaude Opus 5.5 699dd1aeca IMPORT, EXPORT, Plot Preview and Batch Publish; ATTACH, SHARE, 3DORBIT say not available yet (part of #9) (#186)
Squash of PR #186 by @vangel76.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 04:26:39 -04:00
skylar taylor-barrick 50ffb767c7 Merge pull request #456 from skylartaylor/codex/ui-suite-integration-20261010
Add shared workspace docking to CADCraft
2026-10-10 18:54:11 -06:00
skylar taylor-barrick a3f43a700f UI: recover persisted docking without resetting workspace preferences 2026-10-10 18:49:16 -06:00
skylar taylor-barrick 58a8494f98 UI: retain shared workspace while merging current main 2026-10-10 18:31:07 -06:00
Valentin KleinandClaude Opus 5.5 fc4220e9b7 Plot styles: named styles (STB), PLOTSTYLE, STYLESMANAGER and table files (part of #410) (#418)
Layers and objects get a PlotStyle property (ByLayer/ByBlock/name) applied
through named tables (built-in default.stb and monochrome.stb, our own
definitions). DXF keeps the names in the ACAD_PLOTSTYLENAME dictionary of
ACDBPLACEHOLDER objects with group 390 on layers and objects; tables kept in
the drawing travel in a CADCRAFT_PLOTSTYLES XRECORD. PLOTSTYLE sets an object's
or the current (CPLOTSTYLE) style; STYLESMANAGER lists, creates, edits, deletes,
loads and saves tables in our own JSON format (docs/plot-styles.md). A Plot
Style Manager dialog edits a table's styles and the layout's table; the
Properties palette shows the current plot style and table.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:21:24 -04:00
Valentin KleinandClaude Opus 5.5 58a349772e Groups: GROUP, UNGROUP and GROUPEDIT commands; erased members leave their groups (part of #417) (#422)
GROUP makes named or unnamed (*A1, *A2…) groups from the selection, typed
("Select objects or [Name/Description]") or as JSON. UNGROUP removes a group
picked by one of its objects or by name. GROUPEDIT adds and removes objects and
renames a group; removing the last object deletes it. groups.list reports them.
After every command, members that no longer exist leave their groups and empty
groups are deleted (undo restores both). The drawing model and the ACAD_GROUP
DXF round trip already existed.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:20:06 -04:00
Valentin KleinandClaude Opus 5.5 87d1e28345 MLEADER: spline and no-leader types, block content (fixes #408) (#419)
MLEADER's Options answered "not available yet" for Leader type sPline and
None and for Content type Block. Spline leaders now draw as smooth curves
through their points (DXF LEADER path type 72 = 1); None places only the
content at one picked point; Block asks for a block name and how it
attaches (Center extents or Insertion point) and inserts it at the end of
the landing. MLeader gains `spline` and `block` (serde defaults); DXF stays
LEADER + MTEXT/INSERT. PURGE, RENAME, copy/paste, FLATTEN, grips and
extents follow the block content. The choices are remembered like the
other MLEADER options. docs/gaps.md: top-10 row 5, F1 and F10 narrowed.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:20:02 -04:00
Valentin KleinandClaude Opus 5.5 a395ec3d2d SPLINE: Knots, start/end Tangency, toLerance and Object (part of #408) (#413)
SPLINE's Knots, Object, start/end Tangency and toLerance options printed
"not available yet". Fit-point splines now take a knot parametrisation
(chord, square root, uniform), end tangents (clamped cubic with derivative
constraints) and a fit tolerance (least-squares approximation with the
fewest control points that stay within it). The spline keeps these options
so grip and SPLINEDIT edits refit the same way; DXF writes the tolerance
(44) and tangents (12/13) and recovers the parametrisation from the knots.
Object turns 2D/3D polylines with straight segments (PEDIT Spline output)
into splines through their vertices.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:19:57 -04:00
Valentin KleinandClaude Opus 5.5 3ffe1ca2af MTEXT: Height, Justify, Line spacing, Rotation, Style, Width, Columns (part of #408) (#415)
The options at MTEXT's "Specify opposite corner" prompt printed "not
available yet". Each now asks its question and returns to the corner
prompt: Height (also sets TEXTSIZE), Justify (TL..BR, the insertion point
is the box's attachment point), Line spacing (At least/Exactly, then a
factor such as 1.5x or a distance), Rotation (picked, or typed through the
drawing's angle settings; the box turns with it), Style (? lists them),
Width (replaces the opposite corner) and Columns (No; Dynamic and Static
say columns are not available yet). MText stores the line spacing style
(DXF group 73) so Exactly round-trips.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:19:53 -04:00
Valentin KleinandClaude Opus 5.5 ee34f423cc Plot styles: colour-dependent tables apply to PDF plots and layouts (part of #410) (#412)
A PlotStyleTable model in doc with our own built-in tables (default.ctb keeps
object properties, monochrome.ctb prints black, grayscale.ctb prints the grey of
each colour's luminance). The render builder resolves each object's style by its
index colour (true colours by the nearest index) and applies colour, screening,
linetype and lineweight. PLOT/EXPORTPDF use the page setup's table (or the
plotStyleTable option); layouts with Display plot styles (PAGESETUP
displayPlotStyles, DXF plot flag 2) show it on screen and in PNG/SVG exports.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:19:48 -04:00
Valentin KleinandClaude Opus 5.5 f537377355 AUDIT and RECOVER: find and fix database errors, open damaged drawings repaired (part of #406) (#411)
AUDIT checks for missing layers, linetypes, styles and block definitions,
current-style variables naming missing entries, invalid geometry (NaN or
infinite numbers, zero-length lines, zero-radius circles and arcs),
block definitions that contain themselves, duplicate handles, and
references to missing objects (dimension associations, groups,
constraints, viewport layer lists). It asks "Fix any errors detected?
[Yes/No] <N>:"; the JSON form `audit {fix?}` returns a structured
report. RECOVER opens a file through the read hook and applies AUDIT's
fixes. A question prompt now shows its answers without "or".

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:19:44 -04:00
Brandon ThomasandClaude Opus 5.5 315751e3ec Release prep: 0.5.0 and Linux riscv64 release build (#423)
- release.yml: new `linux-riscv64` job (ported from GridCraft): cross-compiles on ubuntu-24.04
  against ports.ubuntu.com riscv64 libraries, packages a tar.gz, smoke-tests the CLI under
  QEMU. The draft-release job now needs it, so SHA256SUMS covers the tarball.
- packaging/linux/package.sh: CROSS_ARCH / CROSS_TARGET / CROSS_COMPILE / EMULATOR support.
- README Downloads and docs/releasing.md list the riscv64 tarball.
- Version 0.4.0 -> 0.5.0 (cargo xtask version set), Cargo.lock refreshed.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:15:06 -04:00
skylar taylor-barrick 1f7f08db8a UI.8: pin final shared dock action labels 2026-10-10 16:01:03 -06:00
skylar taylor-barrick e09fb50627 UI.9: integrate shared workspace docking and preserve CAD controls 2026-10-10 13:30:09 -06:00
678 changed files with 137092 additions and 5549 deletions
+6
View File
@@ -0,0 +1,6 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
reviews:
auto_review:
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
ignore_usernames:
- "dependabot[bot]"
+41
View File
@@ -0,0 +1,41 @@
version: 2
updates:
# Maintain Rust / Cargo dependencies
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
# Consolidate updates into a single PR rather than one PR per crate
groups:
cargo-dependencies:
patterns:
- "*"
commit-message:
prefix: "chore(deps)"
# craft-ui is still on egui 0.36, and two eguis in the graph don't build (#1990). Remove this
# once craft-ui moves to egui 0.37 (storytold/craft-libs#199).
ignore:
- dependency-name: "egui"
versions: [">=0.37"]
- dependency-name: "eframe"
versions: [">=0.37"]
- dependency-name: "egui-wgpu"
versions: [">=0.37"]
- dependency-name: "egui_kittest"
versions: [">=0.37"]
# Maintain GitHub Actions workflows
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
groups:
actions:
patterns:
- "*"
commit-message:
prefix: "ci(deps)"
+30
View File
@@ -0,0 +1,30 @@
name: CI
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
# suite's shared gate workflow in craft-common-actions.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
# A newer push to a PR branch cancels its older run; every push to main runs to the end.
concurrency:
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
gate:
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
timeout-minutes: 90
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
libgl1-mesa-dev
+32
View File
@@ -0,0 +1,32 @@
# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner
# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter.
name: FreeBSD
# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every pull
# request: a drifted dependency still shows up within a day, and always before a release ships.
# PRs that change the FreeBSD workflow or packaging itself still run it.
on:
push:
branches: [release]
pull_request:
paths:
- .github/workflows/freebsd.yml
- packaging/freebsd/**
- packaging/env.sh
schedule:
- cron: "27 3 * * *"
workflow_dispatch:
concurrency:
group: freebsd-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
freebsd:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
+61
View File
@@ -0,0 +1,61 @@
# Evaluates the Nix flake (no build, about a minute): `nix build` / `nix develop` stop at evaluation
# when Cargo.lock gains something nix/package.nix can't vendor, and nothing else would notice.
name: Nix
on:
push:
branches: [main]
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
pull_request:
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nix-${{ github.ref }}
cancel-in-progress: true
jobs:
nix:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
+2 -45
View File
@@ -19,48 +19,5 @@ concurrency:
jobs:
lint:
runs-on: ubuntu-latest
env:
ACTIONLINT_VERSION: 1.7.12
steps:
- uses: actions/checkout@v4
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz -C "$RUNNER_TEMP" actionlint
- name: actionlint
run: |
"$RUNNER_TEMP/actionlint" -color
- name: shellcheck
run: shellcheck packaging/*.sh packaging/*/*.sh
- name: PowerShell
shell: pwsh
run: |
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
Write-Output "ok $($f.Name)"
}
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/cadcraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
# Windows Installer needs Icon ids ending in .ico or .exe, or shortcuts show a blank icon.
if grep -oE '<Icon Id="[^"]*"' packaging/windows/cadcraft.wxs | grep -vE '\.(ico|exe)"$'; then
echo "::error::Icon Id must end in .ico or .exe"; exit 1
fi
desktop-file-validate packaging/linux/ai.storyteller.cadcraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.cadcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.cadcraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.cadcraft.metainfo.xml"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.cadcraft.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.cadcraft" and m["command"] == "cadcraft", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
+59 -415
View File
@@ -1,13 +1,3 @@
# Release pipeline: every push to `release` builds signed installers for every platform and
# creates or updates the draft GitHub Release "CADCraft v<version>". See docs/releasing.md.
#
# Pushes to `release` trigger the run; pushing there is limited by a repository ruleset to org
# admins and the release-managers team. The jobs that sign (macOS, Windows) and the one that
# drafts the GitHub Release run in the `release` environment (restricted to the `release` branch),
# which holds the signing secrets. Every secret is optional: missing ones produce unsigned
# artifacts and a warning, never a failed build. The other jobs (version, Linux, Flatpak, FreeBSD,
# web) sign nothing and get no secrets, so a manual dispatch on any other branch is a dry run of
# them: the environment refuses the signing jobs there, and the draft-release job is skipped.
name: Release
on:
@@ -25,418 +15,72 @@ permissions:
concurrency:
group: release-${{ github.ref }}
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
CADCRAFT_BUILD_SHA: ${{ github.sha }}
INPUT_VERSION: ${{ inputs.version }}
jobs:
version:
name: version
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
prerelease: ${{ steps.v.outputs.prerelease }}
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- id: v
name: Resolve version
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
. packaging/env.sh
v="${INPUT_VERSION#v}"
v="${v:-$VERSION}"
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
exit 1
fi
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
{
echo "version=$v"
echo "date=$(date -u +%Y-%m-%d)"
echo "prerelease=$pre"
} >>"$GITHUB_OUTPUT"
echo "### CADCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
macos:
name: macOS universal
needs: version
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
environment: release
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
- uses: Swatinem/rust-cache@v2
with:
key: release-macos-universal
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$CADCRAFT_VERSION"
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: packaging/macos/import-cert.sh
- name: Build, sign, notarize
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: packaging/macos/package.sh --arch universal
- uses: actions/upload-artifact@v4
with:
name: release-macos
path: dist/release/*
if-no-files-found: error
- name: Remove temporary keychain
if: always()
run: |
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
windows:
name: Windows ${{ matrix.arch }}
needs: version
runs-on: windows-latest
environment: release
strategy:
fail-fast: false
matrix:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
with:
key: release-windows-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
shell: bash
run: cargo xtask version set "$CADCRAFT_VERSION"
- name: Install WiX
shell: pwsh
run: |
dotnet tool install --global wix --version 5.0.2
wix extension add -g WixToolset.UI.wixext/5.0.2
- name: Build, sign, package
shell: pwsh
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@v4
with:
name: release-windows-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux:
name: Linux ${{ matrix.arch }}
needs: version
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@v4
- name: Install build and packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
key: release-linux-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$CADCRAFT_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
run: packaging/linux/package.sh
- name: Check the packages
run: |
dpkg-deb --info dist/release/*.deb
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/cadcraft$|metainfo|applications'
ldd target/release/cadcraft
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.cadcraft.yml')); assert m['id'] == 'ai.storyteller.cadcraft'"
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information is embedded, and the .zsync for delta updates sits beside it.
# Without APPIMAGE_EXTRACT_AND_RUN: with it, the runtime passes --appimage-* options
# on to the app (which then tries to open a window) instead of answering them.
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux-riscv64:
name: Linux riscv64
needs: version
# Cross-compiled on x86_64 (no hosted RISC-V runners) against the runner's own Ubuntu release
# from ports.ubuntu.com, so the binaries need that release's glibc (24.04: 2.39). 22.04's
# riscv64 ports lag its amd64 updates, which breaks the multiarch install. tar.gz only; the
# CLI is smoke-tested under QEMU.
runs-on: ubuntu-24.04
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: riscv64gc-unknown-linux-gnu
- uses: Swatinem/rust-cache@v2
with:
key: release-linux-riscv64
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$CADCRAFT_VERSION"
- name: Install cross-compilation dependencies
run: |
. /etc/os-release
sudo dpkg --add-architecture riscv64
# Pin the existing (archive.ubuntu.com) sources to amd64; riscv64 comes from ports.
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
sudo sed -i '/^Types: deb/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
fi
if [ -f /etc/apt/sources.list ]; then
sudo sed -i 's/^deb /deb [arch=amd64] /g' /etc/apt/sources.list
sudo sed -i 's/^deb-src /deb-src [arch=amd64] /g' /etc/apt/sources.list
fi
for suite in "$VERSION_CODENAME" "$VERSION_CODENAME-updates" "$VERSION_CODENAME-security"; do
echo "deb [arch=riscv64] http://ports.ubuntu.com/ubuntu-ports $suite main universe restricted multiverse"
done | sudo tee /etc/apt/sources.list.d/riscv64.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
gcc-riscv64-linux-gnu binutils-riscv64-linux-gnu libc6-dev-riscv64-cross libc6-dev:riscv64 qemu-user \
libxkbcommon-dev:riscv64 libwayland-dev:riscv64 libx11-dev:riscv64 libxrandr-dev:riscv64 \
libxi-dev:riscv64 libgl1-mesa-dev:riscv64
- name: Build and package (tar.gz)
env:
CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER: riscv64-linux-gnu-gcc
PKG_CONFIG_SYSROOT_DIR: /
PKG_CONFIG_PATH: /usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig
PKG_CONFIG_ALLOW_CROSS: "1"
CROSS_ARCH: riscv64
CROSS_TARGET: riscv64gc-unknown-linux-gnu
CROSS_COMPILE: riscv64-linux-gnu-
EMULATOR: qemu-riscv64
QEMU_LD_PREFIX: /usr/riscv64-linux-gnu
run: packaging/linux/package.sh --formats tar
- uses: actions/upload-artifact@v4
with:
name: release-linux-riscv64
path: dist/release/*.tar.gz
if-no-files-found: error
flatpak:
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader that the host's `appstreamcli compose` (run by
# flatpak-builder) needs for any scalable icon.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: packaging/linux/flatpak-bundle.sh "dist/linux/cadcraft-$CADCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@v4
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
web:
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
TRUNK_VERSION: 0.21.14
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: release-web
- name: Install trunk
run: |
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$CADCRAFT_VERSION"
- name: Build and zip
run: packaging/web/package.sh
- uses: actions/upload-artifact@v4
with:
name: release-web
path: dist/release/*
if-no-files-found: error
freebsd:
name: FreeBSD x86_64
needs: version
# GitHub has no FreeBSD runners: build inside a FreeBSD VM on a Linux runner.
runs-on: ubuntu-latest
# No `environment: release`: this job signs nothing, so it gets no release secrets.
timeout-minutes: 300
env:
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- name: Build and package in a FreeBSD VM
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
envs: "CADCRAFT_VERSION CADCRAFT_BUILD_DATE CADCRAFT_BUILD_SHA INPUT_VERSION"
copyback: true
prepare: |
pkg install -y git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2 alsa-lib
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
run: |
set -e
. "$HOME/.cargo/env"
git config --global --add safe.directory "*"
if [ -n "$INPUT_VERSION" ]; then cargo xtask version set "$CADCRAFT_VERSION"; fi
cargo build --release --locked -p cadcraft -p cadcraft-cli
name="cadcraft-$CADCRAFT_VERSION-freebsd-x86_64"
mkdir -p "dist/release/$name"
cp target/release/cadcraft target/release/cadcraft-cli README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md "dist/release/$name/"
mkdir -p "dist/release/$name/icons"
cp -R assets/app-icon/hicolor "dist/release/$name/icons/" 2>/dev/null || true
(cd dist/release && tar -czf "$name.tar.gz" "$name" && rm -rf "$name")
# Keep the copy back to the runner small.
rm -rf target
- uses: actions/upload-artifact@v4
with:
name: release-freebsd
path: dist/release/*
if-no-files-found: error
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
release:
name: Draft GitHub Release
needs: [version, macos, windows, linux, linux-riscv64, flatpak, web, freebsd]
# Only the `release` branch publishes; a dry run on another branch stops before this job.
if: github.ref == 'refs/heads/release'
runs-on: ubuntu-latest
environment: release
needs: git-sources
permissions:
# The reusable release workflow tags and uploads the draft release.
contents: write
env:
VERSION: ${{ needs.version.outputs.version }}
PRERELEASE: ${{ needs.version.outputs.prerelease }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/download-artifact@v4
with:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Checksums
working-directory: artifacts
run: |
sha256sum -- * | tee SHA256SUMS.txt
- name: Create or update the draft release
working-directory: artifacts
run: |
tag="v$VERSION"
title="CADCraft v$VERSION"
pre=()
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
if [ "$draft" != "true" ]; then
echo "::error::Release $tag is already published. Bump the version (cargo xtask version set) before pushing to release."
exit 1
fi
echo "Updating draft $tag: replacing its assets"
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
gh release delete-asset "$tag" "$asset" --yes
done
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
gh release upload "$tag" --clobber -- *
else
echo "Creating draft $tag"
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
fi
{
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
echo
sed 's/^/ /' SHA256SUMS.txt
} >>"$GITHUB_STEP_SUMMARY"
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
app-name: cadcraft
app-title: CADCraft
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
version: ${{ inputs.version }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
+21
View File
@@ -0,0 +1,21 @@
name: SonarCloud
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
secrets: inherit
+32
View File
@@ -0,0 +1,32 @@
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
# binaries are ARM64, run the CLI natively, and uninstall.
name: Windows ARM64
# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a
# day, and always before a release ships), and on PRs that change the Windows packaging itself.
on:
schedule:
- cron: "3 5 * * *"
push:
branches: [release]
pull_request:
paths:
- .github/workflows/windows-arm64.yml
- packaging/windows/**
workflow_dispatch:
concurrency:
group: windows-arm64-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
windows-arm64:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
with:
app-name: cadcraft
app-dir: CADCraft
+2 -1
View File
@@ -24,12 +24,13 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
## 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`), never a `Cargo.toml` dependency. Code and tests must work without it.
- **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/<app>-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`.
- **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`.
+14
View File
@@ -57,3 +57,17 @@ Generated-in-code assets are original and have no file to list:
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk | Original Ukrainian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `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) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending |
+1 -1
View File
@@ -24,7 +24,7 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
## 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`), never a `Cargo.toml` dependency. Code and tests must work without it.
- **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/<app>-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.
Generated
+339 -152
View File
@@ -4,9 +4,9 @@ version = 4
[[package]]
name = "acadrust"
version = "0.6.3"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7df99ae4f5a6d0147907f9976fe1dd166d01e72ab1a93820b50242937c5797e6"
checksum = "5eaa72520f70eb6f7f09b06f44e1ed0d8fad5fa743364f2c3715c30df962ec7c"
dependencies = [
"anyhow",
"bitflags 2.13.2",
@@ -18,6 +18,7 @@ dependencies = [
"itoa",
"memmap2",
"nom",
"oem_cp",
"once_cell",
"rayon",
"ryu",
@@ -45,7 +46,7 @@ dependencies = [
"accesskit",
"accesskit_consumer 0.36.0",
"atspi-common",
"phf",
"phf 0.13.1",
"serde",
"zvariant",
]
@@ -208,9 +209,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arboard"
version = "3.6.1"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"
checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917"
dependencies = [
"clipboard-win",
"image",
@@ -222,7 +223,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
"x11rb",
]
@@ -433,6 +434,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "basic-udev"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a45f9771ced8a774de5e5ebffbe520f52e3943bf5a9a6baa3a5d14a5de1afe6"
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -540,25 +547,31 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cadcraft"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-engine",
"cadcraft-io",
"cadcraft-mcp",
"cadcraft-ui-egui",
"chrono",
"eframe",
"egui",
"hidapi",
"log",
"muda",
"objc2-app-kit 0.3.2",
"rfd",
"serde_json",
"sys-locale",
"windows",
"winit",
"winresource",
"zbus",
]
[[package]]
name = "cadcraft-cli"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-engine",
"cadcraft-io",
@@ -569,14 +582,14 @@ dependencies = [
[[package]]
name = "cadcraft-color"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"serde",
]
[[package]]
name = "cadcraft-constraints"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-doc",
"cadcraft-geom",
@@ -586,7 +599,7 @@ dependencies = [
[[package]]
name = "cadcraft-doc"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-color",
"cadcraft-geom",
@@ -597,28 +610,34 @@ dependencies = [
[[package]]
name = "cadcraft-dwg"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"acadrust",
]
[[package]]
name = "cadcraft-dxf"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"encoding_rs",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "cadcraft-engine"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-color",
"cadcraft-constraints",
"cadcraft-doc",
"cadcraft-dxf",
"cadcraft-fonts",
"cadcraft-geom",
"cadcraft-io",
"cadcraft-render",
"craft-docpath",
"libc",
"log",
"rstar",
"serde",
@@ -628,69 +647,82 @@ dependencies = [
[[package]]
name = "cadcraft-fonts"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-geom",
"skrifa 0.47.0",
"harfrust 0.14.0",
"skrifa 0.48.0",
"unicode-bidi",
]
[[package]]
name = "cadcraft-geom"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"serde",
]
[[package]]
name = "cadcraft-io"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"acadrust",
"cadcraft-color",
"cadcraft-doc",
"cadcraft-dwg",
"cadcraft-dxf",
"cadcraft-fonts",
"cadcraft-geom",
"cadcraft-render",
"miniz_oxide 0.8.9",
"miniz_oxide 0.9.1",
"quick-xml 0.42.0",
"serde",
"serde_json",
"thiserror 2.0.21",
"tiny-skia",
]
[[package]]
name = "cadcraft-mcp"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-engine",
"cadcraft-io",
"cadcraft-render",
"getrandom 0.4.3",
"log",
"serde_json",
]
[[package]]
name = "cadcraft-render"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-color",
"cadcraft-doc",
"cadcraft-fonts",
"cadcraft-geom",
"lyon_tessellation",
"rayon",
"serde_json",
"tiny-skia",
]
[[package]]
name = "cadcraft-ui-egui"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-color",
"cadcraft-doc",
"cadcraft-engine",
"cadcraft-fonts",
"cadcraft-geom",
"cadcraft-render",
"chrono",
"craft-ui",
"egui",
"egui-wgpu",
"egui_kittest",
"image",
"log",
"naga",
@@ -701,7 +733,7 @@ dependencies = [
[[package]]
name = "cadcraft-web"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"cadcraft-engine",
"cadcraft-io",
@@ -798,6 +830,15 @@ dependencies = [
"libc",
]
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"num-traits",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -827,6 +868,16 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "colored"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
"windows-sys 0.59.0",
]
[[package]]
name = "combine"
version = "4.6.8"
@@ -892,6 +943,20 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675"
dependencies = [
"egui",
"serde",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -947,6 +1012,19 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
name = "dify"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ce0fb972943b4e88cd03b8f92953df0c71bb05e0bde8e5b684895d808013cc"
dependencies = [
"anyhow",
"colored",
"getopts",
"image",
"rayon",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -1133,6 +1211,27 @@ dependencies = [
"winit",
]
[[package]]
name = "egui_kittest"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5eb3f3effb2726fee23449293e67acbf6cc6ce35525b1722bd5743bb348114d5"
dependencies = [
"dify",
"eframe",
"egui",
"egui-wgpu",
"image",
"kittest",
"log",
"open",
"pollster 1.0.1",
"serde",
"tempfile",
"toml",
"wgpu",
]
[[package]]
name = "either"
version = "1.19.0"
@@ -1213,7 +1312,7 @@ dependencies = [
"emath",
"epaint_default_fonts",
"font-types",
"harfrust",
"harfrust 0.12.0",
"log",
"nohash-hasher",
"parking_lot",
@@ -1328,6 +1427,12 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "float_next_after"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -1336,9 +1441,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
version = "0.12.6"
version = "0.12.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274"
checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
dependencies = [
"bytemuck",
"serde",
@@ -1445,6 +1550,15 @@ dependencies = [
"windows-link",
]
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width",
]
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -1620,6 +1734,18 @@ dependencies = [
"smallvec",
]
[[package]]
name = "harfrust"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86aa776d6d32b072119e1f1650f4db843ff4382a4aaa6a2c9c4e35703cd377cb"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts 0.45.1",
"smallvec",
]
[[package]]
name = "hash32"
version = "0.3.1"
@@ -1671,6 +1797,21 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hidapi"
version = "2.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "818c0e1d27887aaf76fe737042e27a66b796a7b099e6d2e1a72d106c2dff3fa6"
dependencies = [
"basic-udev",
"cc",
"cfg-if",
"libc",
"nix",
"pkg-config",
"windows-sys 0.61.2",
]
[[package]]
name = "icu_collections"
version = "2.3.0"
@@ -1785,7 +1926,7 @@ dependencies = [
"byteorder-lite",
"moxcms",
"num-traits",
"png 0.18.1",
"png",
"tiff",
"zune-core",
"zune-jpeg",
@@ -1801,6 +1942,25 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "is-docker"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
dependencies = [
"once_cell",
]
[[package]]
name = "is-wsl"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
dependencies = [
"is-docker",
"once_cell",
]
[[package]]
name = "itertools"
version = "0.15.0"
@@ -1922,6 +2082,16 @@ version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
[[package]]
name = "kittest"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ceaa75eb0036a32b6b9833962eb18137449e9817e2e586006471925b727fd5"
dependencies = [
"accesskit",
"accesskit_consumer 0.35.0",
]
[[package]]
name = "kurbo"
version = "0.13.1"
@@ -1935,10 +2105,16 @@ dependencies = [
]
[[package]]
name = "libc"
version = "0.2.190"
name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libloading"
@@ -2013,6 +2189,38 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lyon_geom"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92"
dependencies = [
"arrayvec",
"euclid",
"num-traits",
]
[[package]]
name = "lyon_path"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e"
dependencies = [
"lyon_geom",
"num-traits",
]
[[package]]
name = "lyon_tessellation"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43b8dcf906637ecef61b3c0740c7a4e7f27caeb31257cfac0cc579ce15be6005"
dependencies = [
"float_next_after",
"lyon_path",
"num-traits",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -2075,9 +2283,9 @@ dependencies = [
[[package]]
name = "muda"
version = "0.21.0"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6744ab645ebe79f9c428455c7cb9dfa4275fa3b50a25408e08f927da8dc618c"
checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03"
dependencies = [
"crossbeam-channel",
"dpi",
@@ -2086,8 +2294,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"once_cell",
"png 0.18.1",
"png",
"thiserror 2.0.21",
"windows-sys 0.61.2",
]
@@ -2166,6 +2373,18 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "nix"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -2525,12 +2744,31 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "oem_cp"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c7959d3349f484aec36462f98226983578bf7d33f9b034c32967489c7000e1f"
dependencies = [
"phf 0.11.3",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "open"
version = "5.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc"
dependencies = [
"is-wsl",
"libc",
]
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -2608,6 +2846,15 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "phf"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
dependencies = [
"phf_shared 0.11.3",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -2615,7 +2862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros",
"phf_shared",
"phf_shared 0.13.1",
"serde",
]
@@ -2626,7 +2873,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -2636,12 +2883,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "phf_shared"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
@@ -2700,19 +2956,6 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "png"
version = "0.17.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
dependencies = [
"bitflags 1.3.2",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "png"
version = "0.18.1"
@@ -2836,6 +3079,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -2914,13 +3166,15 @@ dependencies = [
[[package]]
name = "read-fonts"
version = "0.44.0"
version = "0.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
checksum = "4edc8db0d972de88e53a085b1f01fb3fbdae7bb0cb7a0ce2b2f8285a412fe3ef"
dependencies = [
"bytemuck",
"foldhash",
"font-types",
"once_cell",
"yoke",
]
[[package]]
@@ -2999,9 +3253,9 @@ dependencies = [
[[package]]
name = "rstar"
version = "0.12.2"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "421400d13ccfd26dfa5858199c30a5d76f9c54e0dba7575273025b43c5175dbb"
checksum = "5912b862fa5ffb462607bfd1e35036c458c537921f508c8235a83d5f3987edfe"
dependencies = [
"heapless",
"num-traits",
@@ -3132,9 +3386,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.151"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
@@ -3219,12 +3473,12 @@ dependencies = [
[[package]]
name = "skrifa"
version = "0.47.0"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034"
dependencies = [
"bytemuck",
"read-fonts 0.44.0",
"read-fonts 0.45.1",
]
[[package]]
@@ -3470,24 +3724,24 @@ dependencies = [
[[package]]
name = "tiny-skia"
version = "0.11.4"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
dependencies = [
"arrayref",
"arrayvec",
"bytemuck",
"cfg-if",
"log",
"png 0.17.16",
"png",
"tiny-skia-path",
]
[[package]]
name = "tiny-skia-path"
version = "0.11.4"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
dependencies = [
"arrayref",
"bytemuck",
@@ -3622,6 +3876,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "unicode-bidi"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
[[package]]
name = "unicode-general-category"
version = "1.1.0"
@@ -3902,7 +4162,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
"quick-xml",
"quick-xml 0.41.0",
"quote",
]
@@ -4259,7 +4519,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
"windows-targets",
]
[[package]]
@@ -4268,16 +4528,7 @@ version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
"windows-targets",
]
[[package]]
@@ -4295,31 +4546,14 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link",
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm 0.53.1",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
"windows_x86_64_msvc 0.53.1",
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
@@ -4337,96 +4571,48 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winit"
version = "0.30.13"
@@ -4489,9 +4675,9 @@ dependencies = [
[[package]]
name = "winresource"
version = "0.1.31"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087"
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
dependencies = [
"toml",
"version_check",
@@ -4574,8 +4760,9 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.5.0"
version = "0.12.0"
dependencies = [
"chrono",
"serde_json",
]
+19 -3
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
# default-members
[workspace.package]
version = "0.5.0"
version = "0.12.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.90"
@@ -24,21 +24,35 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
# foundation
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
rayon = "1"
# rendering / formats
tiny-skia = { version = "0.11", default-features = false, features = ["std", "simd", "png-format"] }
skrifa = "0.47"
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd", "png-format"] }
lyon_tessellation = "1.0.22"
skrifa = "0.48"
# Text shaping (OpenType GSUB/GPOS, HarfBuzz port on read-fonts; egui's epaint is still on 0.12,
# so the graph has both) and the Unicode Bidirectional Algorithm for right-to-left drawing text.
harfrust = "0.14"
unicode-bidi = "0.3.18"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
encoding_rs = "0.8.35"
# XML for the SVG reader (streaming parser, no entity expansion beyond the five predefined ones)
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
egui = "0.36"
egui_kittest = "0.36"
eframe = { version = "0.36", default-features = false }
egui-wgpu = "0.36"
rfd = "0.17"
@@ -55,9 +69,11 @@ type_complexity = "allow"
[profile.dev.package."*"]
opt-level = 2
debug = false
[profile.dev]
opt-level = 1
debug = "line-tables-only"
[profile.release]
opt-level = 3
+78 -6
View File
@@ -7,14 +7,18 @@
</a>
</p>
<p align="center">
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.cadcraft.png" width="128" height="128" alt="CADCraft icon: a drafting set square and compass arc on a blue grid tile">
</p>
<h1 align="center">CADCraft</h1>
<p align="center">
<b>Computer-aided design and drafting; an open-source, clean-room reimplementation of Autodesk AutoCAD, rebuilt in pure Rust.</b>
<b>Computer-aided design and drafting; an open-source, modern 2D and 3D CAD application, built in pure Rust.</b>
</p>
<p align="center">
A fast, open-source take on the AutoCAD workflow: the command line, object snaps, layers,
A fast, open-source CAD workflow: the command line, object snaps, layers,
dimensions, hatches, blocks and DXF drawings you already know. It runs natively on macOS,
Windows, Linux and FreeBSD, and in the browser via WebAssembly.<br>
<i>By the ArtCraft team.</i>
@@ -26,6 +30,9 @@
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-0b6f88?style=flat-square">
<img alt="Agent-drivable over MCP" src="https://img.shields.io/badge/agents-MCP-14a3c7?style=flat-square">
<img alt="Status: early development" src="https://img.shields.io/badge/status-early%20development-f07a3a?style=flat-square">
<br>
<a href="https://sonarcloud.io/project/overview?id=storytold_cadcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/cadcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
</p>
<p align="center">
@@ -111,11 +118,14 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English and Ukrainian (Українська), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar) and Turkish (Türkçe), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
Desktop and web UI builds require Rust 1.95 or later. The core workspace's declared minimum
remains Rust 1.90.
```sh
git clone https://github.com/storytold/cadcraft
cd cadcraft
@@ -135,7 +145,13 @@ The web build: `cd apps/cadcraft-web && trunk serve` (needs [trunk](https://trun
### Fonts
CADCraft never ships fonts; it uses the TrueType/OpenType fonts installed on your system. SHX
CADCraft has no fonts in its repository; it uses the TrueType/OpenType fonts installed on your
system. Builds made with the optional [craft-fonts](https://github.com/storytold/craft-fonts)
input (`CRAFT_FONTS_DIR=<absolute path to a checkout> cargo build --release`) also embed its
fonts: BIZ UDPGothic, BIZ UDMincho and Shippori Mincho (Japanese) and Noto Sans Arabic (the web
build, which has no system fonts, only BIZ UDPGothic Regular and Noto Sans Arabic). A text style
can use them by family name, and they draw characters a text's font lacks when no installed
wide-coverage CJK font has them. Without `CRAFT_FONTS_DIR` nothing is embedded. SHX
fonts (including big fonts such as `chineset.shx`) aren't read yet: text in an SHX style is drawn
with our own stroke font, and any character a text's font lacks (CJK, for example) is drawn from
an installed font that has it, preferring wide-coverage fonts such as Noto Sans CJK, Source Han
@@ -149,6 +165,26 @@ run) an environment variable, steer this:
`.` clears either one.
**Your own fonts.** Any `.ttf`, `.otf` or `.ttc` font works: install it in the system font folder
(Windows `C:\Windows\Fonts` or per-user fonts, macOS `/Library/Fonts` or `~/Library/Fonts`,
Linux and the BSDs `/usr/share/fonts`, `/usr/local/share/fonts`, `~/.local/share/fonts` or
`~/.fonts`) and name it in a text style (`STYLE`, or `style {"name":"FA","font":"Vazirmatn"}`)
by file name (`Vazirmatn-Regular.ttf`) or family name (`Vazirmatn`), or inline in MTEXT with
`\fVazirmatn;`. Restart CADCraft after installing a font: the font folders are scanned once.
**Right-to-left text (Persian, Arabic, Urdu, Hebrew).** TEXT and MTEXT lines are laid out with the
Unicode Bidirectional Algorithm (the paragraph direction comes from its first letter, so numbers
and Latin words inside Persian text keep their own order), and Arabic-script text is shaped with
OpenType (contextual letter forms, lam-alef and other ligatures, ZWNJ / ZWJ, mark positioning).
Justification (left, centre, right, MTEXT attachment and wrapping) still refers to the text's box.
Our stroke font has no Arabic letters, so Persian in a stroke-font style is drawn from an
installed font that has them: Vazirmatn, Noto Naskh Arabic, Noto Sans Arabic, Segoe UI, Tahoma,
Arial and DejaVu Sans are looked for first. To choose the font, install a free Persian font such
as [Vazirmatn](https://github.com/rastikerdar/vazirmatn) (SIL Open Font License) and either use it
in the text style or set `FONTFALLBACK` (`CADCRAFT_FONTFALLBACK="Vazirmatn"`). Formatting changes
inside a word (an MTEXT colour change in the middle of a Persian word) break the joining at that
point.
### Logs
The desktop app writes its `log` records to standard error and to `logs/cadcraft.log` in the
@@ -196,6 +232,9 @@ MCP tools include `command_line` (type at the prompt), `execute` (any command wi
`screenshot` and `ui_click`. The desktop app's JSON control channel is documented in
[docs/control-protocol.md](docs/control-protocol.md).
To run LISP routines, scripts and alias files, or to drive CADCraft from your own programs, see
[docs/customization.md](docs/customization.md).
## Architecture
```text
@@ -213,10 +252,35 @@ apps: cadcraft · cadcraft-cli · cadcraft-web
Nothing below `ui-egui` knows about egui, so the front end can be replaced. `cargo xtask ci`
checks formatting, clippy, tests, asset attribution, the crate layering and the wasm build.
Drafting and layer-palette icon buttons use the pinned `craft-ui` button component for interaction,
accessible labels and keyboard focus. CADCraft keeps its multicolor icon painter, dark palette,
disabled tint and tool commands. The native host saves workspace visibility and toolset choices
atomically; `CADCRAFT_CONFIG_DIR` selects an isolated profile. Compact toolbar groups move into a
More menu, and status readouts truncate with a full-value tooltip before they reach layout tabs.
Painted toolbar and tab controls
have accessible labels and visible keyboard focus. Property controls remain application-specific.
## Accessibility
### System cursor
Over the drawing area CADCraft hides the system cursor and draws its own crosshair. Tools that follow the system cursor (Windows Magnifier set to follow or centre the mouse pointer, other screen magnifiers, screen recorders, remote desktops) lose track of it there. Turn on **View ▸ Accessibility ▸ Show System Cursor** to keep a small system crosshair visible at the centre of the drawn one, or start CADCraft with the environment variable `CADCRAFT_SYSTEM_CURSOR=1` (on Windows, set it once with `setx CADCRAFT_SYSTEM_CURSOR 1` and start CADCraft again). Agents can switch it with the control channel: `ui.set {"systemCursor": true}`.
### Animation effects
CADCraft follows the operating system's animation setting. When the system is set to show no animations, dialogs, menus and tooltips appear at once instead of fading in, collapsing sections and scroll bars change at once, and the mouse wheel scrolls lists a whole step at a time instead of gliding. Zooming the drawing with the wheel always moves a whole step; with Ctrl held (a touchpad pinch, on Windows) it glides to the new zoom only while animation effects show.
| System | Where the setting is |
|---|---|
| Windows | Settings ▸ Accessibility ▸ Visual effects ▸ Animation effects |
| macOS | System Settings ▸ Accessibility ▸ Reduce motion |
| Linux, BSD | the desktop's reduced-motion (or animations) setting, read through the XDG Desktop Portal |
| Web | the browser's `prefers-reduced-motion` |
A change to the system setting is picked up while CADCraft runs, within a few seconds. To choose for CADCraft alone, use **View ▸ Accessibility ▸ Animation Effects**: **Use System Setting** (the default), **On** or **Off**. Options ▸ Display has the same choice. Agents can set it with the control channel: `ui.set {"animations": "off"}` (`"system"`, `"on"` or `"off"`), and `ui.inspect` reports whether animations show (`animations`).
Drafting feedback is not an animation effect and stays as it is: rubber bands and previews, snap markers, the pause that acquires an object snap tracking point, the text cursor's blink, the spinner shown while a drawing opens, and pan and zoom, which follow the pointer and the wheel directly.
## Roadmap
See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of remaining work, and [docs/gaps.md](docs/gaps.md) for everything still missing.
@@ -225,6 +289,14 @@ See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of
**Download CADCraft** from GitHub: the [latest release](https://github.com/storytold/cadcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/cadcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
> [!WARNING]
> Download official CADCraft builds from the [storytold/cadcraft releases](https://github.com/storytold/cadcraft/releases). Verify that the repository owner is `storytold`. Before you run a download, check that its checksum matches the line for that file in the release's `SHA256SUMS.txt`:
>
> ```sh
> shasum -a 256 cadcraft-<ver>-macos-universal.dmg # macOS (on Linux: sha256sum FILE)
> Get-FileHash .\cadcraft-<ver>-windows-x64.msi # Windows PowerShell
> ```
### Windows
| Build | Installer | Portable |
@@ -340,9 +412,9 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif
part of this repository and CADCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<sub>Autodesk, AutoCAD and DWG are trademarks or registered trademarks of Autodesk, Inc. in the United States and/or other countries. CADCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Autodesk, Inc.; these names are used only to describe the workflows and file formats it is compatible with.</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
</p>
Tool Sets, Layers, and Properties can be regrouped, split, floated within the app window, closed, and reopened. The drawing canvas stays visible and cannot be closed or turned into a tab. Drag a panel header to a target edge or another header. Its context menu offers Float panel, Move to group, and Close panel. Existing panel toggles reopen panels at their saved location; Reset Panel Layout restores the app layout. Floating panels remain inside the current app window.
+18 -7
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, ~2 points (38% → 40% ready for real work) and ~125–190 Opus 5.5 hours away (the four failing core workflows of the [alpha gate](docs/roadmap.md#alpha-gate))
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (hours to ~95% for each readiness number) · **Target:** Autodesk AutoCAD 2027
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** 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
@@ -10,8 +10,8 @@ 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 (no block editor, REFEDIT or xrefs); plots ignore plot styles; and a DWG saved by
CADCraft drops everything it doesn't model, is always R2000 and has never been checked in
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
AutoCAD. Dimensioning passes. Ready for real work (≈ 38%) is also under the ~40% alpha bar. Beta
is ≈ 600–930 h away.
@@ -80,8 +80,8 @@ 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 only. Detail:
[localization-parity.md](docs/localization-parity.md).
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus partial
Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity.md).
| Language | Status | UI translated |
|---|---|---:|
@@ -94,11 +94,12 @@ AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English only. D
| Portuguese | none | 0% |
| Indonesian | none | 0% |
| Japanese | none | 0% |
| German | 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% |
Other languages shipped: Ukrainian, partial (936 catalog rows, landed with #36; engine messages stay English).
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.
## Upcoming
@@ -118,6 +119,9 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md)
| Date | Entry |
|---|---|
| 2026-10-14 | HATCHEDIT adds boundaries from internal points or closed objects and removes selected loops in the dialog, command line and JSON command; associative links and undo are covered by tests. |
| 2026-10-12 | TRIM: a pick after a closed polyline's last cut keeps only the complementary run instead of an extra circuit of the outline (#726) |
| 2026-10-12 | HATCHEDIT refuses an explicit bad `scale` or `angle` before it edits anything, so a rejected request leaves the drawing, undo and redo as they were (#724) |
| 2026-10-10 | Merged main: Ukrainian interface (#36, first string catalog), Dynamic Input pointer boxes with Tab and relative entry (#60), press-drag selection windows (#63), WIPEOUT and hatch gradients kept through DXF/DWG save (#147, #162), SETVAR DIM* as style overrides (#129), UNITS dialog (#38), close-window save prompt (#47), DIMANGULAR on circles (#20), cargo fmt fixed on main. UI/UX 40% → 43% (dynamic input 15% → 45%), localization 3% → 5%; ready for real work ≈ 37% → 38% (weighted 37.2% → 37.7%), mainstream 27% → 28%, essentials 45% → 46%. Beta is now ~37 points away; hours unchanged within rounding. |
| 2026-10-10 | Added mainstream practitioner (≈ 27%) and essentials user (≈ 45%) numbers; ready for real work unchanged at ≈ 37%. User evidence: 2 praise comments, 0 "switched from AutoCAD" reports, 27 of 37 open issues on the core path. |
| 2026-10-10 | Stage re-normalized from alpha to **pre-alpha** under the craftrules core-workflow gate: drafting with tracking, blocks, plotting and lossless DWG save fail; dimensioning passes. Alpha is ≈ 125–190 h away. |
@@ -131,9 +135,16 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md)
| Date | Change | Summary |
|---|---|---|
| 2026-10-14 | minor | Progress log: HATCHEDIT boundary add/remove |
| 2026-10-12 | trivial | Progress log: closed-polyline TRIM (#726) |
| 2026-10-12 | trivial | Progress log: HATCHEDIT numeric validation (#724) |
| 2026-10-10 | minor | Merged main's changes (Ukrainian catalog, dynamic input pointer boxes, DXF fixes); UI/UX and localization numbers updated |
| 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% for each number |
| 2026-10-10 | minor | Mainstream practitioner and essentials user headline numbers |
| 2026-10-10 | minor | Stage alpha → pre-alpha under the core-workflow gate; banner, why, headline row |
| 2026-10-10 | major | Restructured to the progress-docs standard (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; milestone detail moved to docs/roadmap.md, parity assessment to docs/target-app-parity.md |
| 2026-10-07 | major | Alpha checklist, milestone table, ≈ 29% weighted parity estimate |
## Shared UI workspace integration
Tool Sets, Layers and Properties use shared docking with persisted layouts, keyboard focus and compact toolbar overflow. No milestone percentage change.
+174 -22
View File
@@ -5,26 +5,63 @@
//! cadcraft-cli convert IN.dxf OUT.(dxf|svg|png) [--window x0,y0,x1,y1 | --view extents|current]
//! cadcraft-cli run [FILE|--sample|--metric] [--script TEXT|--script-file F.scr] [--cmd 'id {json}']... [--save OUT] [--export OUT.png] [--window ... | --view ...]
//! cadcraft-cli commands [FILTER] command catalog (JSON)
//! cadcraft-cli mcp [--connect HOST:PORT] MCP server on stdio (headless or bridged to the app)
//! cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]] MCP server on stdio (headless or bridged to the app)
//! cadcraft-cli perf [N] timing table on a synthetic N-entity drawing
//! cadcraft-cli perf FILE canvas display-list build of a drawing, zoomed in step by step
//! cadcraft-cli sample (bracket|floorplan) OUT write a built-in sample drawing
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
/// `println!` that doesn't panic when stdout is closed (`cadcraft-cli commands | head`) with
/// "failed printing to stdout: Broken pipe (os error 32)". Once stdout has failed, later output is
/// dropped and the work goes on: see `stdout_failed`.
macro_rules! outln {
($($arg:tt)*) => {{
use std::io::Write as _;
if !$crate::stdout_gone() {
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
$crate::stdout_failed(e);
}
}
}};
}
use std::process::ExitCode;
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_engine::{Session, View};
use serde_json::{Value, json};
use std::sync::atomic::{AtomicBool, Ordering};
/// Set once a write to stdout has failed; later output is dropped.
static STDOUT_GONE: AtomicBool = AtomicBool::new(false);
/// Set when stdout failed for a reason other than a closed reader: the exit status becomes 1.
static STDOUT_ERROR: AtomicBool = AtomicBool::new(false);
fn stdout_gone() -> bool {
STDOUT_GONE.load(Ordering::Relaxed)
}
/// stdout went away. The program doesn't stop there: the rest of `run` (later `--cmd` results,
/// `--save`, `--export`) still happens, so `cadcraft-cli run … --save out.dxf | head` keeps the
/// drawing. A reader that stopped early (a closed pipe) is not an error, as in ripgrep; any other
/// write error is reported and makes the exit status 1.
fn stdout_failed(e: std::io::Error) {
if STDOUT_GONE.swap(true, Ordering::Relaxed) || e.kind() == std::io::ErrorKind::BrokenPipe {
return;
}
eprintln!("cadcraft-cli: can't write to stdout: {e}");
STDOUT_ERROR.store(true, Ordering::Relaxed);
}
const USAGE: &str = "usage:
cadcraft-cli info FILE.dxf
cadcraft-cli convert IN.dxf OUT.(dxf|dwg|svg|png|pdf) [FRAMING]
cadcraft-cli run [FILE | --sample | --metric] [--script TEXT] [--script-file F.scr] [--cmd 'id {json}']... [--save OUT.dxf] [--export OUT.(png|svg|pdf)] [FRAMING]
cadcraft-cli commands [FILTER]
cadcraft-cli mcp [--connect HOST:PORT]
cadcraft-cli perf [N]
cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]]
cadcraft-cli perf [N | FILE]
cadcraft-cli sample (bracket|floorplan) OUT.(dxf|dwg|svg|png)
cadcraft-cli --version
@@ -130,7 +167,15 @@ fn install_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plot(d, space, opts).map_err(|e| e.to_string())),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
}
@@ -169,7 +214,7 @@ fn info(path: &str) -> Result<(), String> {
let mut s = Session::empty();
open(&mut s, path)?;
let v = s.execute("drawing.inspect", &json!({ "entities": false })).map_err(|e| e.to_string())?;
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
Ok(())
}
@@ -182,7 +227,7 @@ fn export_framed(s: &Session, out: &str, window: Option<Bounds2>) -> Result<(),
let bytes = cadcraft_io::write_framed(d, out, window).map_err(|e| e.to_string())?;
std::fs::write(out, &bytes).map_err(|e| format!("{out}: {e}"))?;
eprintln!("wrote {out} ({} bytes)", bytes.len());
if !cadcraft_io::is_image(out) {
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
eprintln!("{m}");
@@ -227,10 +272,48 @@ fn convert(args: &[String]) -> Result<(), String> {
check_framed_output(framing, Some(o))?;
let mut s = Session::empty();
open(&mut s, i)?;
if let Some(m) = skipped_message(s.doc().map_err(|e| e.to_string())?, i) {
eprintln!("{m}");
}
if cadcraft_io::is_image(o)
&& let Some(m) = undrawn_message(s.doc().map_err(|e| e.to_string())?, i)
{
eprintln!("{m}");
}
let window = export_window(&s, framing, None)?;
export_framed(&s, o, window)
}
/// The warning for the model-space entities of `path` an image can't show, by type (those kept
/// as unknown objects, `Proxy` in `info`), or `None` when there are none.
fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option<String> {
let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
for e in d.model.iter() {
if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind {
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 list: Vec<String> = 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(", ")))
}
/// The warning for the records of `path` the reader could not place, or `None` when there are none.
fn skipped_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option<String> {
let n = d.skipped_records.values().fold(0usize, |a, n| a.saturating_add(*n));
if n == 0 {
return None;
}
let list: Vec<String> = d.skipped_records.iter().map(|(section, n)| format!("{section}: {n}")).collect();
let records = if n == 1 { "record" } else { "records" };
Some(format!("{path}: {n} {records} could not be read and are left out ({})", list.join(", ")))
}
fn run(args: &[String]) -> Result<(), String> {
let mut s = Session::empty();
let mut it = args.iter();
@@ -274,7 +357,7 @@ fn run(args: &[String]) -> Result<(), String> {
let params: Value = serde_json::from_str(json).map_err(|e| format!("--cmd {id}: {e}"))?;
let r = s.execute(id, &params).map_err(|e| e.to_string())?;
if !r.is_null() {
println!("{r}");
outln!("{r}");
}
}
}
@@ -354,11 +437,55 @@ fn synthetic(n: usize, side: f64) -> Result<cadcraft_engine::doc::Drawing, Strin
Ok(dr)
}
/// `perf FILE`: the display list built as the canvas builds it (a 1600 x 1000 px view at the
/// drawing's centre: tolerance, dash level of detail and view window from the zoom band), at
/// zoom extents and zoomed in 4x at a time, next to the full-detail build plots use.
fn perf_file(path: &str) -> Result<(), String> {
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_engine::render::{Options, build};
use std::time::Instant;
let ms = |t: Instant| t.elapsed().as_secs_f64() * 1000.0;
let mut s = Session::empty();
let t = Instant::now();
open(&mut s, path)?;
let open_ms = ms(t);
let st = s.state().map_err(|e| e.to_string())?;
let (d, space) = (&st.doc, &st.space);
let ext = d.extents(space);
let size = ext.width().max(ext.height());
if ext.is_empty() || !(size.is_finite() && size > 0.0) {
return Err("perf: the drawing is empty".into());
}
outln!("open {open_ms:.0} ms, {} entities, extents {:.1} x {:.1}", d.entity_count(), ext.width(), ext.height());
outln!("{:>8} {:>10} {:>10}", "zoom", "build ms", "prims");
let mut finest = Options::default();
for k in 0..5 {
let zoom = 4f64.powi(k);
let h = size / zoom;
let pixel = 2f64.powi((h / 1000.0).max(1e-300).log2().floor() as i32);
let half = Vec2::new(h * 0.8, h * 0.5);
let visible = Bounds2::new(ext.center() - half, ext.center() + half);
let screen = Options { tolerance: pixel * 0.5, min_dash: pixel * 2.0, view: Some(visible.expand(h * 0.8)), ..Default::default() };
let t = Instant::now();
let n = build(d, space, &screen).prims.len();
outln!("{:>7}x {:>10.1} {n:>10}", zoom, ms(t));
finest = screen;
}
// Plots: every pattern line, everywhere (last, so its large list doesn't weigh on the above).
let t = Instant::now();
let n = build(d, space, &Options { min_dash: 0.0, view: None, ..finest }).prims.len();
outln!("{:>8} {:>10.1} {n:>10}", "full", ms(t));
Ok(())
}
fn perf(args: &[String]) -> Result<(), String> {
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_engine::{select, snap};
use std::time::Instant;
if let Some(path) = args.first().filter(|a| a.parse::<usize>().is_err()) {
return perf_file(path);
}
let n: usize = match args.first() {
Some(a) => a.parse().map_err(|_| format!("perf: bad entity count {a}"))?,
None => 200_000,
@@ -427,10 +554,10 @@ fn perf(args: &[String]) -> Result<(), String> {
let back = cadcraft_io::read(&bytes, "perf.dxf").map_err(|e| e.to_string())?;
rows.push(("DXF read".into(), ms(t), format!("{} entities", back.entity_count())));
println!("{:<40} {:>12} notes", "operation", "ms");
println!("{}", "-".repeat(80));
outln!("{:<40} {:>12} notes", "operation", "ms");
outln!("{}", "-".repeat(80));
for (name, t, note) in rows {
println!("{name:<40} {t:>12.2} {note}");
outln!("{name:<40} {t:>12.2} {note}");
}
Ok(())
}
@@ -440,37 +567,47 @@ fn perf(args: &[String]) -> Result<(), String> {
enum McpTarget {
/// An in-process drawing session (no `--connect`).
Headless,
/// The running app's control channel at `HOST:PORT`.
Connect(String),
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
/// `launch`: opened then if it isn't running.
Connect { addr: String, lazy: bool, launch: bool },
}
/// Parses the arguments after `mcp`. `--connect` must be followed by a `HOST:PORT`; a missing,
/// empty or flag-like value is an error, never a silent fall back to a headless session (#103).
fn parse_mcp_args(args: &[String]) -> Result<McpTarget, String> {
let mut target = McpTarget::Headless;
let mut addr: Option<String> = None;
let (mut lazy, mut launch) = (false, false);
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--connect" => {
let addr = it
let a = it
.next()
.map(|v| v.trim())
.filter(|v| !v.is_empty() && !v.starts_with('-'))
.ok_or("--connect needs HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)")?;
if target != McpTarget::Headless {
if addr.is_some() {
return Err("--connect given more than once".into());
}
target = McpTarget::Connect(addr.to_string());
addr = Some(a.to_string());
}
"--lazy" => lazy = true,
"--launch" => launch = true,
other => return Err(format!("mcp: unknown argument {other}\n{USAGE}")),
}
}
Ok(target)
match addr {
// `--launch` connects at the first call too (the app opens then).
Some(addr) => Ok(McpTarget::Connect { addr, lazy: lazy || launch, launch }),
None if lazy || launch => Err("--lazy and --launch need --connect HOST:PORT".into()),
None => Ok(McpTarget::Headless),
}
}
fn mcp(args: &[String]) -> Result<(), String> {
let backend: Box<dyn cadcraft_mcp::Backend> = match parse_mcp_args(args)? {
McpTarget::Connect(addr) => match cadcraft_mcp::Remote::connect(&addr) {
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) {
Ok(r) => Box::new(r),
Err(e) => return Err(format!("cadcraft-cli: cannot connect to {addr}: {e}")),
},
@@ -496,8 +633,14 @@ mod mcp_args_tests {
#[test]
fn mcp_connect_with_address_selects_remote() {
assert_eq!(parse_mcp_args(&args(&["--connect", "127.0.0.1:7979"])), Ok(McpTarget::Connect("127.0.0.1:7979".into())));
assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979"])), Ok(McpTarget::Connect("localhost:7979".into())));
let to = |addr: &str, lazy, launch| Ok(McpTarget::Connect { addr: addr.into(), lazy, launch });
assert_eq!(parse_mcp_args(&args(&["--connect", "127.0.0.1:7979"])), to("127.0.0.1:7979", false, false));
assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979"])), to("localhost:7979", false, false));
assert_eq!(parse_mcp_args(&args(&["--lazy", "--connect", "localhost:7979"])), to("localhost:7979", true, false));
assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979", "--launch"])), to("localhost:7979", true, true));
// Without an app to reach they mean nothing: never a headless session.
assert!(parse_mcp_args(&args(&["--lazy"])).is_err());
assert!(parse_mcp_args(&args(&["--launch"])).is_err());
}
#[test]
@@ -518,6 +661,11 @@ mod mcp_args_tests {
}
fn main() -> ExitCode {
let code = cli();
if STDOUT_ERROR.load(Ordering::Relaxed) { ExitCode::FAILURE } else { code }
}
fn cli() -> ExitCode {
install_io();
let args: Vec<String> = std::env::args().skip(1).collect();
let rest: Vec<String> = args.iter().skip(1).cloned().collect();
@@ -535,11 +683,15 @@ fn main() -> ExitCode {
.filter(|c| f.as_ref().is_none_or(|f| c.id.contains(f.as_str()) || c.label.to_ascii_lowercase().contains(f.as_str())))
.map(|c| serde_json::to_value(c.info(&s)).unwrap_or_default())
.collect();
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
}),
Some("mcp") => mcp(&rest),
Some("--version" | "-V") => {
println!("cadcraft-cli {}", env!("CARGO_PKG_VERSION"));
outln!("cadcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("--help" | "-h" | "help") => {
outln!("{USAGE}");
Ok(())
}
_ => Err(USAGE.into()),
+53
View File
@@ -0,0 +1,53 @@
//! `cadcraft-cli` against a stdout nobody reads any more (#537).
use std::io::Read;
use std::process::{Command, Output, Stdio};
/// `cadcraft-cli commands | head` panicked with "failed printing to stdout: Broken pipe (os error
/// 32)" and exit status 101: `commands` prints a few thousand lines, which no pipe buffer holds,
/// so the reader is gone before the last write.
#[test]
fn closed_stdout_ends_quietly() {
for args in [&["commands"][..], &["commands", "ellipse"], &["--version"]] {
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut first = [0u8; 10];
child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap();
drop(child.stdout.take());
let out = child.wait_with_output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success() && err.is_empty(), "{args:?}: {:?}: {err}", out.status);
}
}
/// The CLI keeps working once stdout is gone: `run` still executes its commands and still saves,
/// so `cadcraft-cli run … --save out.dxf | head` keeps the drawing.
fn run_with_closed_stdout(args: &[&str]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
drop(child.stdout.take());
child.wait_with_output().unwrap()
}
#[test]
fn closed_stdout_still_runs_the_commands_and_saves() {
let dir = std::env::temp_dir().join(format!("cc-cli-pipe-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let drawing = dir.join("piped.dxf");
let out = run_with_closed_stdout(&[
"run",
"--metric",
"--cmd",
"ellipse {\"center\":[0,0],\"major\":[10,0],\"ratio\":0.5}",
"--cmd",
"drawing.inspect {}",
"--save",
drawing.to_str().unwrap(),
]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
let saved = std::fs::read_to_string(&drawing).unwrap();
assert!(saved.contains("ELLIPSE"), "the drawing is saved all the same: {}", &saved[..saved.len().min(200)]);
// A failing command is still a failure, whether or not anyone reads stdout.
let out = run_with_closed_stdout(&["run", "--metric", "--cmd", "no.such.command {}"]);
assert_eq!(out.status.code(), Some(1));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,83 @@
//! Drawing snap/grid spacing survives saving and opening in a fresh CLI process (#607).
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use serde_json::{Value, json};
static NEXT_FILE: AtomicU64 = AtomicU64::new(0);
struct DxfFile(PathBuf);
impl DxfFile {
fn new() -> Self {
let path =
std::env::temp_dir().join(format!("cadcraft-drafting-spacing-{}-{}.dxf", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed)));
std::fs::File::options().write(true).create_new(true).open(&path).expect("reserve test DXF");
Self(path)
}
}
impl Drop for DxfFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn cli(args: &[&str]) -> Vec<Value> {
let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().expect("run cadcraft-cli");
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).lines().map(|line| serde_json::from_str(line).expect("CLI JSON reply")).collect()
}
#[test]
fn quarter_unit_spacing_survives_save_and_reopen() {
let file = DxfFile::new();
let path = file.0.to_str().expect("test file path");
cli(&[
"run",
"--sample",
"--cmd",
r#"setvar {"name":"SNAPUNIT","value":[0.25,0.25]}"#,
"--cmd",
r#"setvar {"name":"GRIDUNIT","value":[0.25,0.25]}"#,
"--save",
path,
]);
let replies = cli(&["run", path, "--cmd", r#"getvar {"name":"SNAPUNIT"}"#, "--cmd", r#"getvar {"name":"GRIDUNIT"}"#]);
for name in ["SNAPUNIT", "GRIDUNIT"] {
let reply = replies.iter().find(|r| r["name"] == name).expect("getvar reply");
assert_eq!(reply["value"], json!([0.25, 0.25]), "{name} reset on reopen");
}
}
#[test]
fn drafting_settings_spacing_roundtrips_without_persisting_osmode() {
let file = DxfFile::new();
let path = file.0.to_str().expect("test file path");
cli(&[
"run",
"--sample",
"--cmd",
r#"dsettings {"snapunit":[0.25,0.125],"gridunit":[0.75,1.5]}"#,
"--cmd",
r#"setvar {"name":"OSMODE","value":0}"#,
"--save",
path,
]);
let replies = cli(&[
"run",
path,
"--cmd",
r#"getvar {"name":"SNAPUNIT"}"#,
"--cmd",
r#"getvar {"name":"GRIDUNIT"}"#,
"--cmd",
r#"getvar {"name":"OSMODE"}"#,
]);
for (name, expected) in [("SNAPUNIT", json!([0.25, 0.125])), ("GRIDUNIT", json!([0.75, 1.5])), ("OSMODE", json!(4133))] {
let reply = replies.iter().find(|r| r["name"] == name).expect("getvar reply");
assert_eq!(reply["value"], expected, "{name} after reopening");
}
}
+23
View File
@@ -0,0 +1,23 @@
//! `--help` is a request, not a failure (#1525): it goes to stdout with exit 0, like `--version`.
//! Bare `cadcraft-cli` keeps reporting on stderr with exit 1.
use std::process::Command;
#[test]
fn help_flags_print_usage_to_stdout_and_exit_zero() {
for args in [&["--help"][..], &["-h"], &["help"]] {
let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().expect("run cadcraft-cli");
assert!(out.status.success(), "{args:?}: {:?}", out.status);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.starts_with("usage:"), "{args:?}: {stdout:?}");
assert!(String::from_utf8_lossy(&out.stderr).is_empty(), "{args:?}: stderr should be empty");
}
}
#[test]
fn bare_invocation_still_reports_on_stderr() {
let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).output().expect("run cadcraft-cli");
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "bare invocation keeps its usage on stderr");
assert!(String::from_utf8_lossy(&out.stderr).starts_with("usage:"));
}
+6
View File
@@ -0,0 +1,6 @@
mod cli;
mod drafting_spacing;
mod help;
mod mcp_connect;
mod skipped_records;
mod undrawn_entities;
@@ -0,0 +1,44 @@
//! `info` reports the records a DXF file lost on reading, by section, and `convert` warns about
//! them before writing the copy (#865). The exit code stays 0.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A LINE after the last ENDSEC and a VERTEX with no POLYLINE before it.
const DAMAGED: &str = "0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n0\nVERTEX\n8\n0\n10\n1\n20\n1\n0\nENDSEC\n0\nLINE\n8\n0\n10\n9\n20\n9\n11\n8\n21\n8\n0\nEOF\n";
#[test]
fn info_counts_and_convert_warns_about_skipped_records() {
let dir = std::env::temp_dir().join(format!("cc-cli-skipped-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let damaged = dir.join("damaged.dxf");
std::fs::write(&damaged, DAMAGED).unwrap();
let damaged = damaged.to_str().unwrap();
let out = cli(&["info", damaged]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(v["skipped"], serde_json::json!({ "count": 2, "sections": { "(no section)": 1, "ENTITIES": 1 } }));
let copy = dir.join("copy.dxf");
let out = cli(&["convert", damaged, copy.to_str().unwrap()]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
let err = String::from_utf8_lossy(&out.stderr);
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("could not be read")).collect();
assert_eq!(warnings.len(), 1, "{err}");
assert!(warnings[0].contains("2 records") && warnings[0].contains("ENTITIES: 1") && warnings[0].contains("(no section): 1"), "{err}");
// An intact file: a zero count, and no warning.
let sample = dir.join("sample.dxf");
assert!(cli(&["sample", "floorplan", sample.to_str().unwrap()]).status.success());
let out = cli(&["info", sample.to_str().unwrap()]);
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(v["skipped"], serde_json::json!({ "count": 0, "sections": {} }));
let out = cli(&["convert", sample.to_str().unwrap(), copy.to_str().unwrap()]);
assert!(out.status.success());
assert!(!String::from_utf8_lossy(&out.stderr).contains("could not be read"), "{}", String::from_utf8_lossy(&out.stderr));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,53 @@
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
//! leaving them out silently (#1208). The exit code stays 0.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// 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\
0\nREGION\n8\n0\n70\n1\n1\nabc\n\
0\nREGION\n8\n0\n70\n1\n1\ndef\n\
0\nPDFUNDERLAY\n8\n0\n10\n0\n20\n0\n41\n1\n42\n1\n43\n1\n\
0\nENDSEC\n0\nEOF\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 input = dir.join("proxies.dxf");
std::fs::write(&input, PROXIES).unwrap();
let input = input.to_str().unwrap();
let out = cli(&["info", input]);
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(v["counts"]["Proxy"], 3, "{v}");
for ext in ["svg", "png", "pdf"] {
let image = dir.join(format!("out.{ext}"));
let out = cli(&["convert", input, image.to_str().unwrap()]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
let err = String::from_utf8_lossy(&out.stderr);
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
assert_eq!(warnings.len(), 1, "{ext}: {err}");
assert_eq!(warnings[0], format!("{input}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)"), "{ext}");
}
// A DXF copy keeps them, so there is nothing to warn about.
let copy = dir.join("copy.dxf");
let out = cli(&["convert", input, copy.to_str().unwrap()]);
assert!(out.status.success());
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
// A drawing without them: no warning.
let sample = dir.join("sample.dxf");
assert!(cli(&["sample", "floorplan", sample.to_str().unwrap()]).status.success());
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);
}
+1 -1
View File
@@ -29,4 +29,4 @@ web-sys = { version = "0.3", features = ["HtmlInputElement", "FileList", "File"]
eframe = { workspace = true, features = ["persistence", "default_fonts", "wgpu", "accesskit"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList"] }
+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CADCraft</title>
<link data-trunk rel="rust" data-bin="cadcraft-web" data-wasm-opt="z" data-weak-refs />
<style>
+150
View File
@@ -0,0 +1,150 @@
//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed
//! CADCraft in an `<iframe>` (such as a Nextcloud app). Messages are plain objects with a `type`:
//!
//! - `cadcraft:ready` (to the parent): `{ version }`, the app is listening; send a drawing now.
//! - `cadcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
//! `Uint8Array`. It opens like a file picked with File › Open or dropped on the window.
//! - `cadcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
//! file CADCraft would otherwise download (SAVE, SAVEAS, exports): it replaces the engine's
//! delivery hook. The parent stores the file and reports failures itself.
//! - `cadcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
//! - `cadcraft:failed` (to the parent): `{ error }` when the app couldn't start.
//!
//! Only the parent window on the page's own origin is heard or answered. In host mode the app
//! starts on the Start tab rather than an empty Drawing1, and the parent guards leaving the page.
use std::cell::{Cell, RefCell};
use cadcraft_ui_egui::CadApp;
use wasm_bindgen::JsCast as _;
use wasm_bindgen::JsValue;
use wasm_bindgen::closure::Closure;
use web_sys::js_sys;
/// Longest file name taken from the parent page.
const MAX_NAME_CHARS: usize = 255;
thread_local! {
/// The bridge [`deliver`] posts through (the engine's hook is a plain `fn`).
static BRIDGE: RefCell<Option<Bridge>> = const { RefCell::new(None) };
}
#[derive(Clone)]
pub struct Bridge {
window: web_sys::Window,
parent: web_sys::Window,
origin: String,
}
/// The unsaved-changes state last reported to the parent.
#[derive(Default)]
pub struct DirtyReport(Cell<Option<bool>>);
impl Bridge {
/// `None` when the page isn't framed (there is no parent to talk to).
pub fn new() -> Option<Self> {
let window = web_sys::window()?;
let parent = window.parent().ok().flatten()?;
if js_sys::Object::is(&parent, &window) {
return None;
}
let origin = window.location().origin().ok()?;
Some(Self { window, parent, origin })
}
/// Make this the bridge [`deliver`] uses.
pub fn install(&self) {
BRIDGE.with(|b| *b.borrow_mut() = Some(self.clone()));
}
pub fn post_ready(&self) {
self.send(&[("type", "cadcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]);
}
pub fn post_failed(&self, error: &str) {
self.send(&[("type", "cadcraft:failed".into()), ("error", error.into())]);
}
/// Hear drawings from the parent; they arrive through the upload inbox.
pub fn listen(&self, inbox: crate::upload::Inbox) {
let parent = self.parent.clone();
let origin = self.origin.clone();
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
return;
}
let data = event.data();
if string(&data, "type").as_deref() != Some("cadcraft:open") {
return;
}
let name = string(&data, "name")
.filter(|n| !n.trim().is_empty())
.map(|n| n.chars().take(MAX_NAME_CHARS).collect())
.unwrap_or_else(|| "Drawing.dxf".to_string());
// Refuse an oversized drawing before copying it into the app's memory.
let Some(array) = byte_array(&data) else { return };
if let Some(e) = CadApp::open_size_error(&name, u64::from(array.length())) {
inbox.refuse(e);
return;
}
inbox.receive(name, array.to_vec());
});
if self.window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() {
// The listener lives as long as the page.
on_message.forget();
}
}
/// After each frame: tell the parent when unsaved changes appear or go away.
pub fn report_dirty(&self, app: &CadApp, reported: &DirtyReport) {
let dirty = app.session.docs.iter().any(|d| d.is_dirty());
if reported.0.get() != Some(dirty) && self.send(&[("type", "cadcraft:dirty".into()), ("dirty", dirty.into())]) {
reported.0.set(Some(dirty));
}
}
fn post_save(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
let buffer = js_sys::Uint8Array::from(bytes).buffer();
let message = message(&[("type", "cadcraft:save".into()), ("name", name.into()), ("bytes", buffer.clone().into())])
.ok_or_else(|| "couldn't build the message".to_string())?;
self.parent
.post_message_with_transfer(&message, &self.origin, &js_sys::Array::of1(&buffer))
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
}
/// Post a message to the parent; false if it couldn't be sent.
fn send(&self, fields: &[(&str, JsValue)]) -> bool {
message(fields).is_some_and(|m| self.parent.post_message(&m, &self.origin).is_ok())
}
}
/// The engine's delivery hook in host mode ([`cadcraft_engine::cmd::file::set_deliver`]): hand
/// the file to the parent page. `Ok` once it was posted; the engine then counts a drawing as saved.
pub fn deliver(name: &str, _mime: &str, bytes: &[u8]) -> Result<(), String> {
let bridge = BRIDGE.with(|b| b.borrow().clone()).ok_or("the page that embeds CADCraft is gone")?;
bridge.post_save(name, bytes)
}
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
let m = js_sys::Object::new();
for (key, value) in fields {
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
}
Some(m)
}
fn string(data: &JsValue, key: &str) -> Option<String> {
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
}
/// `bytes` (an `ArrayBuffer` or `Uint8Array`) as a view, not yet copied.
fn byte_array(data: &JsValue) -> Option<js_sys::Uint8Array> {
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
Some(array.clone())
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
Some(js_sys::Uint8Array::new(&bytes))
} else {
None
}
}
+90 -12
View File
@@ -2,12 +2,17 @@
//!
//! Runs the same [`cadcraft_ui_egui::CadApp`] as the desktop app through eframe's web runner
//! (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release` from this
//! directory (output in `dist/web`). URL flags: `?webgl` forces WebGL2, `?sample` opens the sample
//! drawing. Saving downloads the drawing through the browser (`download.rs`).
//! directory (output in `dist/web`). URL flags: `?webgl` forces WebGL2, `?cpu` draws the drawing
//! with egui shapes instead of the GPU canvas, `?sample` opens the sample drawing. Saving downloads
//! the drawing through the browser (`download.rs`). With `?host=parent` (inside an `<iframe>`), a
//! same-origin parent page sends the drawing to open and stores what CADCraft saves instead
//! (`host.rs`).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
pub mod download;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(target_arch = "wasm32")]
mod web {
@@ -18,14 +23,20 @@ mod web {
const CANVAS_ID: &str = "cadcraft_canvas";
const LOADING_ID: &str = "cadcraft_loading";
/// The app, and the files File > Open… and drag and drop read for it in the background.
struct Shell(CadApp, crate::upload::Inbox);
/// The app, the files File > Open… and drag and drop read for it in the background, the
/// page embedding it (`?host=parent`), and the browser's `prefers-reduced-motion` (it stays
/// live, so View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting follows a change).
struct Shell(CadApp, crate::upload::Inbox, Option<(crate::host::Bridge, crate::host::DirtyReport)>, Option<web_sys::MediaQueryList>);
impl eframe::App for Shell {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.1.take_dropped(ctx);
self.1.drain(&mut self.0);
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
self.0.logic(ctx);
if let Some((bridge, reported)) = &self.2 {
bridge.report_dirty(&self.0, reported);
}
}
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(raw);
@@ -33,6 +44,7 @@ mod web {
}
/// Preferences (interface theme and language) survive reloads; egui state is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
storage.set_string(cadcraft_ui_egui::options::PROFILE_KEY, self.0.profile_json());
storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.0.prefs_json());
}
fn persist_egui_memory(&self) -> bool {
@@ -40,6 +52,9 @@ mod web {
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
if let Some((bridge, reported)) = &self.2 {
bridge.report_dirty(&self.0, reported);
}
}
}
@@ -47,6 +62,10 @@ mod web {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
fn query_param(key: &str) -> Option<String> {
web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key)
}
/// No file picker on the web: Save / Save As from the menu (and the close prompt) download the
/// drawing under its current name; `saveas {"path": "name.dxf"}` picks another name.
fn services() -> Services {
@@ -58,11 +77,29 @@ mod web {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plot(d, space, opts).map_err(|e| e.to_string())),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// No file system here: saved files reach the user as browser downloads.
cadcraft_engine::cmd::file::set_deliver(crate::download::download);
wasm_bindgen_futures::spawn_local(async {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// `?host=parent`: a same-origin page framing CADCraft (such as a Nextcloud app) opens
// drawings in it and stores what it saves. Otherwise there is no file system here: saved
// files reach the user as browser downloads.
let bridge = if query_param("host").as_deref() == Some("parent") { crate::host::Bridge::new() } else { None };
match &bridge {
Some(bridge) => {
bridge.install();
cadcraft_engine::cmd::file::set_deliver(crate::host::deliver);
}
None => cadcraft_engine::cmd::file::set_deliver(crate::download::download),
}
let app_bridge = bridge.clone();
wasm_bindgen_futures::spawn_local(async move {
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
@@ -79,14 +116,24 @@ mod web {
canvas,
options,
Box::new(move |cc| {
let mut app = CadApp::new(Session::new(), services());
// Embedded, the parent 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());
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)) {
app.load_profile(&profile);
}
if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::PREFS_KEY)) {
app.load_prefs(&prefs);
}
if let Some(rs) = &cc.wgpu_render_state {
app.set_wgpu(rs);
// `?cpu`: no render state for the app, so the canvas draws with egui shapes.
if !crate::wants_cpu(&query())
&& let Some(rs) = &cc.wgpu_render_state
{
// eframe's web runner has no stencil buffer: clipped layout
// viewports stay in the layout's display list.
app.set_wgpu(rs, None);
}
if query().contains("sample") {
let _ = app.run("ui.sample", serde_json::json!({}));
@@ -99,10 +146,19 @@ mod web {
picker.pick();
None
}));
Ok(Box::new(Shell(app, inbox)))
let host = app_bridge.map(|bridge| {
bridge.listen(inbox.clone());
bridge.post_ready();
(bridge, crate::host::DirtyReport::default())
});
let reduced_motion = web_sys::window().and_then(|w| w.match_media("(prefers-reduced-motion: reduce)").ok().flatten());
Ok(Box::new(Shell(app, inbox, host, reduced_motion)))
}),
)
.await;
if let (Err(e), Some(bridge)) = (&result, &bridge) {
bridge.post_failed(&format!("{e:?}"));
}
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
@@ -115,6 +171,12 @@ mod web {
}
}
/// True when the URL query (`?cpu&sample`) has a `cpu` flag: the CPU canvas path is requested.
#[cfg(any(target_arch = "wasm32", test))]
fn wants_cpu(query: &str) -> bool {
query.trim_start_matches('?').split('&').any(|p| p == "cpu" || p.starts_with("cpu="))
}
#[cfg(target_arch = "wasm32")]
mod upload;
@@ -127,3 +189,19 @@ fn main() {
fn main() {
eprintln!("cadcraft-web only runs in the browser: build it with `trunk build --release` in apps/cadcraft-web");
}
#[cfg(test)]
mod tests {
use super::wants_cpu;
#[test]
fn cpu_flag_is_detected() {
assert!(wants_cpu("?cpu"));
assert!(wants_cpu("?cpu&sample"));
assert!(wants_cpu("?sample&cpu"));
assert!(!wants_cpu(""));
assert!(!wants_cpu("?sample"));
assert!(!wants_cpu("?webgl&sample"));
assert!(!wants_cpu("?gpucpu"));
}
}
+14
View File
@@ -96,6 +96,20 @@ impl Inbox {
});
}
/// A file read elsewhere (sent by the page embedding CADCraft): opened on the next frame like
/// a picked file, or refused when too large to open.
pub fn receive(&self, name: String, bytes: Vec<u8>) {
match CadApp::open_size_error(&name, bytes.len() as u64) {
Some(e) => self.push(Err(e)),
None => self.push(Ok((name, bytes))),
}
}
/// A file from elsewhere refused before it was read (`error` says why).
pub fn refuse(&self, error: String) {
self.push(Err(error));
}
fn push(&self, upload: Upload) {
let mut files = self.files.take();
files.push(upload);
+20
View File
@@ -14,16 +14,23 @@ workspace = true
cadcraft-engine = { workspace = true }
cadcraft-ui-egui = { workspace = true }
cadcraft-io = { workspace = true }
# For the shared per-session control-token helper (control_server.rs authentication).
cadcraft-mcp = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links", "persistence"] }
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
chrono = { workspace = true }
[build-dependencies]
winresource = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
# is built twice.
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rfd = { workspace = true }
@@ -31,3 +38,16 @@ sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
# Rust HID backends: no proprietary SDK or C HID library.
[target.'cfg(target_os = "windows")'.dependencies]
hidapi = { version = "2.6.7", default-features = false, features = ["windows-native"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: Windows' Animation effects
# setting (system_animations.rs). Already in Cargo.lock through wgpu's DirectX 12 backend.
windows = { version = "0.62", features = ["UI_ViewManagement"] }
[target.'cfg(target_os = "linux")'.dependencies]
hidapi = { version = "2.6.7", default-features = false, features = ["linux-native-basic-udev"] }
+460 -50
View File
@@ -1,64 +1,474 @@
//! Loopback JSON-lines control server: one request per line, one reply per line.
//! This is the transport the MCP server (`cadcraft-cli mcp --connect`) wraps.
//!
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
use std::time::Duration;
use cadcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
return rx;
}
};
log::info!("control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let tx = tx.clone();
let ctx = ctx.clone();
std::thread::spawn(move || serve(stream, tx, ctx));
}
});
rx
/// Resource bounds for the control server.
#[derive(Clone, Copy, Debug)]
struct Limits {
/// Connections served at once; more get an error line and are closed.
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Requests waiting for the app at once; more are answered `busy`.
queue: usize,
/// How long a connection may go without sending a byte before it is closed.
idle_timeout: Duration,
/// How long a reply write may block before the connection is closed.
write_timeout: Duration,
/// How long a request waits for the app's answer.
reply_timeout: Duration,
}
fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
for line in BufReader::new(read).lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let (req, pending) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
// On timeout the request is cancelled if the app hasn't started it, and the reply's
// `state` says whether it can still have run.
let mut r = pending.wait(Duration::from_secs(60));
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
r
}
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
};
if writeln!(out, "{reply}").is_err() {
break;
impl Default for Limits {
fn default() -> Self {
Self {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
queue: 64,
idle_timeout: Duration::from_secs(600),
write_timeout: Duration::from_secs(30),
reply_timeout: Duration::from_secs(60),
}
}
}
/// Start the loopback server with a fresh session token and a bounded request queue.
/// Binding or token-issuance failure returns a disconnected receiver.
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => {
// Loopback TCP cannot tell local users apart, so issue an unguessable per-session
// token in an owner-only file and require it on every request (CWE-306). A client
// (the MCP bridge) reads it from the file, which needs the desktop user's filesystem
// access; another local account cannot.
let token = match cadcraft_mcp::control_token::issue(port) {
Ok(t) => Arc::new(t),
Err(e) => {
log::error!("control server not started: could not write the control token: {e}");
return sync_channel::<ControlRequest>(0).1;
}
};
if let Ok(path) = cadcraft_mcp::control_token::token_path(port) {
log::info!("control server listening on 127.0.0.1:{port} (token in {})", path.display());
}
serve_listener(l, Limits::default(), ctx, token)
}
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
sync_channel::<ControlRequest>(0).1
}
}
}
/// How long the accepting thread waits after a failed accept. Accepting can keep failing, for
/// example while the process has no file descriptors left, and retrying at once would keep a
/// core busy until it recovers.
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
/// The connections `incoming` accepts, calling `wait` after each failed accept.
fn accepted<T>(incoming: impl Iterator<Item = std::io::Result<T>>, mut wait: impl FnMut()) -> impl Iterator<Item = T> {
incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok())
}
/// Accept connections on `listener` under `limits`; requests arrive on the returned receiver.
fn serve_listener(listener: TcpListener, limits: Limits, ctx: egui::Context, token: Arc<String>) -> Receiver<ControlRequest> {
let (tx, rx) = sync_channel::<ControlRequest>(limits.queue.max(1));
std::thread::spawn(move || accept_loop(listener, tx, ctx, limits, token));
rx
}
/// A connection's place among [`Limits::max_clients`], given back when the connection ends (also
/// when its thread can't be started, or panics).
struct Slot(Arc<AtomicUsize>);
impl Drop for Slot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
/// Accept clients within the connection limit and give each worker the same session token.
fn accept_loop(listener: TcpListener, tx: SyncSender<ControlRequest>, ctx: egui::Context, limits: Limits, token: Arc<String>) {
let open = Arc::new(AtomicUsize::new(0));
for mut stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
let _ = stream.set_write_timeout(Some(limits.write_timeout));
if open.fetch_add(1, Ordering::SeqCst) >= limits.max_clients {
open.fetch_sub(1, Ordering::SeqCst);
let _ = writeln!(stream, "{}", json!({"ok": false, "error": "too many control connections"}));
continue;
}
let slot = Slot(Arc::clone(&open));
let tx = tx.clone();
let ctx = ctx.clone();
let token = Arc::clone(&token);
let _ = std::thread::Builder::new().spawn(move || {
let _slot = slot;
serve(stream, &tx, &ctx, limits, &token);
});
}
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() {
// The idle timeout ran out (Windows reports it as TimedOut, Unix as WouldBlock).
ErrorKind::TimedOut | ErrorKind::WouldBlock => "request line not completed in time; closing the connection".to_string(),
_ => e.to_string(),
})?;
if n == 0 {
return Ok(false);
}
if buf.last() == Some(&b'\n') {
buf.pop();
if buf.last() == Some(&b'\r') {
buf.pop();
}
return Ok(true);
}
if buf.len() > max {
return Err(format!("request line longer than {max} bytes; closing the connection"));
}
// Last line without a newline, then end of stream.
Ok(true)
}
/// One request line, parsed.
enum Line {
Request {
id: Value,
method: String,
params: Value,
token: Option<String>,
},
Blank,
/// Not a request: reply with this error and close the connection.
Reject(String),
}
/// Parse a UTF-8 JSON request and its optional token, distinguishing blank lines from rejected input.
fn parse_line(bytes: &[u8]) -> Line {
let Ok(text) = std::str::from_utf8(bytes) else {
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
};
let text = text.trim();
if text.is_empty() {
return Line::Blank;
}
if is_http_request_line(text) {
return Line::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
}
let msg = match serde_json::from_str::<Value>(text) {
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 {
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 {
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
};
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),
}
}
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
fn is_http_request_line(text: &str) -> bool {
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
/// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI.
/// Invalid credentials close the connection; queue and reply limits report whether a request ran.
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits, token: &str) {
if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
return;
}
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line) {
Ok(false) => break,
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
// A line nobody asked for would be read as the reply to the client's next request.
Err(_) if buf.is_empty() => break,
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Request { id, method, params, token: given } => {
// Authenticate the peer before dispatching: loopback TCP does not identify the
// OS user, so only a client holding the owner-only session token may drive the
// desktop user's commands (CWE-306).
if !given.map(|g| cadcraft_mcp::control_token::matches(token, &g)).unwrap_or(false) {
let mut r = json!({"ok": false, "error": "unauthorized: missing or invalid control token", "state": "not-run"});
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
let _ = writeln!(out, "{r}");
break;
}
let (req, pending) = ControlRequest::new(method, params);
let mut r = match tx.try_send(req) {
Ok(()) => {
ctx.request_repaint();
// On timeout the request is cancelled if the app hasn't started it, and
// the reply's `state` says whether it can still have run.
pending.wait(limits.reply_timeout)
}
Err(TrySendError::Full(_)) => json!({"ok": false, "error": "busy: too many queued requests", "state": "not-run"}),
Err(TrySendError::Disconnected(_)) => break,
};
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
if writeln!(out, "{r}").is_err() {
break;
}
continue;
}
},
};
// The connection closes either way; a peer that can't read the reason loses nothing.
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject}));
break;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A failed accept is followed by a wait before the next one, so a listener that keeps
/// failing does not spin, and the connections around the failures still come through.
#[test]
fn a_failed_accept_waits_before_the_next() {
let failed = || Err(std::io::Error::other("no file descriptors left"));
let incoming = vec![failed(), Ok(1), failed(), failed(), Ok(2)];
let mut waits = 0;
let connections: Vec<i32> = super::accepted(incoming.into_iter(), || waits += 1).collect();
assert_eq!(connections, [1, 2]);
assert_eq!(waits, 3, "one wait per failed accept");
}
#[test]
fn lines_are_read_up_to_the_limit() {
let mut buf = Vec::new();
let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc";
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true));
assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted");
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true));
assert_eq!(buf, b"bb", "CRLF is stripped");
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true));
assert_eq!(buf, b"cc", "a last line without a newline is still read");
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(false), "then end of stream");
}
#[test]
fn an_overlong_line_is_refused_without_reading_the_rest() {
let mut buf = Vec::new();
let long = [b'x'; 100];
let mut input: &[u8] = &long;
assert!(read_bounded_line(&mut input, &mut buf, 10).is_err());
assert!(buf.len() <= 11, "at most limit + 1 bytes are buffered, got {}", buf.len());
assert_eq!(input.len(), 100 - 11, "the rest of the line is left unread");
}
fn short() -> Limits {
Limits {
queue: 1,
idle_timeout: Duration::from_millis(300),
write_timeout: Duration::from_millis(300),
reply_timeout: Duration::from_millis(300),
..Limits::default()
}
}
/// A fixed token for tests; real tokens are random (see `cadcraft_mcp::control_token`).
const TEST_TOKEN: &str = "test-control-token";
/// The control server on a loopback port under `limits`; requests arrive on the receiver.
fn serve_with(limits: Limits) -> (std::net::SocketAddr, Receiver<ControlRequest>) {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
(addr, serve_listener(listener, limits, egui::Context::default(), Arc::new(TEST_TOKEN.to_string())))
}
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
let (addr, rx) = serve_with(Limits::default());
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
}
});
addr
}
/// A request line carrying the test token, so it authenticates.
fn req_line(id: i64, method: &str) -> String {
json!({"id": id, "method": method, "token": TEST_TOKEN}).to_string() + "\n"
}
/// Send `input` on a new connection and read reply lines until the server closes it.
fn exchange(addr: std::net::SocketAddr, input: &[u8]) -> Vec<Value> {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(input).unwrap();
let mut replies = Vec::new();
for line in BufReader::new(c).lines() {
// A read timeout here means the server kept the connection open.
let line = line.unwrap();
replies.push(serde_json::from_str(&line).unwrap());
}
replies
}
/// A browser can POST to the port: its request line closes the connection before the JSON
/// line in its body is read, so nothing is dispatched.
#[test]
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
let (addr, rx) = serve_with(short());
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\n\r\n\
{\"id\":1,\"method\":\"cmdline.input\",\"params\":{\"text\":\"circle 0,0 5\"}}\n";
let replies = exchange(addr, http);
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
assert!(rx.try_recv().is_err(), "the body was dispatched");
}
#[test]
fn a_line_that_is_not_a_request_closes_the_connection() {
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
let addr = serve_echo();
let mut input = junk.to_vec();
input.extend_from_slice(b"{\"id\":2,\"method\":\"ping\"}\n");
let replies = exchange(addr, &input);
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
}
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
assert!(is_http_request_line("PRI * HTTP/2.0"));
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
}
#[test]
fn an_idle_connection_is_closed() {
let (addr, _rx) = serve_with(short());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let t = std::time::Instant::now();
let mut got = Vec::new();
c.read_to_end(&mut got).unwrap();
assert!(got.is_empty(), "{}", String::from_utf8_lossy(&got));
assert!(t.elapsed() < Duration::from_secs(4));
}
/// Authenticated requests rejected by a full queue retain their IDs and report that they did not run.
#[test]
fn a_full_queue_answers_busy() {
let (addr, rx) = serve_with(short());
// No UI drains the one-place queue: the first request fills it, the second finds it full.
let first = std::thread::spawn(move || exchange(addr, req_line(1, "m").as_bytes()));
let deadline = std::time::Instant::now() + Duration::from_secs(4);
let busy = loop {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(req_line(2, "m").as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
if v["error"].as_str().is_some_and(|e| e.starts_with("busy")) || std::time::Instant::now() > deadline {
break v;
}
};
assert_eq!((busy["id"].as_i64(), busy["state"].as_str()), (Some(2), Some("not-run")), "{busy}");
assert_eq!(first.join().unwrap()[0]["state"], "not-run");
drop(rx);
}
/// Replies on one authenticated connection preserve the ID of each request.
#[test]
fn requests_are_answered_with_their_ids() {
let addr = serve_echo();
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let input = format!("{}\n{}", req_line(3, "ping").trim_end(), req_line(4, "pong"));
c.write_all(input.as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(3, "ping"), (4, "pong")] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["method"].as_str()), (Some(id), Some(method)), "{line}");
}
}
/// Missing and incorrect session tokens are rejected before dispatch.
#[test]
fn a_request_without_the_token_is_unauthorized() {
// A local peer that does not hold the session token cannot drive the app (CWE-306).
let addr = serve_echo();
let replies = exchange(addr, b"{\"id\":9,\"method\":\"ping\"}\n");
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
assert!(replies[0]["error"].as_str().unwrap().contains("unauthorized"), "{replies:?}");
// A wrong token is also refused.
let wrong = exchange(addr, b"{\"id\":9,\"method\":\"ping\",\"token\":\"nope\"}\n");
assert_eq!(wrong[0]["ok"], false);
assert!(wrong[0]["error"].as_str().unwrap().contains("unauthorized"), "{wrong:?}");
}
/// A request carrying the session token reaches the control dispatcher.
#[test]
fn a_request_with_the_token_is_dispatched() {
let addr = serve_echo();
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(req_line(10, "ping").as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["ok"].as_bool(), v["method"].as_str()), (Some(true), Some("ping")), "{line}");
}
#[test]
fn extra_connections_are_refused() {
let addr = serve_echo();
// Idle connections are accepted in order and held open.
let held: Vec<TcpStream> = (0..Limits::default().max_clients).map(|_| TcpStream::connect(addr).unwrap()).collect();
let mut extra = TcpStream::connect(addr).unwrap();
extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut line = String::new();
BufReader::new(&mut extra).read_line(&mut line).unwrap();
assert!(line.contains("too many control connections"), "{line}");
drop(held);
}
}
+174
View File
@@ -0,0 +1,174 @@
//! The desktop's own light/dark choice, for View ▸ Theme ▸ System.
//!
//! winit reports no system theme on Linux and the BSDs (`RawInput::system_theme` stays `None`),
//! so the System choice fell back to dark whatever the desktop said. This asks the desktop itself:
//! the XDG Desktop Portal's Settings interface, which answers on GNOME, KDE and XFCE alike, over
//! X11 and Wayland alike. The answer is handed to egui as the system theme
//! (`App::raw_input_hook`), so the app and egui's own widgets follow it as they follow macOS and
//! Windows.
//!
//! Ported from PdfCraft (storytold/pdfcraft#881).
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use std::time::Duration;
/// How often the watcher re-reads the desktop's answer. The portal also publishes a change
/// signal, but subscribing needs a connection kept alive for the life of the window; one round
/// trip every few seconds is cheap and reacts soon enough after a theme switch.
const POLL: Duration = Duration::from_secs(4);
/// Watches the desktop and reports its choice when it changes.
#[derive(Default)]
pub struct DesktopTheme {
/// `None` when no watcher thread could be started (or on a platform where winit answers).
changes: Option<Receiver<Option<egui::Theme>>>,
/// The desktop's last answer.
current: Option<egui::Theme>,
}
impl DesktopTheme {
/// Start watching. The first answer is sent straight away; `wake` is called after each
/// answer, so an idle window repaints and picks it up.
pub fn start(wake: impl Fn() + Send + 'static) -> Self {
if !ASKS_THE_DESKTOP {
return Self::default();
}
let (tx, rx) = channel();
let started = std::thread::Builder::new().name("cadcraft-desktop-theme".into()).spawn(move || {
let mut last = read();
if tx.send(last).is_err() {
return;
}
wake();
loop {
std::thread::sleep(POLL);
let now = read();
if now != last {
last = now;
if tx.send(now).is_err() {
return;
}
wake();
}
}
});
Self { changes: started.ok().map(|_| rx), current: None }
}
/// The desktop's choice, `None` when it states none or there is nobody to ask (no session
/// bus, no portal). Polled once a frame; a desktop that stops answering keeps the last answer.
pub fn current(&mut self) -> Option<egui::Theme> {
if let Some(changes) = &self.changes {
loop {
match changes.try_recv() {
Ok(Some(theme)) => self.current = Some(theme),
Ok(None) => {}
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
}
}
}
self.current
}
}
/// Where winit has no answer and the portal does.
const ASKS_THE_DESKTOP: bool = cfg!(all(unix, not(target_os = "macos")));
/// Ask the portal once. D-Bus calls block, so this belongs off the UI thread: the watcher's
/// thread is its only caller.
#[cfg(all(unix, not(target_os = "macos")))]
fn read() -> Option<egui::Theme> {
const PORTAL: &str = "org.freedesktop.portal.Desktop";
const PATH: &str = "/org/freedesktop/portal/desktop";
const SETTINGS: &str = "org.freedesktop.portal.Settings";
// The standard key first (GNOME and KDE answer it: 0 no preference, 1 dark, 2 light); then
// GNOME's own schema, which XFCE's portal proxies without the standard key.
const KEYS: [(&str, &str); 2] = [("org.freedesktop.appearance", "color-scheme"), ("org.gnome.desktop.interface", "color-scheme")];
let connection = zbus::blocking::Connection::session().ok()?;
for (namespace, key) in KEYS {
// `ReadOne` (Settings version 2) answers the value; older portals only have `Read`, which
// wraps it in one more variant. `parse` unwraps either.
let reply = connection
.call_method(Some(PORTAL), PATH, Some(SETTINGS), "ReadOne", &(namespace, key))
.or_else(|_| connection.call_method(Some(PORTAL), PATH, Some(SETTINGS), "Read", &(namespace, key)));
let Ok(reply) = reply else { continue };
let Ok((answer,)) = reply.body().deserialize::<(zbus::zvariant::OwnedValue,)>() else { continue };
if let Some(scheme) = parse(&answer, 0) {
return scheme;
}
}
None
}
/// The portal's `color-scheme` answer: `Some(choice)` when it read as an answer (`Some(None)`
/// for "no preference"), `None` when it didn't. Variants are unwrapped a few levels deep.
#[cfg(all(unix, not(target_os = "macos")))]
fn parse(value: &zbus::zvariant::Value<'_>, depth: u8) -> Option<Option<egui::Theme>> {
use zbus::zvariant::Value;
match value {
Value::U32(1) => Some(Some(egui::Theme::Dark)),
Value::U32(2) => Some(Some(egui::Theme::Light)),
Value::U32(_) => Some(None),
Value::Str(s) => Some(match s.as_str() {
"prefer-dark" => Some(egui::Theme::Dark),
"prefer-light" => Some(egui::Theme::Light),
_ => None,
}),
Value::Value(inner) if depth < 4 => parse(inner, depth + 1),
_ => None,
}
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
fn read() -> Option<egui::Theme> {
None
}
#[cfg(test)]
mod tests {
use super::*;
/// The standard key answers a number, GNOME's schema a string; either may come wrapped in
/// variants (the older `Read`). Only "dark" and "light" are a choice.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn the_portal_answer_reads_as_a_choice_or_as_none() {
use zbus::zvariant::Value;
assert_eq!(parse(&Value::U32(1), 0), Some(Some(egui::Theme::Dark)));
assert_eq!(parse(&Value::U32(2), 0), Some(Some(egui::Theme::Light)));
assert_eq!(parse(&Value::U32(0), 0), Some(None));
assert_eq!(parse(&Value::U32(7), 0), Some(None));
assert_eq!(parse(&Value::from("prefer-dark"), 0), Some(Some(egui::Theme::Dark)));
assert_eq!(parse(&Value::from("prefer-light"), 0), Some(Some(egui::Theme::Light)));
assert_eq!(parse(&Value::from("default"), 0), Some(None));
let wrapped = Value::Value(Box::new(Value::Value(Box::new(Value::U32(1)))));
assert_eq!(parse(&wrapped, 0), Some(Some(egui::Theme::Dark)));
assert_eq!(parse(&Value::Bool(true), 0), None);
let mut deep = Value::U32(1);
for _ in 0..10 {
deep = Value::Value(Box::new(deep));
}
assert_eq!(parse(&deep, 0), None, "nesting is bounded");
}
/// A watcher that was never started is inert rather than a panic.
#[test]
fn a_watcher_without_a_thread_is_inert() {
assert_eq!(DesktopTheme::default().current(), None);
}
/// Answers arrive as changes; "no preference" or silence keeps the last real answer.
#[test]
fn the_last_answer_stands_until_a_new_one() {
let (tx, rx) = channel();
let mut watcher = DesktopTheme { changes: Some(rx), current: None };
assert_eq!(watcher.current(), None);
tx.send(Some(egui::Theme::Light)).unwrap();
assert_eq!(watcher.current(), Some(egui::Theme::Light));
tx.send(Some(egui::Theme::Dark)).unwrap();
tx.send(None).unwrap();
assert_eq!(watcher.current(), Some(egui::Theme::Dark));
drop(tx);
assert_eq!(watcher.current(), Some(egui::Theme::Dark));
}
}
+56 -5
View File
@@ -1,10 +1,14 @@
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
use eframe::{NativeOptions, egui_wgpu::WgpuSetup, wgpu::Backends};
use eframe::{
NativeOptions,
egui_wgpu::WgpuSetup,
wgpu::{Backends, Dx12Compiler},
};
/// Restrict the wgpu instance to DirectX 12 unless `backend_override` (normally
/// `Backends::from_env()`, i.e. `WGPU_BACKEND`) names other backends.
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>) {
/// Default to DirectX 12 with FXC before creating the wgpu instance. Explicit
/// `WGPU_BACKEND` and `WGPU_DX12_COMPILER` choices, read by the caller, take precedence.
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>, compiler_override: Option<Dx12Compiler>) {
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
// eframe's default includes GL. Creating that backend can crash inside AMD's
// atio6axx.dll before adapter selection or any Rust error handling runs, so the
@@ -12,6 +16,15 @@ pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>
// out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12
// workaround without mutating process environment variables.
create.instance_descriptor.backends = backend_override.unwrap_or(Backends::DX12);
// Auto can load another program's dxcompiler.dll without a matching dxil.dll.
// That fails wgpu's indirect-validation pipeline and loses the device before
// the first frame (issue #608). FXC uses the Windows-provided compiler runtime.
create.instance_descriptor.backend_options.dx12.shader_compiler = compiler_override.unwrap_or(Dx12Compiler::Fxc);
log::info!(
"Windows graphics: backends={:?}, DX12 compiler={:?}",
create.instance_descriptor.backends,
create.instance_descriptor.backend_options.dx12.shader_compiler
);
}
}
@@ -21,7 +34,7 @@ mod tests {
fn configured_backends(backend_override: Option<Backends>) -> Backends {
let mut options = NativeOptions::default();
configure(&mut options, backend_override);
configure(&mut options, backend_override, None);
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
@@ -38,6 +51,44 @@ mod tests {
assert_eq!(configured_backends(None), Backends::DX12);
}
#[test]
fn windows_default_uses_fxc_instead_of_searching_for_dxc() {
let mut options = NativeOptions::default();
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
// Auto can find an unrelated DXC without its matching DXIL runtime (issue #608).
create.instance_descriptor.backend_options.dx12.shader_compiler = Dx12Compiler::Auto;
}
configure(&mut options, None, None);
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc));
}
#[test]
fn explicit_compiler_and_backend_overrides_are_preserved() {
let backends = Backends::VULKAN | Backends::DX12;
for compiler in
[Dx12Compiler::Fxc, Dx12Compiler::Auto, Dx12Compiler::StaticDxc, Dx12Compiler::DynamicDxc { dxc_path: "custom/dxcompiler.dll".into() }]
{
let mut options = NativeOptions::default();
configure(&mut options, Some(backends), Some(compiler.clone()));
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
assert_eq!(create.instance_descriptor.backends, backends);
match (compiler, create.instance_descriptor.backend_options.dx12.shader_compiler) {
(Dx12Compiler::Fxc, Dx12Compiler::Fxc)
| (Dx12Compiler::Auto, Dx12Compiler::Auto)
| (Dx12Compiler::StaticDxc, Dx12Compiler::StaticDxc) => {}
(Dx12Compiler::DynamicDxc { dxc_path: expected }, Dx12Compiler::DynamicDxc { dxc_path: actual }) => {
assert_eq!(actual, expected);
}
(expected, actual) => panic!("compiler override changed from {expected:?} to {actual:?}"),
}
}
}
#[test]
fn explicit_backend_override_is_preserved() {
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
+36 -16
View File
@@ -93,7 +93,10 @@ fn matches(name: &str, target: &str) -> bool {
}
}
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch.
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch (the
/// `duration_since` clamp); past the last date chrono can represent (year 262143) the proleptic
/// Gregorian date is kept via the 400-year cycle rather than falling back to the epoch, so the
/// output never changes for a value the old formatter accepted and logging never panics.
pub fn timestamp(t: SystemTime) -> String {
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
let secs = since.as_secs();
@@ -102,20 +105,25 @@ pub fn timestamp(t: SystemTime) -> String {
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
}
/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's
/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch; saturating so an absurd
/// clock can't overflow).
fn civil_from_days(days: u64) -> (u64, u64, u64) {
let z = days.saturating_add(719_468);
let era = z / 146_097;
let doe = z % 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = era.saturating_mul(400).saturating_add(yoe).saturating_add(u64::from(m <= 2));
(y, m, d)
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day).
///
/// `timestamp` clamps a pre-1970 clock to the epoch, so `days` is an unsigned count that can run
/// past `NaiveDate`'s ±262143-year range. The Gregorian calendar repeats every 400 years
/// (146_097 days), so chrono converts the day within one cycle and whole cycles go back into the
/// year (an `i128`, then saturated into `i64`), keeping chrono as the only calendar logic and
/// reproducing the old saturating `civil_from_days` result exactly without hand-rolled day math.
/// 1970-01-01 is `num_days_from_ce` 719_163.
fn civil_from_days(days: u64) -> (i64, u32, u32) {
use chrono::Datelike;
let (cycles, rest) = (days / 146_097, days % 146_097);
// `rest + 719_163` is 719_163..865_259, always a valid CE day.
match i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt) {
Some(d) => {
let y = i128::from(d.year()) + i128::from(cycles) * 400;
(i64::try_from(y).unwrap_or(i64::MAX), d.month(), d.day())
}
None => (1970, 1, 1), // unreachable
}
}
fn numbered(dir: &Path, n: usize) -> PathBuf {
@@ -385,8 +393,20 @@ mod tests {
// 2000 is a leap year (divisible by 400), 2100 is not.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
// Before the epoch (a clock set wrong) clamps instead of panicking.
// Before the epoch (a clock set wrong) clamps to the epoch instead of panicking.
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
// Past chrono's range (a clock set absurdly far ahead) keeps the proleptic Gregorian date
// the old formatter gave, rather than falling back to the epoch.
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
}
// Windows' SystemTime can't hold u64::MAX / 2 seconds, so it is only checked where it exists.
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
}
// Years past 9999 keep the plain zero-padded year (no `+`).
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
}
#[test]
+175 -24
View File
@@ -15,43 +15,94 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod control_server;
mod desktop_theme;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod spacemouse;
mod system_animations;
mod workspace;
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services, i18n};
struct App(CadApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
struct App {
cad: CadApp,
spacemouse: spacemouse::SpaceMouse,
/// The desktop's light/dark choice where winit reports none (Linux, the BSDs).
desktop_theme: desktop_theme::DesktopTheme,
/// Whether the OS shows animations, for the System choice of View ▸ Accessibility ▸ Animation Effects.
system_animations: system_animations::SystemAnimations,
workspace: workspace::Workspace,
workspace_error: Option<String>,
#[cfg(target_os = "macos")]
native_menu: Option<native_menu::NativeMenu>,
}
impl App {
fn persist_workspace(&mut self, final_attempt: bool) {
let result = if final_attempt { self.workspace.save_on_exit(&self.cad.ui) } else { self.workspace.save_if_changed(&self.cad.ui) };
if let Err(error) = result {
if self.workspace_error.as_ref() != Some(&error) {
eprintln!("CADCraft workspace: {error}");
self.cad.set_status(format!("Workspace could not be saved: {error}"));
self.workspace_error = Some(error);
}
} else {
self.workspace_error = None;
}
}
}
/// View ▸ Theme ▸ System resolves against `raw.system_theme`, which winit leaves empty on Linux
/// and the BSDs: the desktop's answer, where it gives one, stands in for it.
fn follow_desktop(raw: &mut egui::RawInput, desktop: Option<egui::Theme>) {
if desktop.is_some() {
raw.system_theme = desktop;
}
}
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
{
if self.1.is_none() && std::env::var_os("CADCRAFT_NO_NATIVE_MENU").is_none() {
self.1 = Some(native_menu::NativeMenu::install(&mut self.0));
if self.native_menu.is_none() && std::env::var_os("CADCRAFT_NO_NATIVE_MENU").is_none() {
self.native_menu = Some(native_menu::NativeMenu::install(&mut self.cad));
}
if let Some(m) = &mut self.1 {
m.poll(&mut self.0, ctx);
if let Some(m) = &mut self.native_menu {
m.poll(&mut self.cad, ctx);
}
}
self.0.logic(ctx);
if std::mem::take(&mut self.0.quit_requested) {
self.cad.system_animations = self.system_animations.current();
self.cad.logic(ctx);
self.spacemouse.poll(&mut self.cad, ctx);
self.persist_workspace(false);
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(raw);
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
self.cad.ui(ui);
self.persist_workspace(false);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
fn on_exit(&mut self) {
self.persist_workspace(true);
self.cad.shutdown_autosave();
}
/// Preferences (the interface theme) survive restarts; window and egui state are not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.0.prefs_json());
storage.set_string(cadcraft_ui_egui::options::PROFILE_KEY, self.cad.profile_json());
storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.cad.prefs_json());
storage.set_string(cadcraft_ui_egui::autosave::PREFS_KEY, cadcraft_ui_egui::autosave::prefs_json());
}
fn persist_egui_memory(&self) -> bool {
false
@@ -63,7 +114,15 @@ pub fn install_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plot(d, space, opts).map_err(|e| e.to_string())),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
}
@@ -71,7 +130,8 @@ fn services() -> Services {
Services {
pick_open: Some(Box::new(|| {
rfd::FileDialog::new()
.add_filter(i18n::t("Drawings (DWG, DXF)"), &["dwg", "dxf"])
.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())
@@ -90,14 +150,15 @@ fn services() -> Services {
/// filter's extension, and macOS accepts only listed extensions, replacing any other with the
/// first one. DWG must be listed for a `.dwg` name to survive, and a drawing opened from DWG
/// then defaults to DWG; other names keep DXF first.
fn filters_for_save(name: &str) -> [(&'static str, &'static str); 5] {
let mut filters = [("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), ("SVG", "svg"), ("PNG", "png"), ("PDF", "pdf")];
fn filters_for_save(name: &str) -> [(&'static str, &'static str); 6] {
let mut filters =
[("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), ("Drawing Template (DWT)", "dwt"), ("SVG", "svg"), ("PNG", "png"), ("PDF", "pdf")];
let lower = name.to_ascii_lowercase();
filters.sort_by_key(|(_, ext)| !lower.ends_with(&format!(".{ext}")));
filters
}
/// The per-user settings directory (today it holds `logs/`): `CADCRAFT_CONFIG_DIR` if set, else
/// The per-user settings directory (it holds `logs/` and `autosave/`): `CADCRAFT_CONFIG_DIR` if set, else
/// `$XDG_CONFIG_HOME/cadcraft` or `~/.config/cadcraft` on Linux and the BSDs,
/// `~/Library/Application Support/CADCraft` on macOS, `%APPDATA%\CADCraft` on Windows.
fn config_dir() -> Option<std::path::PathBuf> {
@@ -123,6 +184,9 @@ fn config_dir_from(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<s
const APP_ID: &str = "ai.storyteller.cadcraft";
/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`).
const STENCIL_BITS: u8 = 8;
#[cfg(target_os = "macos")]
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png");
#[cfg(not(target_os = "macos"))]
@@ -148,6 +212,19 @@ fn control_port_from(source: &str, value: Option<String>) -> Option<u16> {
port
}
/// `--control` followed by `value`: a bare `--control` (last argument) keeps the port already
/// read from `CADCRAFT_CONTROL_PORT` (`current`) instead of turning the control channel off.
fn control_flag(current: Option<u16>, value: Option<String>) -> Option<u16> {
if value.is_some() {
return control_port_from("--control", value);
}
match current {
Some(port) => log::warn!("--control: no port given; using CADCRAFT_CONTROL_PORT ({port})"),
None => log::warn!("--control: no port given; the control channel is off"),
}
current
}
fn main() -> eframe::Result {
// First, so every start-up record is captured; see `logging`.
let logger = logging::install();
@@ -159,7 +236,7 @@ fn main() -> eframe::Result {
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = control_port_from("--control", args.next()),
"--control" => control_port = control_flag(control_port, args.next()),
"--sample" => sample = true,
"--version" | "-V" => {
println!("{}", version_string());
@@ -196,14 +273,27 @@ fn main() -> eframe::Result {
.with_title_shown(false)
.with_app_id(APP_ID),
persist_window: false,
// A stencil buffer clips the contents of clipped layout viewports on the GPU.
stencil_buffer: STENCIL_BITS,
..Default::default()
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
}
// Before eframe creates the wgpu instance: default Windows to DirectX 12 only (see graphics.rs).
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
#[cfg(target_os = "windows")]
graphics::configure(&mut options, eframe::wgpu::Backends::from_env());
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
// Command previews (COPY, MOVE...) of large selections are tessellated by egui, whose index
// buffer outgrew wgpu's default 256 MiB cap; the validation error is fatal. Ask for what the
// adapter actually supports.
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
let base = std::sync::Arc::clone(&create.device_descriptor);
create.device_descriptor = std::sync::Arc::new(move |adapter| {
let mut d = base(adapter);
d.required_limits.max_buffer_size = d.required_limits.max_buffer_size.max(adapter.limits().max_buffer_size);
d
});
}
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
@@ -219,16 +309,42 @@ fn main() -> eframe::Result {
options,
Box::new(move |cc| {
let mut app = CadApp::new(Session::empty(), services());
let (workspace, restored, workspace_error) = workspace::Workspace::load();
if let Some(ui) = restored {
app.ui = ui;
}
if let Some(error) = &workspace_error {
eprintln!("CADCraft workspace: {error}");
app.set_status(error);
}
app.system_languages = std::env::var("CADCRAFT_LOCALE").map(|s| vec![s]).unwrap_or_else(|_| sys_locale::get_locales().collect());
// The user profile (Options): drafting settings, selection sizes, drawing-area colours.
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
app.load_profile(&profile);
}
if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::PREFS_KEY)) {
app.load_prefs(&prefs);
}
if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::autosave::PREFS_KEY)) {
cadcraft_ui_egui::autosave::load_prefs(&prefs);
}
// Autosave files (SAVEFILEPATH) default to `<settings dir>/autosave`.
if let Some(dir) = config_dir() {
app.enable_autosave(&dir.join("autosave"));
// Startup LISP (acad.lsp, acaddoc.lsp) is read from `<settings>/support`; the
// folder is made so it is there to put them in.
let support = dir.join("support");
if let Err(e) = std::fs::create_dir_all(&support) {
log::warn!("no LISP support folder {}: {e}", support.display());
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cfg!(target_os = "macos");
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
if let Some(rs) = &cc.wgpu_render_state {
app.set_wgpu(rs);
app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, STENCIL_BITS));
}
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
@@ -243,18 +359,27 @@ fn main() -> eframe::Result {
if app.session.docs.is_empty() {
app.session.new_drawing(false);
}
Ok(Box::new(App(
app,
let ctx = cc.egui_ctx.clone();
let desktop_theme = desktop_theme::DesktopTheme::start(move || ctx.request_repaint());
let ctx = cc.egui_ctx.clone();
let system_animations = system_animations::SystemAnimations::start(move || ctx.request_repaint());
Ok(Box::new(App {
desktop_theme,
system_animations,
cad: app,
spacemouse: spacemouse::SpaceMouse::start(cc.egui_ctx.clone()),
workspace,
workspace_error,
#[cfg(target_os = "macos")]
None,
)))
native_menu: None,
}))
}),
)
}
#[cfg(test)]
mod tests {
use super::{config_dir_from, control_port_from, filters_for_save};
use super::{config_dir_from, control_flag, control_port_from, filters_for_save, follow_desktop};
use std::ffi::OsString;
use std::path::PathBuf;
@@ -271,6 +396,7 @@ mod tests {
assert_eq!(first("Drawing1.dxf"), "dxf");
assert_eq!(first("Drawing1"), "dxf");
assert_eq!(first("plan.pdf"), "pdf");
assert_eq!(first("office.dwt"), "dwt");
for name in ["a.dwg", "b.dxf", "c"] {
let exts: Vec<_> = filters_for_save(name).iter().map(|(_, e)| *e).collect();
assert!(exts.contains(&"dwg") && exts.contains(&"dxf"), "{name}");
@@ -287,6 +413,16 @@ mod tests {
}
}
#[test]
fn control_without_a_port_keeps_the_environment_port() {
// `CADCRAFT_CONTROL_PORT=47321 cadcraft --control` (#844)
assert_eq!(control_flag(Some(47321), None), Some(47321));
assert_eq!(control_flag(None, None), None);
// A port given on the command line still wins over the variable.
assert_eq!(control_flag(Some(47321), Some("7979".into())), Some(7979));
assert_eq!(control_flag(Some(47321), Some("abc".into())), None);
}
#[test]
fn the_override_variable_wins_and_empty_values_are_unset() {
let vars = [("CADCRAFT_CONFIG_DIR", "/tmp/cc"), ("HOME", "/home/u"), ("XDG_CONFIG_HOME", "/x"), ("APPDATA", "C:\\a")];
@@ -319,4 +455,19 @@ mod tests {
Some(PathBuf::from("C:\\Users\\u\\AppData\\Roaming").join("CADCraft"))
);
}
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
#[test]
fn the_desktop_answers_for_the_system_theme() {
let mut raw = egui::RawInput::default();
follow_desktop(&mut raw, Some(egui::Theme::Light));
assert_eq!(raw.system_theme, Some(egui::Theme::Light));
let mut raw = egui::RawInput { system_theme: Some(egui::Theme::Dark), ..Default::default() };
follow_desktop(&mut raw, None);
assert_eq!(raw.system_theme, Some(egui::Theme::Dark));
let mut raw = egui::RawInput::default();
follow_desktop(&mut raw, None);
assert_eq!(raw.system_theme, None);
}
}
+30 -5
View File
@@ -16,6 +16,9 @@ pub struct NativeMenu {
predefined: Vec<(&'static str, PredefinedMenuItem)>,
language: &'static str,
last_refresh: f64,
/// The recent files File ▸ Open Recent lists now (it is rebuilt when they change).
recent: Vec<String>,
counter: usize,
}
/// Accelerator for "Cmd+Shift+S" (modifier-less shortcuts stay in the app so typing works).
@@ -43,7 +46,9 @@ impl NativeMenu {
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
let _ = app_menu.append_items(&[&about, &discord, &PredefinedMenuItem::separator()]);
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
let _ = app_menu.append_items(&[&about, &discord, &PredefinedMenuItem::separator(), &settings, &PredefinedMenuItem::separator()]);
for (label, item) in &predefined {
let _ = app_menu.append(item);
if ["Services", "Show All"].contains(label) {
@@ -52,15 +57,34 @@ impl NativeMenu {
}
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
let _ = menu.append(&app_menu);
for (title, entries) in menus::tree(app) {
let sub = Submenu::new(i18n::tr(language, &title), true);
let sub = Submenu::new(i18n::tr_menu(language, &title), true);
build(&sub, &entries, &mut items, &mut submenus, &mut counter, language);
let _ = menu.append(&sub);
submenus.push((title, sub));
}
menu.init_for_nsapp();
Self { _menu: menu, items, submenus, predefined, language, last_refresh: 0.0 }
Self { _menu: menu, items, submenus, predefined, language, last_refresh: 0.0, recent: app.ui.recent_files.clone(), counter }
}
/// Rebuild File ▸ Open Recent after a drawing was opened or the list was cleared: the native
/// menu is built once, and its items name the files by position.
fn refresh_recent(&mut self, app: &CadApp) {
if self.recent == app.ui.recent_files {
return;
}
self.recent = app.ui.recent_files.clone();
let Some(sub) = self.submenus.iter().find(|(label, _)| label == menus::OPEN_RECENT).map(|(_, s)| s.clone()) else { return };
for _ in sub.items() {
sub.remove_at(0);
}
let ids: Vec<String> = self.items.iter().filter(|(_, (cmd, _, _))| cmd.starts_with("ui.recent.")).map(|(id, _)| id.clone()).collect();
for id in ids {
self.items.remove(&id);
}
build(&sub, &menus::recent_entries(app), &mut self.items, &mut self.submenus, &mut self.counter, self.language);
}
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
@@ -74,6 +98,7 @@ impl NativeMenu {
ctx.request_repaint();
}
}
self.refresh_recent(app);
let language = app.language();
if self.language != language {
self.language = language;
@@ -84,7 +109,7 @@ impl NativeMenu {
item.set_text(i18n::tr(language, label));
}
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr(language, label));
submenu.set_text(i18n::tr_menu(language, label));
}
}
let now = cadcraft_ui_egui::now_ms();
@@ -110,7 +135,7 @@ fn build(
for e in entries {
match e {
Entry::Sub { label, children } => {
let sub = Submenu::new(i18n::tr(language, label), true);
let sub = Submenu::new(i18n::tr_menu(language, label), true);
build(&sub, children, items, submenus, counter, language);
let _ = parent.append(&sub);
submenus.push((label.clone(), sub));
+242
View File
@@ -0,0 +1,242 @@
//! Native 3Dconnexion input. The reader publishes one latest sample, never an input queue;
//! only movement starting/stopping or status/buttons wake egui. Active motion runs at 60 Hz.
#[cfg(any(target_os = "windows", target_os = "linux"))]
mod motion;
use cadcraft_ui_egui::{CadApp, spacemouse::Status};
#[cfg(any(target_os = "windows", target_os = "linux"))]
use std::time::Duration;
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
time::Instant,
};
#[derive(Default)]
struct Shared {
status: Status,
device: Option<String>,
detail: Option<String>,
#[cfg(any(target_os = "windows", target_os = "linux"))]
motion: motion::Motion,
#[cfg(any(target_os = "windows", target_os = "linux"))]
last_report: Option<Instant>,
buttons: u8,
recalibrate: bool,
}
pub struct SpaceMouse {
shared: Arc<Mutex<Shared>>,
stop: Arc<AtomicBool>,
last_frame: Instant,
#[cfg(any(target_os = "windows", target_os = "linux"))]
moving: bool,
}
impl SpaceMouse {
pub fn start(ctx: egui::Context) -> Self {
let shared = Arc::new(Mutex::new(Shared::default()));
let stop = Arc::new(AtomicBool::new(false));
#[cfg(any(target_os = "windows", target_os = "linux"))]
{
let (input, quit, context) = (Arc::clone(&shared), Arc::clone(&stop), ctx.clone());
if let Err(error) = std::thread::Builder::new().name("spacemouse-hid".into()).spawn(move || read(input, quit, context)) {
set_status(&shared, &ctx, Status::Error, None, Some(error.to_string()));
}
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
let _ = ctx;
Self {
shared,
stop,
last_frame: Instant::now(),
#[cfg(any(target_os = "windows", target_os = "linux"))]
moving: false,
}
}
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
let now = Instant::now();
let elapsed = now.saturating_duration_since(self.last_frame).as_secs_f64().min(0.05);
self.last_frame = now;
let Ok(mut shared) = self.shared.lock() else { return };
if std::mem::take(&mut app.spacemouse.calibrate_requested) {
shared.recalibrate = true;
}
let changed = app.spacemouse.status != shared.status || app.spacemouse.device != shared.device || app.spacemouse.detail != shared.detail;
app.spacemouse.status = shared.status;
app.spacemouse.device.clone_from(&shared.device);
app.spacemouse.detail.clone_from(&shared.detail);
if changed && !matches!(shared.status, Status::Unavailable | Status::Searching) {
app.set_status(cadcraft_ui_egui::i18n::tr(app.language(), shared.status.message()));
}
let buttons = std::mem::take(&mut shared.buttons);
#[cfg(any(target_os = "windows", target_os = "linux"))]
let motion = if shared.last_report.is_some_and(|at| now.saturating_duration_since(at) < Duration::from_millis(250)) {
shared.motion
} else {
motion::Motion::default()
};
drop(shared);
let allowed = app.spacemouse.settings.enabled
&& ctx.input(|i| i.focused)
&& !app.ui.start_tab
&& app.ui.dialog.is_none()
&& app.closing.is_none()
&& app.canvas.rect.is_some()
&& !egui::Popup::is_any_open(ctx);
if allowed && buttons & 1 != 0 {
let _ = app.run("zoom", serde_json::json!({"mode": "extents"}));
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
{
let moving = allowed && motion.active();
if moving {
if self.moving {
let settings = app.spacemouse.settings;
let rate = if settings.reverse_zoom { -settings.zoom_speed } else { settings.zoom_speed };
if let Err(error) = app.run(
"ui.spacemouse.navigate",
serde_json::json!({
"pan": motion.pan.map(|v| v * settings.pan_speed * elapsed),
"zoom": (motion.zoom * rate * elapsed).exp()
}),
) {
app.set_status(error);
}
}
ctx.request_repaint_after(Duration::from_millis(16));
}
self.moving = moving;
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
let _ = elapsed;
}
}
impl Drop for SpaceMouse {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
}
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
fn set_status(shared: &Mutex<Shared>, ctx: &egui::Context, status: Status, device: Option<String>, detail: Option<String>) {
let Ok(mut state) = shared.lock() else { return };
let changed = state.status != status || state.device != device || state.detail != detail;
if !changed {
return;
}
if let Some(error) = &detail {
log::warn!("3D mouse: {error}");
}
state.status = status;
state.device = device;
state.detail = detail;
state.motion = motion::Motion::default();
state.last_report = None;
state.buttons = 0;
drop(state);
ctx.request_repaint();
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
fn retry(stop: &AtomicBool) {
for _ in 0..40 {
if stop.load(Ordering::Relaxed) {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
fn read(shared: Arc<Mutex<Shared>>, stop: Arc<AtomicBool>, ctx: egui::Context) {
while !stop.load(Ordering::Relaxed) {
let mut api = match hidapi::HidApi::new() {
Ok(api) => api,
Err(error) => {
set_status(&shared, &ctx, Status::Error, None, Some(error.to_string()));
retry(&stop);
continue;
}
};
while !stop.load(Ordering::Relaxed) {
if let Err(error) = api.refresh_devices() {
set_status(&shared, &ctx, Status::Error, None, Some(error.to_string()));
break;
}
let device =
api.device_list().find(|device| matches!(device.vendor_id(), 0x046d | 0x256f) && device.usage_page() == 1 && device.usage() == 8);
let Some(info) = device else {
set_status(&shared, &ctx, Status::Searching, None, None);
retry(&stop);
continue;
};
let name = info.product_string().unwrap_or("3Dconnexion SpaceMouse").to_string();
match info.open_device(&api) {
Ok(device) => {
set_status(&shared, &ctx, Status::Calibrating, Some(name.clone()), None);
if let Err(error) = read_device(&device, &shared, &stop, &ctx, &name) {
set_status(&shared, &ctx, Status::Disconnected, Some(name), Some(error.to_string()));
}
}
Err(error) => set_status(&shared, &ctx, Status::OpenFailed, Some(name), Some(error.to_string())),
}
retry(&stop);
}
retry(&stop);
}
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
fn read_device(device: &hidapi::HidDevice, shared: &Mutex<Shared>, stop: &AtomicBool, ctx: &egui::Context, name: &str) -> hidapi::HidResult<()> {
let mut filter = motion::Filter::default();
let mut buffer = [0; 64];
let mut buttons = 0;
while !stop.load(Ordering::Relaxed) {
let recalibrate = if let Ok(mut state) = shared.lock() { std::mem::take(&mut state.recalibrate) } else { return Ok(()) };
if recalibrate {
filter.recalibrate();
set_status(shared, ctx, Status::Calibrating, Some(name.into()), None);
}
let len = device.read_timeout(&mut buffer, 50)?;
let now = Instant::now();
let report = buffer.get(..len).and_then(motion::decode);
let Ok(mut state) = shared.lock() else { return Ok(()) };
let mut wake = false;
match report {
Some(motion::Report::Buttons(next)) => {
let pressed = next & !buttons;
buttons = next;
state.buttons |= pressed & 1;
state.recalibrate |= pressed & 2 != 0;
wake = pressed != 0;
}
Some(motion::Report::Axes { values, mask }) => {
let motion = filter.update(values, mask, now);
wake = state.motion.active() != motion.active();
state.motion = motion;
state.last_report = Some(now);
if filter.calibrated() && state.status != Status::Connected {
state.status = Status::Connected;
wake = true;
}
}
None => {
if state.motion.active() && state.last_report.is_some_and(|at| now.saturating_duration_since(at) >= Duration::from_millis(250)) {
state.motion = motion::Motion::default();
wake = true;
}
}
}
drop(state);
if wake {
ctx.request_repaint();
}
}
Ok(())
}
+158
View File
@@ -0,0 +1,158 @@
//! Bounded, dependency-free decoding and rest calibration of 3Dconnexion HID input reports.
use std::time::{Duration, Instant};
const FULL_SCALE: f64 = 500.0;
const DEADZONE: f64 = 0.04;
const REST_LIMIT: f64 = 60.0;
const REST_RANGE: f64 = 10.0;
const CALIBRATION_TIME: Duration = Duration::from_millis(400);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Report {
/// Mask 1 = translation, 2 = rotation, 3 = a combined six-axis report.
Axes {
values: [i16; 6],
mask: u8,
},
Buttons(u8),
}
/// hidapi includes the report ID. A legacy motion report has six payload bytes; combined
/// report 1 has twelve. Windows may pad the short button report to the input-report size.
pub fn decode(bytes: &[u8]) -> Option<Report> {
let (&id, payload) = bytes.split_first()?;
if id == 3 {
return payload.first().copied().map(Report::Buttons);
}
let (mask, offset, count) = match id {
1 if payload.len() >= 12 => (3, 0, 6),
1 if payload.len() >= 6 => (1, 0, 3),
2 if payload.len() >= 6 => (2, 3, 3),
_ => return None,
};
let mut values = [0; 6];
for (out, pair) in values.iter_mut().skip(offset).take(count).zip(payload.as_chunks::<2>().0.iter()) {
*out = i16::from_le_bytes([*pair.first()?, *pair.get(1)?]);
}
Some(Report::Axes { values, mask })
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Motion {
pub pan: [f64; 2],
pub zoom: f64,
}
impl Motion {
pub fn active(self) -> bool {
self.pan.iter().any(|v| *v != 0.0) || self.zoom != 0.0
}
}
#[derive(Default)]
struct Rest {
since: Option<Instant>,
count: u32,
sum: [f64; 6],
min: [f64; 6],
max: [f64; 6],
}
impl Rest {
fn observe(&mut self, raw: [f64; 6], now: Instant) -> Option<[f64; 6]> {
if raw.iter().any(|v| v.abs() > REST_LIMIT) {
*self = Self::default();
return None;
}
if self.since.is_none() || raw.iter().zip(self.min.iter().zip(&self.max)).any(|(v, (min, max))| v.max(*max) - v.min(*min) > REST_RANGE) {
*self = Self { since: Some(now), count: 1, sum: raw, min: raw, max: raw };
return None;
}
for ((min, max), value) in self.min.iter_mut().zip(&mut self.max).zip(raw) {
*min = min.min(value);
*max = max.max(value);
}
// A fixed bound even if a device sends far more than the expected 125 reports/sec.
if self.count < 128 {
self.count += 1;
for (sum, value) in self.sum.iter_mut().zip(raw) {
*sum += value;
}
}
if self.count >= 16 && self.since.is_some_and(|since| now.saturating_duration_since(since) >= CALIBRATION_TIME) {
Some(self.sum.map(|sum| sum / f64::from(self.count)))
} else {
None
}
}
}
#[derive(Default)]
pub struct Filter {
raw: [f64; 6],
bias: Option<[f64; 6]>,
rest: Rest,
parts: u8,
seen: [Option<Instant>; 2],
idle_since: Option<Instant>,
}
impl Filter {
pub fn calibrated(&self) -> bool {
self.bias.is_some()
}
pub fn recalibrate(&mut self) {
*self = Self::default();
}
pub fn update(&mut self, values: [i16; 6], mask: u8, now: Instant) -> Motion {
for (index, seen) in self.seen.iter_mut().enumerate() {
if mask & (1 << index) != 0 {
*seen = Some(now);
}
}
for (index, (raw, value)) in self.raw.iter_mut().zip(values).enumerate() {
if mask & if index < 3 { 1 } else { 2 } != 0 {
*raw = f64::from(value);
}
}
self.parts |= mask & 3;
let complete = self.parts == 3;
if complete {
self.parts = 0;
}
if self.bias.is_none() && complete {
self.bias = self.rest.observe(self.raw, now);
}
let Some(mut bias) = self.bias else { return Motion::default() };
// Follow small resting drift only after two seconds entirely inside the deadzone.
if complete {
if self.raw.iter().zip(bias).all(|(raw, bias)| (*raw - bias).abs() <= FULL_SCALE * DEADZONE) {
let since = *self.idle_since.get_or_insert(now);
if now.saturating_duration_since(since) >= Duration::from_secs(2) {
for (bias, raw) in bias.iter_mut().zip(self.raw) {
*bias += (raw - *bias) * 0.01;
}
self.bias = Some(bias);
}
} else {
self.idle_since = None;
}
}
let mut axes = [0.0; 6];
for ((axis, raw), bias) in axes.iter_mut().zip(self.raw).zip(bias) {
let value = ((raw - bias) / FULL_SCALE).clamp(-1.0, 1.0);
*axis = if value.abs() <= DEADZONE { 0.0 } else { value.signum() * (value.abs() - DEADZONE) / (1.0 - DEADZONE) };
}
// A missing rotation report must not keep zooming while translations still arrive.
for (group, seen) in axes.as_chunks_mut::<3>().0.iter_mut().zip(self.seen) {
if seen.is_none_or(|at| now.saturating_duration_since(at) >= Duration::from_millis(250)) {
group.fill(0.0);
}
}
let [tx, ty, tz, _rx, _ry, rz] = axes;
Motion { pan: [tx, ty], zoom: (tz + rz).clamp(-1.0, 1.0) }
}
}
+182
View File
@@ -0,0 +1,182 @@
//! Whether the operating system shows animations, for View ▸ Accessibility ▸ Animation Effects ▸
//! Use System Setting.
//!
//! egui animates whatever the OS says (windows and menus fade in, wheel scrolling glides), and
//! winit reports no such setting. This asks the OS itself:
//!
//! - Windows: Settings ▸ Accessibility ▸ Visual effects ▸ Animation effects.
//! - macOS: System Settings ▸ Accessibility ▸ Reduce motion.
//! - Linux and the BSDs: the XDG Desktop Portal's Settings interface, as for the theme
//! (`desktop_theme.rs`): its `reduced-motion`, or GNOME's own `enable-animations`.
//!
//! The answer goes to `CadApp::system_animations` once a frame.
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use std::time::{Duration, Instant};
/// How often the OS is asked again, so a change to its setting is followed while CADCraft runs.
const POLL: Duration = Duration::from_secs(3);
/// Watches the OS setting.
#[derive(Default)]
pub struct SystemAnimations {
/// The watcher thread's answers, where asking can block (the portal); `None` elsewhere, or
/// when no thread could be started.
changes: Option<Receiver<Option<bool>>>,
/// The OS's last answer.
current: Option<bool>,
/// When the OS was last asked from the UI thread, where asking is one quick call.
asked: Option<Instant>,
}
impl SystemAnimations {
/// Start watching. Where a thread does the asking, `wake` is called after each answer, so an
/// idle window repaints and picks it up.
pub fn start(wake: impl Fn() + Send + 'static) -> Self {
if !ASKS_THE_PORTAL {
return Self::default();
}
let (tx, rx) = channel();
let started = std::thread::Builder::new().name("cadcraft-system-animations".into()).spawn(move || {
let mut last = read();
if tx.send(last).is_err() {
return;
}
wake();
loop {
std::thread::sleep(POLL);
let now = read();
if now != last {
last = now;
if tx.send(now).is_err() {
return;
}
wake();
}
}
});
Self { changes: started.ok().map(|_| rx), ..Self::default() }
}
/// Whether the OS shows animations; `None` when it states nothing or there is nobody to ask.
/// Polled once a frame; an OS that stops answering keeps its last answer.
pub fn current(&mut self) -> Option<bool> {
if let Some(changes) = &self.changes {
loop {
match changes.try_recv() {
Ok(Some(animate)) => self.current = Some(animate),
Ok(None) => {}
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
}
}
} else if !ASKS_THE_PORTAL && self.asked.is_none_or(|at| at.elapsed() >= POLL) {
self.asked = Some(Instant::now());
if let Some(animate) = read() {
self.current = Some(animate);
}
}
self.current
}
}
/// Where the answer comes over D-Bus, which can block: a thread asks. Elsewhere the UI thread asks.
const ASKS_THE_PORTAL: bool = cfg!(all(unix, not(target_os = "macos")));
/// Ask Windows once: `UISettings::AnimationsEnabled`, the setting behind
/// `SPI_GETCLIENTAREAANIMATION`.
#[cfg(windows)]
fn read() -> Option<bool> {
windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()).ok()
}
/// Ask macOS once. Called on the main thread (`SystemAnimations::current`).
#[cfg(target_os = "macos")]
fn read() -> Option<bool> {
Some(!objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion())
}
/// Ask the portal once. D-Bus calls block, so this belongs off the UI thread: the watcher's
/// thread is its only caller.
#[cfg(all(unix, not(target_os = "macos")))]
fn read() -> Option<bool> {
const PORTAL: &str = "org.freedesktop.portal.Desktop";
const PATH: &str = "/org/freedesktop/portal/desktop";
const SETTINGS: &str = "org.freedesktop.portal.Settings";
// The standard key first (0 no preference, 1 reduced motion); then GNOME's own switch, which
// its portal answered before the standard key existed.
const KEYS: [(&str, &str); 2] = [("org.freedesktop.appearance", "reduced-motion"), ("org.gnome.desktop.interface", "enable-animations")];
let connection = zbus::blocking::Connection::session().ok()?;
for (namespace, key) in KEYS {
// `ReadOne` (Settings version 2) answers the value; older portals only have `Read`, which
// wraps it in one more variant. `parse` unwraps either.
let reply = connection
.call_method(Some(PORTAL), PATH, Some(SETTINGS), "ReadOne", &(namespace, key))
.or_else(|_| connection.call_method(Some(PORTAL), PATH, Some(SETTINGS), "Read", &(namespace, key)));
let Ok(reply) = reply else { continue };
let Ok((answer,)) = reply.body().deserialize::<(zbus::zvariant::OwnedValue,)>() else { continue };
if let Some(animate) = parse(&answer, 0) {
return Some(animate);
}
}
None
}
/// The portal's answer as "show animations": `reduced-motion` is a number (1 asks for less
/// motion; 0 and values from a later version state no preference), `enable-animations` a
/// boolean. `None` when it reads as neither. Variants are unwrapped a few levels deep.
#[cfg(all(unix, not(target_os = "macos")))]
fn parse(value: &zbus::zvariant::Value<'_>, depth: u8) -> Option<bool> {
use zbus::zvariant::Value;
match value {
Value::U32(reduced) => Some(*reduced != 1),
Value::Bool(enabled) => Some(*enabled),
Value::Value(inner) if depth < 4 => parse(inner, depth + 1),
_ => None,
}
}
#[cfg(not(any(unix, windows)))]
fn read() -> Option<bool> {
None
}
// macOS is asked on the main thread only, so there is nothing to test off it.
#[cfg(all(test, not(target_os = "macos")))]
mod tests {
use super::*;
/// Windows is asked on the first frame, then not again until the poll interval has passed.
#[test]
#[cfg(windows)]
fn the_os_is_asked_on_the_first_frame_and_its_answer_kept() {
let mut watch = SystemAnimations::start(|| {});
assert!(watch.changes.is_none(), "no thread: asking is one quick call");
let first = watch.current();
assert_eq!(first, read());
let asked = watch.asked;
assert!(asked.is_some());
assert_eq!(watch.current(), first);
assert_eq!(watch.asked, asked, "not asked again within the poll interval");
}
/// The standard key answers a number, GNOME's switch a boolean; either may come wrapped in
/// variants (the older `Read`).
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn the_portal_answer_reads_as_show_animations_or_as_none() {
use zbus::zvariant::Value;
assert_eq!(parse(&Value::U32(1), 0), Some(false));
assert_eq!(parse(&Value::U32(0), 0), Some(true));
assert_eq!(parse(&Value::U32(7), 0), Some(true), "unknown values are no preference");
assert_eq!(parse(&Value::Bool(false), 0), Some(false));
assert_eq!(parse(&Value::Bool(true), 0), Some(true));
assert_eq!(parse(&Value::Value(Box::new(Value::U32(1))), 0), Some(false));
assert_eq!(parse(&Value::Str("off".into()), 0), None);
// A hostile answer nested without end is given up on.
let mut nested = Value::U32(1);
for _ in 0..16 {
nested = Value::Value(Box::new(nested));
}
assert_eq!(parse(&nested, 0), None);
}
}
+336
View File
@@ -0,0 +1,336 @@
//! Native workspace preferences. Drawing data and transient dialogs never enter this file.
use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use cadcraft_ui_egui::UiState;
use serde_json::{Value, json};
const MAX_BYTES: u64 = 64 * 1024;
static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
pub struct Workspace {
path: Option<PathBuf>,
last_attempt: Option<Value>,
read_failed: bool,
pending_write_error: Option<String>,
}
fn config_dir_from(platform: &str, get: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
if let Some(root) = get("CADCRAFT_CONFIG_DIR") {
return (!root.is_empty()).then(|| PathBuf::from(root));
}
let nonempty = |key| get(key).filter(|value| !value.is_empty()).map(PathBuf::from);
match platform {
"macos" => nonempty("HOME").map(|home| home.join("Library/Application Support/CADCraft")),
"windows" => nonempty("APPDATA").map(|root| root.join("CADCraft")),
_ => nonempty("XDG_CONFIG_HOME").map(|root| root.join("cadcraft")).or_else(|| nonempty("HOME").map(|home| home.join(".config/cadcraft"))),
}
}
fn snapshot(ui: &UiState) -> Result<Value, String> {
ui.docking.validate()?;
if !matches!(ui.toolset_tab.as_str(), "Drafting" | "Modeling") {
return Err("toolsetTab must be Drafting or Modeling".into());
}
if ui.collapsed_groups.len() > 64 || ui.collapsed_groups.iter().any(|name| name.len() > 256) {
return Err("collapsedGroups exceeds the workspace size limit".into());
}
if ui.history_lines > 12 {
return Err("historyLines must be between 0 and 12".into());
}
Ok(json!({
"docking": ui.docking,
"showToolsets": ui.show_toolsets,
"showPalettes": ui.show_palettes,
"showToolbar": ui.show_toolbar,
"showFileTabs": ui.show_file_tabs,
"showStatusBar": ui.show_status_bar,
"showCommandLine": ui.show_command_line,
"showViewcube": ui.show_viewcube,
"showUcsIcon": ui.show_ucs_icon,
"showLayerList": ui.show_layer_list,
"toolsetTab": ui.toolset_tab,
"collapsedGroups": ui.collapsed_groups,
"propertiesAll": ui.properties_all,
"inWindowMenu": ui.in_window_menu,
"historyLines": ui.history_lines,
}))
}
fn read(path: &Path) -> Result<Option<UiState>, String> {
let file = match File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(format!("{}: {error}", path.display())),
};
let mut bytes = Vec::new();
file.take(MAX_BYTES + 1).read_to_end(&mut bytes).map_err(|error| format!("{}: {error}", path.display()))?;
if bytes.len() as u64 > MAX_BYTES {
return Err(format!("{}: workspace file exceeds 64 KiB", path.display()));
}
let value: Value = serde_json::from_slice(&bytes).map_err(|error| format!("{}: invalid workspace JSON: {error}", path.display()))?;
if value.get("version").and_then(Value::as_u64) != Some(1) {
return Err(format!("{}: unsupported workspace version", path.display()));
}
let workspace =
value.get("workspace").filter(|value| value.is_object()).ok_or_else(|| format!("{}: missing workspace object", path.display()))?;
// Dock schemas can evolve independently of the other saved workspace preferences.
// Recover only this optional field; runtime UiState deserialization remains strict.
let mut fields = workspace.clone();
let docking = fields.as_object_mut().and_then(|fields| fields.remove("docking"));
let mut ui: UiState = serde_json::from_value(fields).map_err(|error| format!("{}: invalid workspace: {error}", path.display()))?;
if let Some(docking) = docking
&& let Ok(docking) = serde_json::from_value::<cadcraft_ui_egui::docking::Workspace>(docking)
&& docking.validate().is_ok()
{
ui.docking = docking;
}
// Old or hand-edited files cannot reopen a dialog or replace the active drawing view.
ui.dialog = None;
ui.start_tab = false;
snapshot(&ui).map_err(|error| format!("{}: {error}", path.display()))?;
Ok(Some(ui))
}
fn write(path: &Path, workspace: &Value) -> Result<(), String> {
let bytes = serde_json::to_vec_pretty(&json!({"version": 1, "workspace": workspace})).map_err(|error| error.to_string())?;
if bytes.len() as u64 > MAX_BYTES {
return Err("workspace exceeds 64 KiB".into());
}
let parent = path.parent().ok_or("workspace path has no parent")?;
fs::create_dir_all(parent).map_err(|error| format!("{}: {error}", parent.display()))?;
let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let temporary = parent.join(format!(".workspace-{}-{sequence}.tmp", std::process::id()));
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&temporary).map_err(|error| format!("{}: {error}", temporary.display()))?;
let result = (|| {
file.write_all(&bytes)?;
file.sync_all()?;
drop(file);
fs::rename(&temporary, path)
})();
if let Err(error) = result {
let _ = fs::remove_file(&temporary);
return Err(format!("{}: could not save workspace: {error}", path.display()));
}
Ok(())
}
impl Workspace {
pub fn load() -> (Self, Option<UiState>, Option<String>) {
Self::at(config_dir_from(std::env::consts::OS, |key| std::env::var_os(key)).map(|root| root.join("workspace.json")))
}
fn at(path: Option<PathBuf>) -> (Self, Option<UiState>, Option<String>) {
let result = path.as_deref().map(read).transpose().map(Option::flatten);
match result {
Ok(ui) => {
let initial = ui.as_ref().cloned().unwrap_or_default();
(Self { path, last_attempt: snapshot(&initial).ok(), read_failed: false, pending_write_error: None }, ui, None)
}
Err(error) => (
Self { path, last_attempt: None, read_failed: true, pending_write_error: None },
None,
Some(format!("Workspace could not be restored; its file was left unchanged. {error}")),
),
}
}
pub fn save_if_changed(&mut self, ui: &UiState) -> Result<(), String> {
let Some(path) = &self.path else { return Ok(()) };
if self.read_failed {
// Preserve a corrupt, oversized or newer-version file until the user repairs it.
return Ok(());
}
let value = snapshot(ui)?;
if self.last_attempt.as_ref() == Some(&value) {
return self.pending_write_error.clone().map_or(Ok(()), Err);
}
// Keep a failed state's warning without retrying disk I/O every rendered frame.
self.last_attempt = Some(value.clone());
let result = write(path, &value);
self.pending_write_error = result.as_ref().err().cloned();
result
}
pub fn save_on_exit(&mut self, ui: &UiState) -> Result<(), String> {
if self.pending_write_error.is_some() {
self.last_attempt = None;
}
self.save_if_changed(ui)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir() -> PathBuf {
let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("cadcraft-workspace-test-{}-{sequence}", std::process::id()));
fs::create_dir_all(&path).unwrap();
path
}
#[test]
fn profile_override_isolated_or_explicitly_disabled() {
let get = |key: &str| match key {
"CADCRAFT_CONFIG_DIR" => Some(OsString::from("/private/test-state")),
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some(OsString::from("/unrelated-user-profile")),
_ => None,
};
for platform in ["macos", "windows", "linux", "freebsd"] {
assert_eq!(config_dir_from(platform, get), Some(PathBuf::from("/private/test-state")));
assert_eq!(config_dir_from(platform, |key| if key == "CADCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { get(key) }), None);
}
assert_eq!(
config_dir_from("linux", |key| (key == "XDG_CONFIG_HOME").then(|| OsString::from("/config"))),
Some(PathBuf::from("/config/cadcraft"))
);
assert_eq!(config_dir_from("macos", |_| None), None);
}
#[test]
fn workspace_survives_new_store_without_transient_or_document_state() {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
assert!(restored.is_none() && error.is_none());
let ui = UiState {
show_palettes: false,
show_command_line: false,
toolset_tab: "Modeling".into(),
collapsed_groups: vec!["Solid".into()],
history_lines: 5,
dialog: Some("layers".into()),
start_tab: true,
..Default::default()
};
first.save_if_changed(&ui).unwrap();
let bytes = fs::read(&path).unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
assert!(value["workspace"].get("dialog").is_none());
assert!(value["workspace"].get("startTab").is_none());
let (_, restored, error) = Workspace::at(Some(path.clone()));
assert!(error.is_none());
let restored = restored.unwrap();
assert_eq!(snapshot(&restored).unwrap(), snapshot(&ui).unwrap());
assert!(restored.dialog.is_none() && !restored.start_tab);
let mut transient_only = ui.clone();
transient_only.dialog = None;
transient_only.start_tab = false;
first.save_if_changed(&transient_only).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn docked_floating_and_hidden_panels_survive_native_workspace_file_reload() {
use cadcraft_ui_egui::docking::Panel;
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState::default();
let mut app = cadcraft_ui_egui::CadApp::new(cadcraft_engine::Session::default(), Default::default());
app.run("ui.dock", json!({"operation":"float", "panel":"layers", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui).unwrap();
let (_, reloaded, error) = Workspace::at(Some(path));
assert!(error.is_none());
let mut reloaded = reloaded.unwrap();
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
reloaded.docking.set_visible(Panel::ToolSets, true).unwrap();
assert!(reloaded.docking.layout.contains(&Panel::ToolSets));
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn malformed_oversized_and_newer_state_are_reported_and_preserved() {
let directory = temp_dir();
let path = directory.join("workspace.json");
for bytes in [
b"{invalid".to_vec(),
vec![b' '; MAX_BYTES as usize + 1],
br#"{"version":2,"workspace":{}}"#.to_vec(),
br#"{"version":1,"workspace":{"toolsetTab":"unknown"}}"#.to_vec(),
br#"{"version":1,"workspace":{"historyLines":18446744073709551615}}"#.to_vec(),
] {
fs::write(&path, &bytes).unwrap();
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
assert!(ui.is_none());
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn unsupported_docking_preserves_other_workspace_preferences() {
let directory = temp_dir();
let path = directory.join("workspace.json");
for docking in [
json!({"layout":{"root":{"FuturePanelGroup":{}}},"hidden":[]}),
json!({"layout":false,"hidden":[]}),
json!({"layout":{"root":null,"floating":[]},"hidden":[["futurePanel",{}]]}),
] {
let workspace = json!({"showToolbar":false,"showPalettes":false,"toolsetTab":"Modeling", "collapsedGroups":["Draw"], "historyLines":7,"docking":docking});
assert!(serde_json::from_value::<UiState>(workspace.clone()).is_err(), "runtime state must stay strict");
fs::write(&path, serde_json::to_vec(&json!({"version":1,"workspace":workspace})).unwrap()).unwrap();
let (_, restored, error) = Workspace::at(Some(path.clone()));
assert!(error.is_none());
let restored = restored.unwrap();
assert!(!restored.show_toolbar);
assert!(!restored.show_palettes);
assert_eq!(restored.toolset_tab, "Modeling");
assert_eq!(restored.collapsed_groups, ["Draw"]);
assert_eq!(restored.history_lines, 7);
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
}
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn invalid_update_cannot_replace_last_good_workspace() {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState { show_palettes: false, ..Default::default() };
store.save_if_changed(&ui).unwrap();
let good = fs::read(&path).unwrap();
ui.collapsed_groups = vec!["x".repeat(257)];
assert!(store.save_if_changed(&ui).is_err());
assert_eq!(fs::read(&path).unwrap(), good);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn failed_write_keeps_warning_and_retries_once_on_exit() {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
// Simulate a destination becoming unavailable after startup.
fs::create_dir(&path).unwrap();
let ui = UiState { show_palettes: false, ..Default::default() };
let first_error = store.save_if_changed(&ui).unwrap_err();
fs::remove_dir(&path).unwrap();
assert_eq!(store.save_if_changed(&ui).unwrap_err(), first_error);
assert!(!path.exists(), "ordinary frames must not retry disk writes");
store.save_on_exit(&ui).unwrap();
assert!(!read(&path).unwrap().unwrap().show_palettes);
fs::remove_dir_all(directory).unwrap();
}
}
+45
View File
@@ -22,9 +22,54 @@ real_name = "Brandon Thomas"
display_name = "Brandon Thomas"
sync_github_name = false
[people.switch87]
real_name = "Gert Pellin"
display_name = "Gert Pellin"
sync_github_name = false
[people.rangoDJ]
sync_github_name = true
[people.Tru10]
display_name = "by Truitt"
sync_github_name = false
[people.tsangiotis]
real_name = "Tasos Sangiotis"
display_name = "Tasos Sangiotis"
sync_github_name = false
[people.vangel76]
sync_github_name = true
[people.WladmirJunior]
real_name = "Wladmir Júnior"
sync_github_name = true
[people.Losminek]
sync_github_name = true
[people.GJoe2]
sync_github_name = true
[people.holmbom]
real_name = "Erik Holmbom"
display_name = "Erik Holmbom"
sync_github_name = false
[people.cyfung1031]
real_name = "Chester Fung"
display_name = "Chester Fung"
sync_github_name = true
[people.C00kieMonsta]
real_name = "Antoine Boxho"
display_name = "Antoine Boxho"
sync_github_name = true
[people.Silvertree2010]
display_name = "Netter"
sync_github_name = false
[people.gurparvez]
real_name = "Gurparvez"
+9 -1
View File
@@ -22,7 +22,7 @@ impl Rgb {
}
pub fn parse_hex(s: &str) -> Option<Rgb> {
let s = s.trim().trim_start_matches('#');
if s.len() != 6 || !s.is_ascii() {
if s.len() != 6 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(s, 16).ok().map(Rgb::from_u32)
@@ -225,6 +225,14 @@ pub fn display_rgb(c: Rgb, aci7: bool, background: Rgb) -> Rgb {
mod tests {
use super::*;
#[test]
fn parse_hex_rejects_non_hex_digits() {
assert_eq!(Rgb::parse_hex("+12345"), None);
assert_eq!(Rgb::parse_hex("-12345"), None);
assert_eq!(Color::parse("#+12345"), None);
assert_eq!(Rgb::parse_hex("#012345"), Some(Rgb(1, 35, 69)));
}
#[test]
fn palette_known_entries() {
assert_eq!(aci_rgb(1), Rgb(255, 0, 0));
+115 -2
View File
@@ -1,4 +1,5 @@
//! AUTOCONSTRAIN: infer constraints from geometry that already nearly satisfies them.
//! AUTOCONSTRAIN: infer constraints from geometry that already nearly satisfies them; and
//! CONSTRAINTINFER's inference for what a command just placed ([`infer_placed`]).
use cadcraft_doc::{Constraint, ConstraintKind, Drawing, EntityKind, GeomRef, Handle, Sub};
use cadcraft_geom::{Line, Vec2};
@@ -101,7 +102,11 @@ fn ang_between(d1: Vec2, d2: Vec2) -> f64 {
pub fn infer(d: &Drawing, handles: &[Handle], o: &InferOptions) -> Vec<Constraint> {
let tol = if o.distance_tolerance.is_finite() { o.distance_tolerance.clamp(0.0, 1e9) } else { 0.05 };
let atol = if o.angle_tolerance.is_finite() { o.angle_tolerance.clamp(0.0, 45.0).to_radians() } else { 1f64.to_radians() };
let allow = |k: ConstraintKind| o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(k.name()));
// Resolve the allowed type names into a set once, so membership is O(1) per candidate instead
// of re-scanning the whole (attacker-controllable) `o.types` list for every geometric match
// (CWE-407). Empty `o.types` means "all types".
let allowed: std::collections::HashSet<String> = o.types.iter().map(|t| t.to_ascii_lowercase()).collect();
let allow = |k: ConstraintKind| allowed.is_empty() || allowed.contains(&k.name().to_ascii_lowercase());
let g = collect(d, handles);
let mut out: Vec<Constraint> = Vec::new();
let mut push = |kind: ConstraintKind, refs: Vec<GeomRef>| {
@@ -191,6 +196,114 @@ pub fn infer(d: &Drawing, handles: &[Handle], o: &InferOptions) -> Vec<Constrain
out
}
/// Constraint types CONSTRAINTINFER applies.
pub const INFER_TYPES: [ConstraintKind; 6] = [
ConstraintKind::Coincident,
ConstraintKind::Tangent,
ConstraintKind::Perpendicular,
ConstraintKind::Parallel,
ConstraintKind::Horizontal,
ConstraintKind::Vertical,
];
/// CONSTRAINTINFER: the constraints that the exact placement of `placed` (objects a command just
/// drew or edited) implies against each other and `others`: end points snapped onto end points,
/// midpoints, centres or onto objects (Coincident), tangent and perpendicular snaps, parallel
/// lines, and horizontal/vertical lines (ortho, polar). Snapped geometry is exact, so the
/// tolerances in `o` are expected to be tight. Only [`INFER_TYPES`] (and `o.types`, when set)
/// are returned, each involving a placed object.
pub fn infer_placed(d: &Drawing, placed: &[Handle], others: &[Handle], o: &InferOptions) -> Vec<Constraint> {
let tol = if o.distance_tolerance.is_finite() { o.distance_tolerance.clamp(0.0, 1e9) } else { 0.0 };
let mut all: Vec<Handle> = placed.iter().take(MAX_OBJECTS).copied().collect();
for h in others {
if all.len() >= MAX_OBJECTS {
break;
}
if !all.contains(h) {
all.push(*h);
}
}
let mine = |c: &Constraint| c.refs.iter().any(|r| placed.contains(&r.handle));
let mut out: Vec<Constraint> = infer(d, &all, o).into_iter().filter(|c| INFER_TYPES.contains(&c.kind) && mine(c)).collect();
// Placed end points on other objects' midpoints, centres, or on the objects themselves.
let allow = o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(ConstraintKind::Coincident.name()));
if !allow {
return out;
}
let g = collect(d, &all);
// Point to point (midpoint, centre) first; point on an object last, so a tangent or
// perpendicular snap keeps its tangency (an end on the curve it touches adds nothing then).
let mut extra = Vec::new();
let mut on = Vec::new();
for (rp, p) in g.points.iter().filter(|(r, _)| placed.contains(&r.handle)) {
if out.iter().any(|c| c.kind == ConstraintKind::Coincident && c.refs.contains(rp)) {
continue;
}
let target = g
.lines
.iter()
.filter(|(r, _, _)| r.handle != rp.handle)
.find_map(|(r, a, b)| {
let ln = Line::new(*a, *b);
if a.mid(*b).dist(*p) <= tol && r.sub == Sub::Whole {
Some(GeomRef::new(r.handle, Sub::Mid))
} else {
let t = ln.param_of(*p);
(ln.dist(*p) <= tol && (0.0..=1.0).contains(&t) && ln.len() > tol).then_some(*r)
}
})
.or_else(|| {
g.curves.iter().filter(|(r, _, _)| r.handle != rp.handle).find_map(|(r, c, rad)| {
if c.dist(*p) <= tol {
Some(GeomRef::new(r.handle, Sub::Center))
} else {
((c.dist(*p) - rad).abs() <= tol && on_arc(d, r.handle, *c, *p)).then_some(*r)
}
})
});
if let Some(t) = target
&& extra.len() + on.len() + out.len() < MAX_CANDIDATES
{
let c = Constraint { id: 0, kind: ConstraintKind::Coincident, refs: vec![*rp, t], name: String::new(), expr: String::new() };
if t.sub == Sub::Whole { on.push(c) } else { extra.push(c) }
}
}
// 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)) {
for (r2, a2, b2) in g.lines.iter().filter(|(r, _, _)| r.handle != r1.handle) {
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
&& (std::f64::consts::FRAC_PI_2 - ang).abs() <= atol
&& l1.len() > tol
&& l2.len() > tol
&& out.len() < MAX_CANDIDATES
{
out.push(Constraint { id: 0, kind: ConstraintKind::Perpendicular, refs: vec![*r1, *r2], name: String::new(), expr: String::new() });
}
}
}
let n = out.iter().take_while(|c| c.kind == ConstraintKind::Coincident).count();
out.splice(n..n, extra);
out.extend(on);
out
}
/// Does `p` (on the circle) lie within the arc's sweep (always for a circle)?
fn on_arc(d: &Drawing, h: Handle, c: Vec2, p: Vec2) -> bool {
match d.entity(h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => cadcraft_geom::angle_in_sweep((p - c).angle(), a.start, a.end),
_ => true,
}
}
/// Infer and apply constraints over `handles`; returns the ids added. Redundant or conflicting
/// candidates are skipped.
pub fn autoconstrain(d: &mut Drawing, handles: &[Handle], o: &InferOptions) -> Vec<u32> {
+245
View File
@@ -0,0 +1,245 @@
//! Curve math for the residuals: ellipse points and derivatives, B-spline end derivatives and
//! curve end frames (point, tangent, curvature) for tangent and smooth (G2) joins.
//!
//! Textbook formulas only: the derivative of a clamped B-spline at its ends follows from the
//! derivative control points (Piegl & Tiller, *The NURBS Book*, ch. 3–4), rational curves through
//! the quotient rule on homogeneous coordinates.
use cadcraft_geom::{Spline as GSpline, Vec2};
/// `v <= lim`, or NaN.
pub(crate) fn not_above(v: f64, lim: f64) -> bool {
v.is_nan() || v <= lim
}
/// A curve end: point, unit tangent in the curve's own direction, signed curvature (positive
/// when the curve turns left).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Frame {
pub p: Vec2,
pub t: Vec2,
pub k: f64,
}
impl Frame {
/// From a point and the first and second derivatives with respect to any parameter.
pub fn from_derivs(p: Vec2, d1: Vec2, d2: Vec2) -> Option<Frame> {
let l = d1.len();
if !l.is_finite() || not_above(l, 1e-300) {
return None;
}
let k = d1.cross(d2) / (l * l * l);
let f = Frame { p, t: d1 * (1.0 / l), k };
(f.p.is_finite() && f.t.is_finite() && f.k.is_finite()).then_some(f)
}
/// The same end traversed the other way.
pub fn reversed(self) -> Frame {
Frame { p: self.p, t: -self.t, k: -self.k }
}
}
/// An ellipse or elliptical arc in solver parameters.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Ell {
pub c: Vec2,
/// Major axis vector (centre to the end of the major axis).
pub mj: Vec2,
pub ratio: f64,
pub t0: f64,
pub t1: f64,
pub arc: bool,
}
impl Ell {
pub fn minor(&self) -> Vec2 {
self.mj.perp() * self.ratio
}
pub fn at(&self, t: f64) -> Vec2 {
self.c + self.mj * t.cos() + self.minor() * t.sin()
}
pub fn d1(&self, t: f64) -> Vec2 {
self.mj * -t.sin() + self.minor() * t.cos()
}
pub fn d2(&self, t: f64) -> Vec2 {
self.mj * -t.cos() - self.minor() * t.sin()
}
pub fn frame(&self, t: f64) -> Option<Frame> {
Frame::from_derivs(self.at(t), self.d1(t), self.d2(t))
}
/// Semi-axes `(a, b)`.
fn axes(&self) -> (f64, f64) {
let a = self.mj.len();
(a, a * self.ratio.abs())
}
/// Local coordinates of `p` along the major and minor axes.
fn local(&self, p: Vec2) -> Option<(f64, f64, Vec2, Vec2)> {
let (a, _) = self.axes();
if not_above(a, 1e-300) {
return None;
}
let u_dir = self.mj * (1.0 / a);
let v_dir = u_dir.perp();
let q = p - self.c;
Some((q.dot(u_dir), q.dot(v_dir), u_dir, v_dir))
}
/// A distance-like residual of `p` from the ellipse: zero exactly on it, about the distance
/// near it.
pub fn on(&self, p: Vec2) -> f64 {
let (a, b) = self.axes();
match self.local(p) {
Some((u, v, _, _)) if b > 1e-300 => {
let s = a / b;
(u * u + v * v * s * s).sqrt() - a
}
_ => p.dist(self.c) - a,
}
}
/// Unit outward normal of the ellipse's implicit form at (or near) `p`.
pub fn normal(&self, p: Vec2) -> Vec2 {
let (a, b) = self.axes();
match self.local(p) {
Some((u, v, ud, vd)) if b > 1e-300 => (ud * (u / (a * a)) + vd * (v / (b * b))).normalized(),
_ => (p - self.c).normalized(),
}
}
/// Largest `n·(P − c)` over the ellipse for a unit direction `n` (its support distance).
pub fn support(&self, n: Vec2) -> f64 {
let (x, y) = (n.dot(self.mj), n.dot(self.minor()));
(x * x + y * y).sqrt()
}
}
/// A circle (or the circle of an arc) as a parametric curve.
pub(crate) fn circle_at(c: Vec2, r: f64, t: f64) -> (Vec2, Vec2) {
let (s, co) = t.sin_cos();
(c + Vec2::new(co, s) * r, Vec2::new(-s, co) * r)
}
/// Homogeneous control point.
#[derive(Clone, Copy, Debug)]
struct H {
x: f64,
y: f64,
w: f64,
}
impl H {
fn sub(self, o: H) -> H {
H { x: self.x - o.x, y: self.y - o.y, w: self.w - o.w }
}
fn scale(self, f: f64) -> H {
H { x: self.x * f, y: self.y * f, w: self.w * f }
}
}
/// Is the knot vector clamped (end knot repeated `degree + 1` times) at the start or end?
pub(crate) fn clamped(s: &GSpline, at_end: bool) -> bool {
let p = s.degree;
let k = &s.knots;
if !s.is_valid() || k.len() < 2 * (p + 1) {
return false;
}
let scale = k.iter().fold(1.0f64, |m, v| m.max(v.abs()));
let tol = 1e-12 * scale;
let window = if at_end { k.get(k.len() - p - 1..) } else { k.get(..=p) };
match window {
Some(w) => w.iter().all(|v| w.first().is_some_and(|f| (v - f).abs() <= tol)),
None => false,
}
}
/// End frame of a clamped spline at its start (`at_end` false) or end, in the curve's own
/// direction. `None` for an unclamped end or degenerate data.
pub(crate) fn spline_end(s: &GSpline, at_end: bool) -> Option<Frame> {
if !clamped(s, at_end) {
return None;
}
let p = s.degree;
let n = s.control.len();
let wt = |i: usize| if s.weights.is_empty() { Some(1.0) } else { s.weights.get(i).copied() };
let hp = |i: usize| -> Option<H> {
let c = s.control.get(i)?;
let w = wt(i)?;
Some(H { x: c.x * w, y: c.y * w, w })
};
// Work on the start of the curve; for the end, reverse the control points and knots.
let (q, u): (Vec<H>, Vec<f64>) = if at_end {
let q = (0..n.min(3)).map(|i| hp(n - 1 - i)).collect::<Option<Vec<_>>>()?;
let last = s.knots.len() - 1;
let u = (0..s.knots.len().min(p + 3)).map(|i| s.knots.get(last - i).map(|v| -v)).collect::<Option<Vec<_>>>()?;
(q, u)
} else {
let q = (0..n.min(3)).map(hp).collect::<Option<Vec<_>>>()?;
let u = s.knots.get(..(p + 3).min(s.knots.len()))?.to_vec();
(q, u)
};
let pf = p as f64;
let (q0, q1) = (*q.first()?, *q.get(1)?);
let den1 = u.get(p + 1)? - u.get(1)?;
if not_above(den1.abs(), 1e-300) {
return None;
}
let a1 = q1.sub(q0).scale(pf / den1);
let a2 = if p >= 2 {
let q2 = *q.get(2)?;
let den2 = u.get(p + 2)? - u.get(2)?;
let den0 = u.get(p + 1)? - u.get(2)?;
if !(den2.abs() > 1e-300 && den0.abs() > 1e-300) {
return None;
}
q2.sub(q1).scale(1.0 / den2).sub(q1.sub(q0).scale(1.0 / den1)).scale(pf * (pf - 1.0) / den0)
} else {
H { x: 0.0, y: 0.0, w: 0.0 }
};
// Quotient rule: C = A / w.
if not_above(q0.w.abs(), 1e-300) {
return None;
}
let c = Vec2::new(q0.x / q0.w, q0.y / q0.w);
let c1 = (Vec2::new(a1.x, a1.y) - c * a1.w) / q0.w;
let c2 = (Vec2::new(a2.x, a2.y) - c1 * (2.0 * a1.w) - c * a2.w) / q0.w;
let f = Frame::from_derivs(c, c1, c2)?;
// The reversed curve's start is the end traversed backwards.
Some(if at_end { f.reversed() } else { f })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ellipse_residuals() {
let e = Ell { c: Vec2::new(1.0, 2.0), mj: Vec2::new(4.0, 0.0), ratio: 0.5, t0: 0.0, t1: 1.0, arc: false };
assert!(e.on(Vec2::new(5.0, 2.0)).abs() < 1e-12);
assert!(e.on(Vec2::new(1.0, 4.0)).abs() < 1e-12);
assert!(e.on(Vec2::new(6.0, 2.0)) > 0.0);
assert!((e.support(Vec2::new(0.0, 1.0)) - 2.0).abs() < 1e-12);
assert!((e.support(Vec2::new(1.0, 0.0)) - 4.0).abs() < 1e-12);
assert!(e.normal(Vec2::new(1.0, 4.0)).near(Vec2::new(0.0, 1.0), 1e-12));
// Curvature at the end of the major axis: a / b².
let f = e.frame(0.0).unwrap();
assert!((f.k - 4.0 / 4.0).abs() < 1e-12);
}
#[test]
fn spline_end_derivatives_match_sampling() {
let s = GSpline::from_control(vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0), Vec2::new(3.0, 3.0), Vec2::new(6.0, 1.0)], 3);
for at_end in [false, true] {
let f = spline_end(&s, at_end).unwrap();
let (lo, hi) = s.domain();
let (t, h) = if at_end { (hi, -1e-4) } else { (lo, 1e-4) };
let (p0, p1, p2) = (s.eval(t), s.eval(t + h), s.eval(t + 2.0 * h));
assert!(f.p.near(p0, 1e-12));
// One-sided differences (a negative step at the end still gives d/dt).
let d1 = (p1 - p0) * (1.0 / h);
let d2 = (p2 - p1 * 2.0 + p0) * (1.0 / (h * h));
let g = Frame::from_derivs(p0, d1, d2).unwrap();
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
}
// An unclamped (periodic) spline has no ends.
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
assert!(spline_end(&closed, false).is_none());
}
}
+241
View File
@@ -0,0 +1,241 @@
//! Degrees of freedom: how much the constraints leave the geometry free to move.
//!
//! Per connected component, the remaining DOF is the number of free parameters minus the rank
//! of the constraint Jacobian at the current geometry; equations beyond the rank are redundant
//! (over-constraint). Per object, the DOF is the dimension of the null-space motion restricted
//! to the object's own parameters: how many independent ways the object can still move while
//! every constraint keeps holding (the rest of its component moving along as needed).
use std::collections::HashSet;
use cadcraft_doc::{Constraint, Drawing, Handle};
use serde::Serialize;
use crate::model::Model;
use crate::{Comp, MAX_CONSTRAINTS, SolveError, SolveOptions, build_budgeted, lm};
/// Most free parameters for which per-object freedom is analysed (null-space basis size).
const MAX_NULL_COLS: usize = 600;
/// Largest Jacobian (rows × columns × min) whose rank is computed.
const MAX_RANK_WORK: f64 = 4e8;
/// Largest residual-evaluation work (rows × free × per-residual cost, including spline
/// reconstruction) allowed before building the Jacobian during numerical differentiation.
const MAX_EVAL_WORK: f64 = 2e9;
/// Most objects listed in one report.
const MAX_OBJECTS: usize = 10_000;
/// Constraint state of an object or a selection.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum DofStatus {
/// No constraints.
Unconstrained,
/// Some freedom left.
Under,
/// No freedom left, no redundant constraints.
Fully,
/// Redundant constraints.
Over,
/// Too large to analyse.
Unknown,
}
impl DofStatus {
pub fn label(self) -> &'static str {
match self {
DofStatus::Unconstrained => "Not constrained",
DofStatus::Under => "Under-constrained",
DofStatus::Fully => "Fully constrained",
DofStatus::Over => "Over-constrained",
DofStatus::Unknown => "Unknown",
}
}
}
/// Degrees of freedom of one object.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectDof {
pub handle: String,
#[serde(rename = "type")]
pub kind: &'static str,
/// Parameters of the object: its degrees of freedom without constraints.
pub params: usize,
/// Remaining degrees of freedom (`None` when the system is too large to analyse).
pub dof: Option<usize>,
pub status: DofStatus,
}
/// Degrees of freedom of the drawing's constrained geometry, or of a selection.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DofReport {
/// Remaining degrees of freedom: the constraint components touching the analysed objects,
/// plus unconstrained objects' own parameters (`None` when too large to analyse).
pub dof: Option<usize>,
pub status: DofStatus,
/// Equations that duplicate others.
pub redundant: usize,
/// Constraints taking part.
pub constraints: usize,
pub objects: Vec<ObjectDof>,
pub message: String,
}
struct CompDof {
dof: Option<usize>,
redundant: usize,
/// Per slot (model order).
objects: Vec<Option<usize>>,
}
/// Compute component and object freedom only when rank and residual-evaluation work fit their budgets.
/// Return unknown freedom before building the Jacobian when either work limit is exceeded.
fn analyse(comp: &Comp) -> CompDof {
let free = comp.free(None);
let rows = comp.rows(None);
let nf = free.len();
let unknown = CompDof { dof: None, redundant: 0, objects: vec![None; comp.model.slots.len()] };
if rows > lm::MAX_ROWS || (rows as f64) * (nf as f64) * (rows.min(nf) as f64) > MAX_RANK_WORK {
return unknown;
}
// Numerical differentiation evaluates every residual about `rows × free` times, and each
// spline-end residual reconstructs its spline through a dense solve. Account for that
// reconstruction cost before building the Jacobian so a component with few equations but large
// splines cannot pass the rank-work check yet still require billions of operations (row 43).
let eval_work = (rows as f64) * (nf as f64) * (1.0 + comp.built.iter().map(|b| b.spline_reconstruct_cost(&comp.model)).sum::<f64>());
if eval_work > MAX_EVAL_WORK {
return unknown;
}
let f = |x: &[f64], out: &mut Vec<f64>| comp.eval(x, out, None);
let jac = lm::jacobian(&f, &comp.model.x0, &free, rows);
if nf > MAX_NULL_COLS {
let rank = lm::rank_qr(&jac, rows, nf);
return CompDof { dof: Some(nf - rank.min(nf)), redundant: rows.saturating_sub(rank), objects: vec![None; comp.model.slots.len()] };
}
let (rank, basis) = lm::null_space(&jac, rows, nf);
let objects = comp
.model
.slots
.iter()
.map(|s| {
let cols: Vec<usize> = free.iter().enumerate().filter(|(_, j)| (s.off..s.off + s.len).contains(*j)).map(|(k, _)| k).collect();
if cols.is_empty() || basis.is_empty() {
return Some(0);
}
// Null vectors restricted to the object's columns; their rank is its freedom.
let restricted: Vec<Vec<f64>> = basis.iter().map(|v| cols.iter().map(|&k| v.get(k).copied().unwrap_or(0.0)).collect()).collect();
Some(lm::qr(restricted, 0.0, 1e-6).0)
})
.collect();
CompDof { dof: Some(nf - rank.min(nf)), redundant: rows.saturating_sub(rank), objects }
}
fn plural(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
/// Degrees of freedom of the constrained geometry (`handles` empty), or of the given objects
/// (constrained or not) and the constraint components they belong to.
pub fn dof(d: &Drawing, handles: &[Handle]) -> Result<DofReport, SolveError> {
let cons: Vec<&Constraint> = d.constraints.iter().take(MAX_CONSTRAINTS).collect();
let mut members_left = crate::model::MAX_RIGID_WORK;
let (comps, _) = build_budgeted(d, &cons, &SolveOptions::default(), &mut members_left)?;
let want = |h: Handle| handles.is_empty() || handles.contains(&h);
let mut objects = Vec::new();
let mut seen = HashSet::new();
let mut total = Some(0usize);
let mut redundant = 0;
let mut constraints = 0;
let mut any_constrained = false;
for comp in &comps {
if !comp.model.slots.iter().any(|s| want(s.handle)) {
continue;
}
any_constrained = true;
let a = analyse(comp);
constraints += comp.built.len();
redundant += a.redundant;
total = match (total, a.dof) {
(Some(t), Some(v)) => Some(t.saturating_add(v)),
_ => None,
};
for (s, od) in comp.model.slots.iter().zip(&a.objects) {
if !want(s.handle) || !seen.insert(s.handle) || objects.len() >= MAX_OBJECTS {
continue;
}
let status = match od {
_ if a.redundant > 0 => DofStatus::Over,
Some(0) => DofStatus::Fully,
Some(_) => DofStatus::Under,
None => DofStatus::Unknown,
};
let kind = d.entity(s.handle).map_or("", |e| e.kind.type_name());
objects.push(ObjectDof { handle: s.handle.hex(), kind, params: s.len, dof: *od, status });
}
}
let mut free_objects = false;
for &h in handles.iter().take(MAX_OBJECTS) {
if seen.contains(&h) {
continue;
}
let m = Model::build_budgeted(d, &[h], &mut members_left);
let Some(s) = m.slots.first() else { continue };
seen.insert(h);
free_objects = true;
total = total.map(|t| t.saturating_add(s.len));
let kind = d.entity(h).map_or("", |e| e.kind.type_name());
objects.push(ObjectDof { handle: h.hex(), kind, params: s.len, dof: Some(s.len), status: DofStatus::Unconstrained });
}
let status = if redundant > 0 {
DofStatus::Over
} else if !any_constrained {
DofStatus::Unconstrained
} else {
match total {
Some(0) => DofStatus::Fully,
Some(_) => DofStatus::Under,
None => DofStatus::Unknown,
}
};
let message = match (status, total) {
(DofStatus::Unconstrained, _) if !free_objects => "No constraints".to_string(),
(DofStatus::Over, _) => format!("Over-constrained: {}", plural(redundant, "redundant equation", "redundant equations")),
(DofStatus::Fully, _) => "Fully constrained".to_string(),
(_, Some(n)) => format!("{} remaining", plural(n, "degree of freedom", "degrees of freedom")),
(_, None) => "Too large to analyse".to_string(),
};
Ok(DofReport { dof: total, status, redundant, constraints, objects, message })
}
#[cfg(test)]
mod budget_tests {
use super::*;
use crate::residual::{Built, Form};
use cadcraft_doc::{Common, ConstraintKind, EntityKind, GeomRef, Space};
use cadcraft_geom::{Spline, Vec2};
/// An expensive fit-spline endpoint residual produces unknown freedom before numerical differentiation.
#[test]
fn endpoint_analysis_rejects_cubic_fit_work_before_differentiation() {
let mut d = Drawing::default();
let pts: Vec<_> = (0..500).map(|i| Vec2::new(i as f64, (i % 3) as f64)).collect();
let mut spline = Spline::from_control(pts.clone(), 3);
spline.fit = pts;
let h = d.add(&Space::Model, Common::default(), EntityKind::Spline(spline)).unwrap();
let model = Model::build(&d, &[h]);
let endpoint = Built {
id: 1,
kind: ConstraintKind::Tangent,
refs: vec![GeomRef::whole(h)],
form: Form::EndOn { spline: 0, at_end: false },
target: 0.0,
sign: 1.0,
rows: 2,
aux_init: Vec::new(),
aux: 0,
};
let comp = Comp { model, built: vec![endpoint], weights: vec![1.0; 2], tol: 1e-9 };
assert!(analyse(&comp).dof.is_none());
}
}
+44
View File
@@ -185,6 +185,43 @@ pub fn names(e: &Expr, out: &mut Vec<String>) {
}
}
/// `text` with every whole-name use of `old` replaced by `new`; numbers (`1e3`), other names
/// (`d10` for `d1`) and spacing are left as written.
pub fn rename(text: &str, old: &str, new: &str) -> String {
let b = text.as_bytes();
let mut out = String::with_capacity(text.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
let start = i;
if c.is_ascii_digit() || c == b'.' {
while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'.') {
i += 1;
}
if b.get(i).is_some_and(|c| *c == b'e' || *c == b'E') {
let mut j = i + 1;
if b.get(j).is_some_and(|c| *c == b'+' || *c == b'-') {
j += 1;
}
if b.get(j).is_some_and(u8::is_ascii_digit) {
i = j;
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
}
} else if c.is_ascii_alphabetic() || c == b'_' {
while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_') {
i += 1;
}
} else {
i += text.get(i..).and_then(|r| r.chars().next()).map_or(1, char::len_utf8);
}
let token = text.get(start..i).unwrap_or_default();
out.push_str(if token == old { new } else { token });
}
out
}
/// Evaluate with a variable lookup.
pub fn eval_with(e: &Expr, lookup: &mut dyn FnMut(&str) -> Result<f64, ExprError>) -> Result<f64, ExprError> {
let v = match e {
@@ -314,6 +351,13 @@ mod tests {
assert!(chain.value("p0").is_err());
}
#[test]
fn rename_replaces_whole_names_only() {
assert_eq!(rename("d1+d10*d1 / (d1_x+2e1)", "d1", "w"), "w+d10*w / (d1_x+2e1)");
assert_eq!(rename("1e2+e", "e", "x"), "1e2+x");
assert_eq!(rename("é+a", "a", "b"), "é+b");
}
#[test]
fn names_valid() {
assert!(valid_name("d1") && valid_name("_w") && !valid_name("1d") && !valid_name("a-b") && !valid_name("") && !valid_name("pi"));
+224 -30
View File
@@ -1,6 +1,7 @@
//! CADCraft parametric solver.
//!
//! Maps constrained lines, arcs, circles, points and polyline vertices to a parameter vector
//! Maps constrained lines, arcs, circles, points, polyline vertices, ellipses, splines and block
//! references to a parameter vector
//! ([`model`]), turns each [`Constraint`] into residual equations ([`residual`]), and drives the
//! residuals to zero with a weighted minimum-norm damped Gauss–Newton solver ([`lm`]), so
//! geometry moves as little as possible and geometry the caller wants kept (just edited, or picked
@@ -9,7 +10,11 @@
//! Inconsistent systems are not "solved" by moving things wildly: the solve fails, nothing is
//! written back, and the error names the conflicting constraints (each one whose removal makes
//! the rest solvable). New constraints that add no independent equation are reported as
//! redundant (over-constraining), as AutoCAD does.
//! redundant (over-constraining), as AutoCAD does, naming the constraints they duplicate.
//!
//! [`dof()`] reports the remaining degrees of freedom: the rank of the constraint Jacobian per
//! connected component (Householder QR with column pivoting), and per object the dimension of
//! the null-space motion its own parameters still have.
//!
//! Own implementation (clean-room): the KittyCAD `ezpz` crate (MIT) was evaluated; it pulls in
//! the `faer` linear-algebra stack and models KCL's geometry, so a small solver tailored to the
@@ -18,6 +23,8 @@
#![forbid(unsafe_code)]
pub mod auto;
mod curves;
mod dof;
pub mod expr;
mod lm;
mod model;
@@ -29,9 +36,10 @@ use cadcraft_doc::{Constraint, ConstraintKind, Drawing, GeomRef, Handle};
use cadcraft_geom::Vec2;
use serde::Serialize;
pub use auto::{InferOptions, autoconstrain, infer};
pub use auto::{INFER_TYPES, InferOptions, autoconstrain, infer, infer_placed};
pub use dof::{DofReport, DofStatus, ObjectDof, dof};
pub use expr::{Env, ExprError};
pub use model::supported;
pub use model::{ref_points, rigid_points, supported};
use model::Model;
use residual::{Built, Form};
@@ -168,10 +176,34 @@ pub fn next_id(d: &Drawing) -> u32 {
// ---------------- systems ----------------
/// Interpret a constraint against the model's current parameters, appending its auxiliary
/// unknowns (contact parameters) to the model, settled with the geometry held still.
pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> {
let x = model.x0.clone();
let mut b = Built::new(c, model, &x, target)?;
if b.aux_init.is_empty() {
return Ok(b);
}
if model.x0.len() + b.aux_init.len() > model::MAX_PARAMS + 1000 {
return Err("constraint system too large".into());
}
b.aux = model.x0.len();
model.x0.extend(b.aux_init.iter().copied());
let free: Vec<usize> = (b.aux..model.x0.len()).collect();
let weights = vec![1.0; model.x0.len()];
let o = {
let m: &Model = model;
let f = |x: &[f64], out: &mut Vec<f64>| b.eval(m, x, out);
lm::solve(&f, &m.x0, &free, &weights, 1e-14, 60)
};
model.x0 = o.x;
Ok(b)
}
/// One connected component of the constraint graph.
struct Comp {
model: Model,
built: Vec<Built>,
pub(crate) struct Comp {
pub(crate) model: Model,
pub(crate) built: Vec<Built>,
weights: Vec<f64>,
tol: f64,
}
@@ -193,17 +225,17 @@ impl Comp {
}
locked
}
fn free(&self, skip: Option<usize>) -> Vec<usize> {
pub(crate) fn free(&self, skip: Option<usize>) -> Vec<usize> {
self.locks(skip).iter().enumerate().filter(|(_, l)| !**l).map(|(i, _)| i).collect()
}
fn eval(&self, x: &[f64], out: &mut Vec<f64>, skip: Option<usize>) {
pub(crate) fn eval(&self, x: &[f64], out: &mut Vec<f64>, skip: Option<usize>) {
for (i, b) in self.built.iter().enumerate() {
if Some(i) != skip {
b.eval(&self.model, x, out);
}
}
}
fn rows(&self, skip: Option<usize>) -> usize {
pub(crate) fn rows(&self, skip: Option<usize>) -> usize {
self.built.iter().enumerate().filter(|(i, _)| Some(*i) != skip).map(|(_, b)| b.rows).sum()
}
fn run(&self, skip: Option<usize>) -> Result<lm::Outcome, SolveError> {
@@ -291,17 +323,29 @@ fn components<'a>(cons: &[&'a Constraint]) -> Vec<Vec<&'a Constraint>> {
}
/// Build the component systems. Constraints that cannot be interpreted are returned as skipped.
fn build(d: &Drawing, cons: &[&Constraint], opts: &SolveOptions) -> Result<(Vec<Comp>, Vec<(u32, String)>), SolveError> {
pub(crate) fn build(d: &Drawing, cons: &[&Constraint], opts: &SolveOptions) -> Result<(Vec<Comp>, Vec<(u32, String)>), SolveError> {
let mut members_left = model::MAX_RIGID_WORK;
build_budgeted(d, cons, opts, &mut members_left)
}
/// Build constraint components with one caller-owned rigid-member sampling budget shared by every model.
/// Return constraints that cannot be interpreted as skipped entries.
pub(crate) fn build_budgeted(
d: &Drawing,
cons: &[&Constraint],
opts: &SolveOptions,
members_left: &mut usize,
) -> Result<(Vec<Comp>, Vec<(u32, String)>), SolveError> {
let mut e = env(d);
let mut skipped = Vec::new();
let mut comps = Vec::new();
for group in components(cons) {
let handles: Vec<Handle> = group.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let model = Model::build(d, &handles);
let mut model = Model::build_budgeted(d, &handles, members_left);
let mut built = Vec::new();
for c in group {
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c)? } else { 0.0 };
match Built::new(c, &model, &model.x0, target) {
match interpret(c, &mut model, target) {
Ok(b) => built.push(b),
Err(msg) => skipped.push((c.id, msg)),
}
@@ -323,16 +367,32 @@ fn build(d: &Drawing, cons: &[&Constraint], opts: &SolveOptions) -> Result<(Vec<
*slot = w;
}
}
if s.shape == model::Shape::Arc {
// Angles: weight by r² so the endpoints' movement is what is minimised.
let r2 = model.x0.get(s.off + 2).map_or(1.0, |r| (r * r).max(1e-6));
for j in [s.off + 3, s.off + 4] {
if let Some(slot) = weights.get_mut(j) {
*slot *= r2;
// Angles and ratios: weight by size² so the movement of points is what is minimised.
let sq = |j: usize| model.x0.get(j).map_or(1.0, |r| (r * r).max(1e-6));
let scaled: Vec<(usize, f64)> = match s.shape {
model::Shape::Arc => vec![(s.off + 3, sq(s.off + 2)), (s.off + 4, sq(s.off + 2))],
model::Shape::Ellipse { arc } => {
let a2 = (sq(s.off + 2) + sq(s.off + 3)).max(1e-6);
let mut v = vec![(s.off + 4, a2)];
if arc {
v.extend([(s.off + 5, a2), (s.off + 6, a2)]);
}
v
}
model::Shape::Insert { .. } => vec![(s.off + 2, model.rigid_extent2(s.handle).max(1.0))],
_ => Vec::new(),
};
for (j, f) in scaled {
if let Some(slot) = weights.get_mut(j) {
*slot *= f;
}
}
}
// Contact parameters move freely.
let geo = model.slots.iter().map(|s| s.off + s.len).max().unwrap_or(0);
for w in weights.iter_mut().skip(geo) {
*w = 1e-3;
}
let tol = scale_tol(&model.x0);
comps.push(Comp { model, built, weights, tol });
}
@@ -364,13 +424,13 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result<SolveReport, SolveE
pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
let mut e = env(d);
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let model = Model::build(d, &handles);
let mut model = Model::build(d, &handles);
d.constraints
.iter()
.take(MAX_CONSTRAINTS)
.map(|c| {
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
let r = target.and_then(|t| Built::new(c, &model, &model.x0, t).ok()).map(|b| {
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
let mut out = Vec::new();
b.eval(&model, &model.x0, &mut out);
lm::max_abs(&out)
@@ -380,6 +440,46 @@ pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
.collect()
}
/// Put back what each Fix locks where `before` had it, and report whether anything moved.
///
/// A Fix keeps no position of its own: the solver locks the parameters at their current values.
/// Without this, an edit that moves a fixed point (a grip drag) would carry the lock along with
/// it. Only Fixes that already existed in `before`, on objects of the same shape, are restored.
pub fn restore_fixed(d: &mut Drawing, before: &Drawing) -> bool {
let refs: Vec<GeomRef> = d
.constraints
.iter()
.filter(|c| c.kind == ConstraintKind::Fix && before.constraints.contains(c))
.flat_map(|c| c.refs.iter().copied())
.collect();
if refs.is_empty() {
return false;
}
let handles: Vec<Handle> = refs.iter().map(|r| r.handle).collect();
let (now, old) = (Model::build(d, &handles), Model::build(before, &handles));
let mut x = now.x0.clone();
let mut changed = false;
for r in &refs {
let same_shape = matches!((now.slot(r.handle), old.slot(r.handle)), (Some(a), Some(b)) if a.shape == b.shape);
let (Some(i), Some(j)) = (now.lock_indices(r), old.lock_indices(r)) else { continue };
if !same_shape {
continue;
}
for (i, j) in i.into_iter().zip(j) {
if let (Some(slot), Some(&v)) = (x.get_mut(i), old.x0.get(j))
&& *slot != v
{
*slot = v;
changed = true;
}
}
}
if changed {
now.write_back(d, &x);
}
changed
}
/// True when every interpretable constraint holds at the current geometry.
pub fn all_satisfied(d: &Drawing) -> bool {
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
@@ -397,16 +497,16 @@ pub fn validate(d: &Drawing, c: &Constraint) -> Result<(), String> {
_ => {}
}
}
let model = Model::build(d, &handles);
Built::new(c, &model, &model.x0, 1.0).map(|_| ())
let mut model = Model::build(d, &handles);
interpret(c, &mut model, 1.0).map(|_| ())
}
/// The current measured value of a dimensional constraint over `refs` (degrees for angular).
pub fn measure(d: &Drawing, kind: ConstraintKind, refs: &[GeomRef]) -> Result<f64, String> {
let c = Constraint { id: 0, kind, refs: refs.to_vec(), name: String::new(), expr: String::new() };
let handles: Vec<Handle> = refs.iter().map(|r| r.handle).collect();
let model = Model::build(d, &handles);
let b = Built::new(&c, &model, &model.x0, 1.0)?;
let mut model = Model::build(d, &handles);
let b = interpret(&c, &mut model, 1.0)?;
Ok(b.measure(&model, &model.x0))
}
@@ -475,8 +575,7 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result<u3
return Err(SolveError::Conflict { ids });
}
// Redundancy: the new rows must raise the rank.
if let Some(pos) = comp.built.iter().position(|b| b.id == id)
&& let Some(nb) = comp.built.get(pos)
if let Some(nb) = comp.built.iter().find(|b| b.id == id)
&& nb.rows > 0
{
let free = comp.free(None);
@@ -489,11 +588,31 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result<u3
};
let rows_all: usize = ordered.iter().map(|b| b.rows).sum();
let rows_old = rows_all - nb.rows;
let nf = free.len();
let jac = lm::jacobian(&f, &o.x, &free, rows_all);
let r_all = lm::rank(&jac, rows_all, free.len());
let r_old = lm::rank(jac.get(..rows_old * free.len()).unwrap_or_default(), rows_old, free.len());
let r_all = lm::rank_qr(&jac, rows_all, nf);
let r_old = lm::rank_qr(jac.get(..rows_old * nf).unwrap_or_default(), rows_old, nf);
if r_all < r_old + nb.rows {
let mine: Vec<Handle> = nb.refs.iter().map(|r| r.handle).collect();
return Err(SolveError::Redundant { ids: redundant_with(&comp, &ordered, &jac, nf, id) });
}
}
// A Fix that locks parameters adds one equation per parameter it locks.
if let Some(pos) = comp.built.iter().position(|b| b.id == id)
&& comp.built.get(pos).is_some_and(|b| b.form == Form::Lock)
{
let before = comp.free(Some(pos));
let after = comp.free(None);
let locked: Vec<usize> = before.iter().enumerate().filter(|(_, j)| !after.contains(j)).map(|(k, _)| k).collect();
let rows_old = comp.rows(Some(pos));
let nf = before.len();
let f = |x: &[f64], out: &mut Vec<f64>| comp.eval(x, out, Some(pos));
let mut jac = lm::jacobian(&f, &o.x, &before, rows_old);
let r_old = lm::rank_qr(&jac, rows_old, nf);
for k in &locked {
jac.extend((0..nf).map(|c| if c == *k { 1.0 } else { 0.0 }));
}
if locked.is_empty() || lm::rank_qr(&jac, rows_old + locked.len(), nf) < r_old + locked.len() {
let mine: Vec<Handle> = comp.built.get(pos).map(|b| b.refs.iter().map(|r| r.handle).collect()).unwrap_or_default();
let ids = comp.built.iter().filter(|b| b.id != id && b.refs.iter().any(|r| mine.contains(&r.handle))).map(|b| b.id).collect();
return Err(SolveError::Redundant { ids });
}
@@ -503,6 +622,53 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result<u3
Ok(id)
}
/// The existing constraints a redundant new one (last in `ordered`) duplicates: each one whose
/// removal would let the new one add independent equations. Falls back to the constraints on
/// the same objects.
fn redundant_with(comp: &Comp, ordered: &[&Built], jac: &[f64], nf: usize, id: u32) -> Vec<u32> {
let mut starts = Vec::with_capacity(ordered.len());
let mut at = 0;
for b in ordered {
starts.push(at);
at += b.rows;
}
let pick = |skip: usize, with_new: bool| -> (Vec<f64>, usize) {
let mut m = Vec::new();
let mut rows = 0;
let last = ordered.len().saturating_sub(1);
for (i, b) in ordered.iter().enumerate() {
if i == skip || (i == last && !with_new) {
continue;
}
let s = starts.get(i).copied().unwrap_or(0);
if let Some(part) = jac.get(s * nf..(s + b.rows) * nf) {
m.extend_from_slice(part);
rows += b.rows;
}
}
(m, rows)
};
let new_rows = ordered.last().map_or(0, |b| b.rows);
let mut ids = Vec::new();
if ordered.len() <= MAX_CONFLICT_PROBES + 1 {
for (i, b) in ordered.iter().enumerate().take(ordered.len().saturating_sub(1)) {
if b.rows == 0 {
continue;
}
let (old, ro) = pick(i, false);
let (all, ra) = pick(i, true);
if lm::rank_qr(&all, ra, nf) == lm::rank_qr(&old, ro, nf) + new_rows {
ids.push(b.id);
}
}
}
if ids.is_empty() {
let mine: Vec<Handle> = ordered.last().map(|b| b.refs.iter().map(|r| r.handle).collect()).unwrap_or_default();
ids = comp.built.iter().filter(|b| b.id != id && b.refs.iter().any(|r| mine.contains(&r.handle))).map(|b| b.id).collect();
}
ids
}
/// Format a value for an expression (up to 6 decimals, trailing zeros trimmed).
pub fn format_value(v: f64) -> String {
let s = format!("{v:.6}");
@@ -545,6 +711,33 @@ pub fn set_parameter(d: &mut Drawing, name: &str, expr_text: &str, opts: &SolveO
Ok(report)
}
/// Rename a parameter (dimensional constraint name or user parameter) and every expression that
/// uses it. Geometry doesn't change. On error the drawing is unchanged.
pub fn rename_parameter(d: &mut Drawing, old: &str, new: &str) -> Result<(), SolveError> {
if !name_in_use(d, old) {
return Err(SolveError::Other(format!("no parameter `{old}`")));
}
if !expr::valid_name(new) {
return Err(SolveError::Other(format!("invalid parameter name `{new}`")));
}
if new != old && name_in_use(d, new) {
return Err(SolveError::Other(format!("`{new}` is already in use")));
}
for c in d.constraints.iter_mut().filter(|c| c.kind.is_dimensional()) {
if c.name == old {
c.name = new.to_string();
}
c.expr = expr::rename(&c.expr, old, new);
}
for p in &mut d.parametric.parameters {
if p.name == old {
p.name = new.to_string();
}
p.expr = expr::rename(&p.expr, old, new);
}
Ok(())
}
/// Where to draw a constraint's glyphs (one anchor per reference).
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -580,6 +773,7 @@ pub fn glyphs(d: &Drawing) -> Vec<Glyph> {
.point(x, r)
.or_else(|| model.line(x, r).map(|(a, b)| a.mid(b)))
.or_else(|| model.circle(x, r).map(|(c, rad)| c + Vec2::new(0.0, rad)))
.or_else(|| model.anchor(x, r))
})
.collect();
Glyph {
+132 -43
View File
@@ -102,50 +102,124 @@ fn solve_dense(mut a: Vec<f64>, mut b: Vec<f64>, n: usize) -> Option<Vec<f64>> {
y.iter().all(|v| v.is_finite()).then_some(y)
}
/// Numerical rank of a row-major `rows × cols` matrix (rows normalised first).
pub(crate) fn rank(m: &[f64], rows: usize, cols: usize) -> usize {
let mut a: Vec<Vec<f64>> = (0..rows)
.map(|i| {
let r: Vec<f64> = m.get(i * cols..(i + 1) * cols).map(<[f64]>::to_vec).unwrap_or_default();
let n = norm2(&r).sqrt();
if n > 1e-12 { r.iter().map(|v| v / n).collect() } else { vec![0.0; cols] }
})
.collect();
let mut rank = 0;
let mut used = vec![false; rows];
/// Householder QR with column pivoting of the columns `cols` (each of the same length). Stops
/// when the largest remaining column norm drops to `rel` times the first pivot's (or below
/// `abs`). Returns the numerical rank and the Householder vectors (full length, zero above the
/// diagonal; each reflector is `I − 2vvᵀ/(vᵀv)`).
pub(crate) fn qr(mut cols: Vec<Vec<f64>>, rel: f64, abs: f64) -> (usize, Vec<Vec<f64>>) {
let m = cols.first().map_or(0, Vec::len);
let n = cols.len();
let mut refl = Vec::new();
let mut first = None;
for k in 0..m.min(n) {
// Pivot: the column with the largest remaining norm.
let mut best = (k, -1.0f64);
for (j, c) in cols.iter().enumerate().skip(k) {
let v = c.get(k..).map_or(0.0, norm2);
if v.is_finite() && v > best.1 {
best = (j, v);
}
}
let norm = best.1.max(0.0).sqrt();
let lim = first.map_or(abs, |f: f64| (f * rel).max(abs));
if crate::curves::not_above(norm, lim) {
break;
}
first.get_or_insert(norm);
cols.swap(k, best.0);
let Some(col) = cols.get(k) else { break };
let mut v = vec![0.0; m];
for i in k..m {
if let (Some(d), Some(s)) = (v.get_mut(i), col.get(i)) {
*d = *s;
}
}
let x0 = v.get(k).copied().unwrap_or(0.0);
let alpha = if x0 >= 0.0 { -norm } else { norm };
if let Some(d) = v.get_mut(k) {
*d -= alpha;
}
let vv = norm2(&v);
if crate::curves::not_above(vv, 0.0) {
break;
}
for c in cols.iter_mut().skip(k) {
reflect(&v, vv, c);
}
refl.push(v);
}
(refl.len(), refl)
}
fn reflect(v: &[f64], vv: f64, c: &mut [f64]) {
let d: f64 = v.iter().zip(c.iter()).map(|(a, b)| a * b).sum();
let f = 2.0 * d / vv;
if f != 0.0 {
for (ci, vi) in c.iter_mut().zip(v) {
*ci -= f * vi;
}
}
}
/// Rows and columns scaled to unit norm (zero ones left alone), as columns of the transpose:
/// `out[i]` is row `i` of the row-major `rows × cols` matrix `m`.
fn balanced_rows(m: &[f64], rows: usize, cols: usize) -> Vec<Vec<f64>> {
let mut r: Vec<Vec<f64>> = (0..rows).map(|i| m.get(i * cols..(i + 1) * cols).map(<[f64]>::to_vec).unwrap_or_else(|| vec![0.0; cols])).collect();
for row in &mut r {
let n = norm2(row).sqrt();
let f = if n > 1e-12 && n.is_finite() { 1.0 / n } else { 0.0 };
row.iter_mut().for_each(|v| *v *= f);
}
// Columns: unit norm, except numerical noise (an exactly zero derivative evaluated by
// differences), which scaling would turn into a spurious independent direction.
for c in 0..cols {
let mut piv = None;
let mut best = 1e-7;
for (i, row) in a.iter().enumerate() {
if used.get(i).copied().unwrap_or(true) {
continue;
}
let v = row.get(c).copied().unwrap_or(0.0).abs();
if v > best {
best = v;
piv = Some(i);
}
}
let Some(p) = piv else { continue };
if let Some(u) = used.get_mut(p) {
*u = true;
}
rank += 1;
let prow = a.get(p).cloned().unwrap_or_default();
let pv = prow.get(c).copied().unwrap_or(1.0);
for (i, row) in a.iter_mut().enumerate() {
if i == p || used.get(i).copied().unwrap_or(true) {
continue;
}
let f = row.get(c).copied().unwrap_or(0.0) / pv;
if f != 0.0 {
for (v, pr) in row.iter_mut().zip(&prow) {
*v -= f * pr;
}
let n = r.iter().map(|row| row.get(c).map_or(0.0, |v| v * v)).sum::<f64>().sqrt();
let f = if n > COL_NOISE && n.is_finite() { 1.0 / n } else { 0.0 };
for row in &mut r {
if let Some(v) = row.get_mut(c) {
*v *= f;
}
}
}
rank
r
}
/// Column norm (after row balancing) below which a column is difference noise.
const COL_NOISE: f64 = 1e-6;
/// Relative threshold below which a pivot counts as zero (the Jacobian is numerical).
const RANK_TOL: f64 = 1e-7;
/// Numerical rank of a row-major `rows × cols` Jacobian (rows and columns balanced first,
/// Householder QR with column pivoting).
pub(crate) fn rank_qr(m: &[f64], rows: usize, cols: usize) -> usize {
if rows == 0 || cols == 0 {
return 0;
}
// QR of the transpose: its columns are the Jacobian's rows.
qr(balanced_rows(m, rows, cols), RANK_TOL, 1e-12).0
}
/// Rank and an orthonormal basis of the null space (each vector of length `cols`) of a
/// row-major `rows × cols` Jacobian, in balanced column coordinates (a diagonal scaling, so
/// which parameters a null vector moves is preserved).
pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec<Vec<f64>>) {
let (rank, refl) = if rows == 0 { (0, Vec::new()) } else { qr(balanced_rows(m, rows, cols), RANK_TOL, 1e-12) };
let mut basis = Vec::with_capacity(cols.saturating_sub(rank));
for j in rank..cols {
let mut e = vec![0.0; cols];
if let Some(v) = e.get_mut(j) {
*v = 1.0;
}
// Q e_j with Q = H_0 H_1 … H_{r−1}.
for v in refl.iter().rev() {
let vv = norm2(v);
if vv > 0.0 {
reflect(v, vv, &mut e);
}
}
basis.push(e);
}
(rank, basis)
}
/// Run the solver from `x0`. Only `free` parameters change.
@@ -241,9 +315,24 @@ mod tests {
let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap();
assert!((y[0] - 0.8).abs() < 1e-12 && (y[1] - 1.4).abs() < 1e-12);
assert!(solve_dense(vec![1.0, 2.0, 2.0, 4.0], vec![1.0, 1.0], 2).is_none());
assert_eq!(rank(&[1.0, 0.0, 0.0, 1.0, 1.0, 1.0], 3, 2), 2);
assert_eq!(rank(&[1.0, 2.0, 2.0, 4.0], 2, 2), 1);
assert_eq!(rank(&[0.0; 4], 2, 2), 0);
assert_eq!(rank_qr(&[1.0, 0.0, 0.0, 1.0, 1.0, 1.0], 3, 2), 2);
assert_eq!(rank_qr(&[1.0, 2.0, 2.0, 4.0], 2, 2), 1);
assert_eq!(rank_qr(&[0.0; 4], 2, 2), 0);
assert_eq!(rank_qr(&[1e-9, 0.0, 0.0, 1e6], 2, 2), 2, "balanced: scale does not hide rank");
}
#[test]
fn null_space_spans_free_motion() {
// x0 + x1 = c fixes one combination; x2 is untouched.
let (r, n) = null_space(&[1.0, 1.0, 0.0], 1, 3);
assert_eq!((r, n.len()), (1, 2));
for v in &n {
assert!((v[0] + v[1]).abs() < 1e-12);
}
// x2's own motion survives in the null space; x0 alone does not.
assert!(n.iter().any(|v| v[2].abs() > 0.5));
let (r, n) = null_space(&[], 0, 2);
assert_eq!((r, n.len()), (0, 2));
}
#[test]
+420 -6
View File
@@ -5,22 +5,59 @@
//! - Arc: `cx cy r start end` (angles in radians)
//! - LwPolyline: `x0 y0 x1 y1 …` (bulges are kept; segments are treated as straight lines)
//! - Point: `x y`
//! - Ellipse: `cx cy mx my ratio` plus `start end` (parameters, radians) for an elliptical arc;
//! `(mx, my)` is the major axis vector
//! - Spline: its defining points `x0 y0 x1 y1 …`: the fit points of an interpolating spline
//! (rebuilt through them on write-back), else the control points
//! - Block reference: `x y rotation`; the block's characteristic points ride along rigidly
//!
//! Constraints may append auxiliary unknowns after the entity parameters (contact parameters of
//! a tangency between curves); they are never written back.
use std::collections::HashMap;
use cadcraft_doc::{Drawing, EntityKind, GeomRef, Handle, Sub};
use cadcraft_geom::{Vec2, ccw_sweep};
use cadcraft_doc::{Drawing, EntityKind, GeomRef, Handle, Insert, Sub};
use cadcraft_geom::{Spline as GSpline, Vec2, ccw_sweep};
use crate::curves::{Ell, Frame, clamped, spline_end};
/// Most parameters one solve may have.
pub const MAX_PARAMS: usize = 4000;
/// Most defining points of a spline taking part in constraints.
pub const MAX_SPLINE_POINTS: usize = 500;
/// Most characteristic points of a block reference used as rigid constraint points.
pub const MAX_RIGID_POINTS: usize = 256;
/// Block members examined when sampling rigid points, counting those that contribute none, so a
/// block padded with point-less entities cannot make sampling (repeated per Insert) unbounded.
const MAX_RIGID_MEMBERS: usize = 100_000;
/// Shared across every model built for one analysis request.
pub(crate) const MAX_RIGID_WORK: usize = 1_000_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Shape {
Line,
Circle,
Arc,
Poly { n: usize, closed: bool },
Poly {
n: usize,
closed: bool,
},
Point,
/// `arc`: elliptical arc (has start/end parameters).
Ellipse {
arc: bool,
},
/// `n` defining points; `fit`: they are fit points; `ends`: the curve has a start and an end
/// (open and clamped) that are its first and last defining points.
Spline {
n: usize,
fit: bool,
ends: bool,
},
/// Block reference with `n` rigid points.
Insert {
n: usize,
},
}
#[derive(Clone, Copy, Debug)]
@@ -36,20 +73,124 @@ pub(crate) struct Model {
pub slots: Vec<Slot>,
pub x0: Vec<f64>,
index: HashMap<Handle, usize>,
/// Spline templates (degree, knots, weights, fit options) the defining points plug into.
splines: HashMap<Handle, GSpline>,
/// Block reference rigid points relative to the insertion point at rotation 0.
rigid: HashMap<Handle, Vec<Vec2>>,
}
impl Model {
/// Work for a spline that an endpoint residual actually reconstructs. Fit interpolation
/// uses dense Gaussian elimination (cubic); control splines clone and evaluate their template.
pub(crate) fn spline_reconstruct_cost(&self, handle: Handle) -> f64 {
let Some(s) = self.splines.get(&handle) else { return 0.0 };
let n = s.fit.len() as f64;
if fit_mode(s) {
n * n * n
} else {
let n = s.control.len() as f64;
n * n
}
}
}
/// Can this entity take part in constraints?
pub fn supported(kind: &EntityKind) -> bool {
matches!(kind, EntityKind::Line(_) | EntityKind::Circle(_) | EntityKind::Arc(_) | EntityKind::LwPolyline(_) | EntityKind::Point(_))
matches!(
kind,
EntityKind::Line(_)
| EntityKind::Circle(_)
| EntityKind::Arc(_)
| EntityKind::LwPolyline(_)
| EntityKind::Point(_)
| EntityKind::Ellipse(_)
| EntityKind::Spline(_)
| EntityKind::Insert(_)
)
}
/// World positions of a block reference's rigid points: the characteristic points (end points,
/// centres, vertices, nested insertion points) of the block's own objects, at most
/// [`MAX_RIGID_POINTS`]. Nested blocks are not entered.
pub fn rigid_points(d: &Drawing, ins: &Insert) -> Vec<Vec2> {
let mut members_left = MAX_RIGID_MEMBERS;
rigid_points_budgeted(d, ins, &mut members_left)
}
/// Sample finite block points within per-insert and caller-shared member limits.
/// Members that contribute no points still consume traversal work; nested blocks are not entered.
fn rigid_points_budgeted(d: &Drawing, ins: &Insert, members_left: &mut usize) -> Vec<Vec2> {
let Some(block) = d.block(&ins.block) else { return Vec::new() };
let m = ins.transform(block.base.xy());
let mut out = Vec::new();
// Bound the members examined, not only the points collected: entities that contribute no
// points (Text, Ray, …) still cost traversal, so a block full of them — scanned again for
// every Insert — would otherwise be unbounded (CWE-407).
let mut examined = 0usize;
for e in block.entities.iter() {
examined += 1;
if out.len() >= MAX_RIGID_POINTS || examined > MAX_RIGID_MEMBERS || *members_left == 0 {
break;
}
*members_left -= 1;
let pts: Vec<Vec2> = match &e.kind {
EntityKind::Line(l) => vec![l.a.xy(), l.b.xy()],
EntityKind::Arc(a) => {
let g = cadcraft_geom::Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![g.start_point(), g.end_point(), g.center]
}
EntityKind::Circle(c) => vec![c.center.xy()],
EntityKind::Point(p) => vec![p.p.xy()],
EntityKind::Ellipse(el) => vec![el.center.xy()],
EntityKind::Insert(i) => vec![i.insert.xy()],
EntityKind::LwPolyline(p) => p.vertices.iter().take(MAX_RIGID_POINTS).map(|v| v.p).collect(),
_ => Vec::new(),
};
out.extend(pts.into_iter().map(|p| m.apply(p)).filter(|p| p.is_finite()));
}
out.truncate(MAX_RIGID_POINTS);
out
}
/// Constraint points of an object as the solver sees them (`Sub`, position): end points,
/// centres, axis ends, defining points, rigid points. Points at the same place are listed once.
pub fn ref_points(d: &Drawing, h: Handle) -> Vec<(Sub, Vec2)> {
let m = Model::build(d, &[h]);
let Some(s) = m.slots.first() else { return Vec::new() };
let n = match s.shape {
Shape::Ellipse { .. } => 4,
Shape::Spline { n, .. } | Shape::Insert { n } | Shape::Poly { n, .. } => n,
_ => 0,
};
let mut out: Vec<(Sub, Vec2)> = Vec::new();
for sub in [Sub::Whole, Sub::Center, Sub::Start, Sub::End, Sub::Mid].into_iter().chain((0..n).map(|i| Sub::Vertex(i as u32))) {
if let Some(p) = m.point(&m.x0, &GeomRef::new(h, sub))
&& !out.iter().any(|(_, q)| *q == p)
{
out.push((sub, p));
}
}
out
}
fn p2(x: &[f64], i: usize) -> Option<Vec2> {
Some(Vec2::new(*x.get(i)?, *x.get(i + 1)?))
}
/// Does a spline interpolate its fit points (so they can be its parameters)?
fn fit_mode(s: &GSpline) -> bool {
s.fit.len() >= 2 && s.fit_opts.tolerance == 0.0
}
impl Model {
/// Build a model for the given entities. Unsupported or missing entities are skipped.
pub fn build(d: &Drawing, handles: &[Handle]) -> Model {
let mut members_left = MAX_RIGID_WORK;
Self::build_budgeted(d, handles, &mut members_left)
}
/// Build solver parameters for supported entities while sharing rigid-member sampling work with other models.
pub(crate) fn build_budgeted(d: &Drawing, handles: &[Handle], members_left: &mut usize) -> Model {
let mut m = Model::default();
for &h in handles {
if m.index.contains_key(&h) {
@@ -83,6 +224,43 @@ impl Model {
m.x0.extend([p.p.x, p.p.y]);
Shape::Point
}
EntityKind::Ellipse(el) => {
let ell = cadcraft_geom::Ellipse { center: el.center.xy(), major: el.major.xy(), ratio: el.ratio, start: el.start, end: el.end };
let arc = !ell.is_full();
m.x0.extend([el.center.x, el.center.y, el.major.x, el.major.y, el.ratio]);
if arc {
m.x0.extend([el.start, el.end]);
}
Shape::Ellipse { arc }
}
EntityKind::Spline(sp) => {
let fit = fit_mode(sp);
let pts = if fit { &sp.fit } else { &sp.control };
let n = pts.len();
if !(2..=MAX_SPLINE_POINTS).contains(&n) || off + n * 2 > MAX_PARAMS || (!fit && !sp.is_valid()) {
continue;
}
for p in pts {
m.x0.extend([p.x, p.y]);
}
// Fit points interpolate exactly, so the curve's ends are the first and last
// fit point; a control polygon's ends are its first and last points when the
// knots are clamped.
let ends = !sp.closed && (fit || (clamped(sp, false) && clamped(sp, true)));
// Missing weights default to 1 in eval; only excess weights are unused.
let mut kept = sp.clone();
kept.weights.truncate(kept.control.len());
m.splines.insert(h, kept);
Shape::Spline { n, fit, ends }
}
EntityKind::Insert(ins) => {
let base = Vec2::new(ins.insert.x, ins.insert.y);
let pts: Vec<Vec2> = rigid_points_budgeted(d, ins, members_left).into_iter().map(|p| (p - base).rotate(-ins.rotation)).collect();
m.x0.extend([ins.insert.x, ins.insert.y, ins.rotation]);
let n = pts.len();
m.rigid.insert(h, pts);
Shape::Insert { n }
}
_ => continue,
};
if m.x0.len() > MAX_PARAMS || m.x0.get(off..).unwrap_or(&[]).iter().any(|v| !v.is_finite()) {
@@ -128,6 +306,129 @@ impl Model {
(Shape::Poly { n, .. }, Sub::End) => p2(x, o + 2 * n.checked_sub(1)?),
(Shape::Poly { .. }, Sub::Mid) => None,
(Shape::Point, Sub::Whole | Sub::Start | Sub::Center) => p2(x, o),
(Shape::Ellipse { .. }, Sub::Center) => p2(x, o),
(Shape::Ellipse { .. }, Sub::Vertex(i)) => {
// Axis end points: +major, +minor, −major, −minor.
let e = self.ell_at(x, o, false)?;
Some(match i {
0 => e.c + e.mj,
1 => e.c + e.minor(),
2 => e.c - e.mj,
3 => e.c - e.minor(),
_ => return None,
})
}
(Shape::Ellipse { arc: true }, Sub::Start | Sub::End | Sub::Mid) => {
let e = self.ell_at(x, o, true)?;
Some(e.at(match r.sub {
Sub::Start => e.t0,
Sub::End => e.t1,
_ => e.t0 + ccw_sweep(e.t0, e.t1) / 2.0,
}))
}
(Shape::Spline { n, .. }, Sub::Vertex(i)) => {
let i = i as usize;
if i < n { p2(x, o + 2 * i) } else { None }
}
(Shape::Spline { ends: true, .. }, Sub::Start) => p2(x, o),
(Shape::Spline { n, ends: true, .. }, Sub::End) => p2(x, o + 2 * n.checked_sub(1)?),
(Shape::Insert { .. }, Sub::Whole | Sub::Start | Sub::Center) => p2(x, o),
(Shape::Insert { n }, Sub::Vertex(i)) => {
let i = i as usize;
if i >= n {
return None;
}
let q = *self.rigid.get(&s.handle)?.get(i)?;
Some(p2(x, o)? + q.rotate(*x.get(o + 2)?))
}
_ => None,
}
}
fn ell_at(&self, x: &[f64], o: usize, arc: bool) -> Option<Ell> {
let (t0, t1) = if arc { (*x.get(o + 5)?, *x.get(o + 6)?) } else { (0.0, std::f64::consts::TAU) };
Some(Ell { c: p2(x, o)?, mj: p2(x, o + 2)?, ratio: *x.get(o + 4)?, t0, t1, arc })
}
/// An ellipse-like reference (ellipse or elliptical arc).
pub fn ellipse(&self, x: &[f64], r: &GeomRef) -> Option<Ell> {
let s = self.slot(r.handle)?;
match (s.shape, r.sub) {
(Shape::Ellipse { arc }, Sub::Whole) => self.ell_at(x, s.off, arc),
_ => None,
}
}
/// Is this reference (any part of) a spline?
pub fn is_spline(&self, r: &GeomRef) -> bool {
self.slot(r.handle).is_some_and(|s| matches!(s.shape, Shape::Spline { .. }))
}
/// The spline of a reference with the defining points taken from `x`.
fn spline(&self, x: &[f64], s: &Slot) -> Option<GSpline> {
let Shape::Spline { n, fit, .. } = s.shape else { return None };
let t = self.splines.get(&s.handle)?;
let pts = (0..n).map(|i| p2(x, s.off + 2 * i)).collect::<Option<Vec<_>>>()?;
Some(if fit {
t.refit(&pts, t.closed)
} else {
let mut sp = t.clone();
sp.control = pts;
sp
})
}
/// The start (`at_end` false) or end of a curve reference, in the curve's own direction:
/// lines and polyline segments, arcs, elliptical arcs and open splines. A polyline's
/// `start`/`end` are its first and last segments' outer ends.
pub fn end_frame(&self, x: &[f64], r: &GeomRef, at_end: bool) -> Option<Frame> {
let s = self.slot(r.handle)?;
let o = s.off;
let seg = match (s.shape, r.sub) {
(Shape::Poly { .. }, Sub::Start) => Some(GeomRef::new(r.handle, Sub::Segment(0))),
(Shape::Poly { n, closed: false }, Sub::End) => Some(GeomRef::new(r.handle, Sub::Segment(n.checked_sub(2)? as u32))),
(Shape::Line, Sub::Start | Sub::End) => Some(GeomRef::whole(r.handle)),
_ => None,
};
if let Some((a, b)) = self.line(x, &seg.unwrap_or(*r)) {
let d = b - a;
let l = d.len();
if crate::curves::not_above(l, 1e-300) {
return None;
}
return Some(Frame { p: if at_end { b } else { a }, t: d * (1.0 / l), k: 0.0 });
}
match (s.shape, r.sub) {
(Shape::Arc, Sub::Whole | Sub::Start | Sub::End) => {
let (c, rad) = (p2(x, o)?, *x.get(o + 2)?);
let a = *x.get(if at_end { o + 4 } else { o + 3 })?;
if crate::curves::not_above(rad.abs(), 1e-300) {
return None;
}
let (p, d1) = crate::curves::circle_at(c, rad, a);
Some(Frame { p, t: d1.normalized(), k: 1.0 / rad })
}
(Shape::Ellipse { arc: true }, Sub::Whole | Sub::Start | Sub::End) => {
let e = self.ell_at(x, o, true)?;
e.frame(if at_end { e.t1 } else { e.t0 })
}
(Shape::Spline { ends: true, .. }, Sub::Whole | Sub::Start | Sub::End) => spline_end(&self.spline(x, s)?, at_end),
_ => None,
}
}
/// Squared distance of a block reference's farthest rigid point from its insertion point.
pub fn rigid_extent2(&self, h: Handle) -> f64 {
self.rigid.get(&h).map_or(0.0, |v| v.iter().map(|q| q.len2()).fold(0.0, f64::max))
}
/// Where to draw a glyph for a reference that is not a point, line or circle.
pub fn anchor(&self, x: &[f64], r: &GeomRef) -> Option<Vec2> {
let s = self.slot(r.handle)?;
match s.shape {
Shape::Ellipse { .. } => self.ell_at(x, s.off, false).map(|e| e.c + e.minor()),
Shape::Spline { n, .. } => p2(x, s.off + 2 * (n / 2)),
Shape::Insert { .. } => p2(x, s.off),
_ => None,
}
}
@@ -193,6 +494,11 @@ impl Model {
let (a, b) = Self::seg(n, closed, i as usize)?;
vec![o + 2 * a, o + 2 * a + 1, o + 2 * b, o + 2 * b + 1]
}
(Shape::Ellipse { .. } | Shape::Insert { .. }, Sub::Center) => vec![o, o + 1],
(Shape::Insert { .. }, Sub::Start) => vec![o, o + 1],
(Shape::Spline { n, .. }, Sub::Vertex(i)) if (i as usize) < n => vec![o + 2 * i as usize, o + 2 * i as usize + 1],
(Shape::Spline { ends: true, .. }, Sub::Start) => vec![o, o + 1],
(Shape::Spline { n, ends: true, .. }, Sub::End) if n > 0 => vec![o + 2 * (n - 1), o + 2 * (n - 1) + 1],
_ => return None,
};
Some(v)
@@ -211,6 +517,13 @@ impl Model {
continue;
}
let shape = s.shape;
// A control-point spline loses its fit data once its control points move.
let spline = self.spline(x, s).map(|mut sp| {
if matches!(shape, Shape::Spline { fit: false, .. }) {
sp.fit.clear();
}
sp
});
let ok = d.modify_entity(s.handle, |e| match (&mut e.kind, shape) {
(EntityKind::Line(l), Shape::Line) => {
if let [ax, ay, bx, by] = new {
@@ -229,11 +542,14 @@ impl Model {
}
(EntityKind::Arc(a), Shape::Arc) => {
if let [cx, cy, r, s0, s1] = new {
// A negative radius puts every point opposite its angle: turning both
// ends half a turn keeps the same points with a positive radius.
let turn = if *r < 0.0 { std::f64::consts::PI } else { 0.0 };
a.center.x = *cx;
a.center.y = *cy;
a.radius = r.abs().max(1e-12);
a.start = cadcraft_geom::norm_angle(*s0);
a.end = cadcraft_geom::norm_angle(*s1);
a.start = cadcraft_geom::norm_angle(*s0 + turn);
a.end = cadcraft_geom::norm_angle(*s1 + turn);
}
}
(EntityKind::LwPolyline(p), Shape::Poly { n, .. }) if p.vertices.len() == n => {
@@ -249,6 +565,47 @@ impl Model {
p.p.y = *py;
}
}
(EntityKind::Ellipse(el), Shape::Ellipse { arc }) => {
if let [cx, cy, mx, my, ratio, rest @ ..] = new {
let (mut major, mut ratio) = (Vec2::new(*mx, *my), ratio.abs());
let (mut t0, mut t1) = match rest {
[a, b] if arc => (*a, *b),
_ => (el.start, el.end),
};
// Keep the stored form: the major axis is the longer one.
if ratio > 1.0 {
major = major.perp() * ratio;
ratio = 1.0 / ratio;
if arc {
t0 -= std::f64::consts::FRAC_PI_2;
t1 -= std::f64::consts::FRAC_PI_2;
}
}
if major.len() > 1e-12 {
el.center.x = *cx;
el.center.y = *cy;
el.major.x = major.x;
el.major.y = major.y;
el.ratio = ratio.clamp(1e-9, 1.0);
if arc {
el.start = cadcraft_geom::norm_angle(t0);
el.end = cadcraft_geom::norm_angle(t1);
}
}
}
}
(EntityKind::Spline(sp), Shape::Spline { .. }) => {
if let Some(rebuilt) = spline.as_ref() {
*sp = rebuilt.clone();
}
}
(EntityKind::Insert(ins), Shape::Insert { .. }) => {
if let [ix, iy, rot] = new {
ins.insert.x = *ix;
ins.insert.y = *iy;
ins.rotation = cadcraft_geom::norm_angle(*rot);
}
}
_ => {}
});
if ok.is_ok() {
@@ -258,3 +615,60 @@ impl Model {
moved
}
}
#[cfg(test)]
mod budget_tests {
use super::*;
use cadcraft_doc::{Block, Common, Entity, Line, Space};
use cadcraft_geom::Vec3;
use std::sync::Arc;
/// Writing an unchanged model back leaves partial rational weights and the original spline geometry intact.
#[test]
fn write_back_keeps_partial_rational_weights() {
let mut drawing = Drawing::default();
let mut spline = GSpline::from_control(vec![Vec2::ZERO, Vec2::new(1.0, 2.0), Vec2::new(3.0, 0.0)], 2);
spline.weights = vec![2.0, 0.5];
let h = drawing.add(&Space::Model, Common::default(), EntityKind::Spline(spline.clone())).unwrap();
let model = Model::build(&drawing, &[h]);
model.write_back(&mut drawing, &model.x0);
let EntityKind::Spline(after) = &drawing.entity(h).unwrap().kind else { panic!("spline") };
assert_eq!(after.weights, spline.weights);
for i in 0..=10 {
assert!(after.eval(i as f64 / 10.0).near(spline.eval(i as f64 / 10.0), 1e-12));
}
}
/// A second model receives no sampled block points after the first model spends the shared member budget.
#[test]
fn rigid_sampling_budget_is_shared_between_models() {
let mut d = Drawing::default();
let mut block = Block::new("BAR");
for _ in 0..3 {
block.entities.push(Entity {
handle: d.new_handle(),
common: Common::default(),
kind: EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }),
});
}
d.blocks.insert("BAR".into(), Arc::new(block));
let ins = Insert {
block: "BAR".into(),
insert: Vec3::ZERO,
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,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let mut budget = 2;
let first = Model::build_budgeted(&d, &[h], &mut budget);
assert_eq!(first.rigid[&h].len(), 4);
assert_eq!(budget, 0);
let next = Model::build_budgeted(&d, &[h], &mut budget);
assert!(next.rigid[&h].is_empty());
}
}
+221 -18
View File
@@ -3,8 +3,12 @@
use cadcraft_doc::{Constraint, ConstraintKind, DistAxis, GeomRef};
use cadcraft_geom::Vec2;
use crate::curves::circle_at;
use crate::model::Model;
/// Contact parameter samples per curve when guessing where two curves touch.
const CONTACT_SAMPLES: usize = 72;
/// How a constraint's references were interpreted (decided once from the starting geometry).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Form {
@@ -36,10 +40,38 @@ pub(crate) enum Form {
C1,
/// Arc sweep (angular on an arc).
ArcSweep,
/// Two lines measured along the rays from their intersection to each line's far end, the
/// angle the dimension draws; `rev` marks a line whose far end is its start point.
Rays {
rev: [bool; 2],
},
/// Fix of a derived point (residual to an anchor).
Anchor(Vec2),
/// Fix handled by locking parameters (no rows).
Lock,
/// Point on an ellipse (refs: point, ellipse).
PE {
swap: bool,
},
/// Line tangent to an ellipse.
LE {
swap: bool,
},
/// Two curves (circles, arcs, ellipses; at least one ellipse) touching at a contact point
/// given by one auxiliary parameter per curve.
Contact,
/// A spline end on a line, circle, arc or ellipse and tangent to it (`spline`: which
/// reference is the spline).
EndOn {
spline: usize,
at_end: bool,
},
/// Two curve ends joined with a common tangent (G1), and common curvature when `g2`.
Join {
a_end: bool,
b_end: bool,
g2: bool,
},
}
#[derive(Clone, Debug)]
@@ -53,6 +85,10 @@ pub(crate) struct Built {
/// Orientation chosen from the starting geometry (±1).
pub sign: f64,
pub rows: usize,
/// Starting values of auxiliary unknowns (contact parameters), appended to the parameter
/// vector at `aux` by [`crate::interpret`].
pub aux_init: Vec<f64>,
pub aux: usize,
}
fn dir_n(a: Vec2, b: Vec2) -> Vec2 {
@@ -61,6 +97,10 @@ fn dir_n(a: Vec2, b: Vec2) -> Vec2 {
if l > 1e-12 { d * (1.0 / l) } else { d }
}
fn ray(a: Vec2, b: Vec2, rev: bool) -> Vec2 {
if rev { dir_n(b, a) } else { dir_n(a, b) }
}
fn sgn(v: f64) -> f64 {
if v < 0.0 { -1.0 } else { 1.0 }
}
@@ -76,6 +116,16 @@ fn r_at(c: &Constraint, i: usize) -> Option<&GeomRef> {
}
impl Built {
/// Estimate spline reconstruction work for endpoint and join residuals; other residual forms add no such cost.
pub(crate) fn spline_reconstruct_cost(&self, m: &Model) -> f64 {
let cost = |i: usize| self.refs.get(i).map_or(0.0, |r| m.spline_reconstruct_cost(r.handle));
match self.form {
Form::EndOn { spline, .. } => cost(spline),
Form::Join { .. } => cost(0) + cost(1),
_ => 0.0,
}
}
/// Interpret a constraint against the model at `x`. `target` is the evaluated value for
/// dimensional constraints (degrees for angular). Errors explain what references are needed.
pub fn new(c: &Constraint, m: &Model, x: &[f64], target: f64) -> Result<Built, String> {
@@ -85,7 +135,9 @@ impl Built {
let ln = |i: usize| r_at(c, i).and_then(|r| m.line(x, r));
let ci = |i: usize| r_at(c, i).and_then(|r| m.circle(x, r));
let n = c.refs.len();
let mut b = Built { id: c.id, kind: c.kind, refs, form: Form::PP, target, sign: 1.0, rows: 0 };
let el = |i: usize| r_at(c, i).and_then(|r| m.ellipse(x, r));
let lnx = |i: usize| ln(i).or_else(|| el(i).map(|e| (e.c - e.mj, e.c + e.mj)));
let mut b = Built { id: c.id, kind: c.kind, refs, form: Form::PP, target, sign: 1.0, rows: 0, aux_init: Vec::new(), aux: 0 };
let need = |what: &str| Err(format!("{} needs {what}", c.kind.name()));
match c.kind {
K::Coincident => {
@@ -103,20 +155,24 @@ impl Built {
Form::PC { swap: false }
} else if pt(1).is_some() && ci(0).is_some() {
Form::PC { swap: true }
} else if pt(0).is_some() && el(1).is_some() {
Form::PE { swap: false }
} else if pt(1).is_some() && el(0).is_some() {
Form::PE { swap: true }
} else {
return need("two points, or a point and a line/circle/arc");
return need("two points, or a point and a line/circle/arc/ellipse");
};
if b.rows == 0 {
b.rows = 1;
}
}
K::Horizontal | K::Vertical => {
if n == 1 && ln(0).is_some() {
if n == 1 && lnx(0).is_some() {
b.form = Form::L1;
} else if n == 2 && pt(0).is_some() && pt(1).is_some() {
b.form = Form::P2;
} else {
return need("a line or two points");
return need("a line, an ellipse or two points");
}
b.rows = 1;
}
@@ -128,9 +184,10 @@ impl Built {
b.rows = if c.kind == K::Collinear { 2 } else { 1 };
}
K::Concentric => {
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| pt(i));
if !(n == 2 && center(0).is_some() && center(1).is_some() && (ci(0).is_some() || ci(1).is_some())) {
return need("two circles or arcs");
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| el(i).map(|e| e.c)).or_else(|| pt(i));
let curve = |i: usize| ci(i).is_some() || el(i).is_some();
if !(n == 2 && center(0).is_some() && center(1).is_some() && (curve(0) || curve(1))) {
return need("two circles, arcs or ellipses");
}
b.form = Form::CC;
b.rows = 2;
@@ -152,6 +209,9 @@ impl Built {
if n != 2 {
return need("two objects");
}
if c.refs.iter().any(|r| m.is_spline(r)) {
return Self::spline_form(b, m, x);
}
b.rows = 1;
if let (Some((a, bb)), Some((cc, _))) = (ln(0), ci(1)) {
b.form = Form::LC { swap: false };
@@ -165,10 +225,20 @@ impl Built {
let d = c1.dist(c2);
b.sign = if d >= r1.abs().max(r2.abs()) { 1.0 } else { -1.0 };
b.target = sgn(r1 - r2);
} else if let (Some((a, bb)), Some(e)) = (ln(0), el(1)) {
b.form = Form::LE { swap: false };
b.sign = sgn(dir_n(a, bb).cross(e.c - a));
} else if let (Some((a, bb)), Some(e)) = (ln(1), el(0)) {
b.form = Form::LE { swap: true };
b.sign = sgn(dir_n(a, bb).cross(e.c - a));
} else if (ci(0).is_some() || el(0).is_some()) && (ci(1).is_some() || el(1).is_some()) {
b.form = Form::Contact;
b.rows = 3;
b.aux_init = b.contact_guess(m, x).ok_or_else(|| format!("{} could not find where the curves touch", c.kind.name()))?;
} else if ln(0).is_some() && ln(1).is_some() && c.kind == K::Smooth {
b.form = Form::LL;
} else {
return need("a line and a circle/arc, or two circles/arcs");
return need("a line and a circle/arc/ellipse, two curves, or a spline end and a curve");
}
}
K::Symmetric => {
@@ -233,10 +303,15 @@ impl Built {
}
K::Angular => {
b.rows = 1;
if n == 2 && ln(0).is_some() && ln(1).is_some() {
b.form = Form::LL;
let (Some((a1, b1)), Some((a2, b2))) = (ln(0), ln(1)) else { return need("two lines") };
let (d1, d2) = (dir_n(a1, b1), dir_n(a2, b2));
if let (2, Some((a1, b1)), Some((a2, b2))) = (n, ln(0), ln(1)) {
// Start-to-end directions would measure the supplement when a line is drawn
// towards the vertex, so use the rays the dimension draws.
let rev = match cadcraft_geom::line_line_infinite(a1, b1, a2, b2) {
Some((_, t, u)) => [t > 0.5, u > 0.5],
None => [false, false],
};
b.form = Form::Rays { rev };
let (d1, d2) = (ray(a1, b1, rev[0]), ray(a2, b2, rev[1]));
b.sign = sgn(d1.cross(d2).atan2(d1.dot(d2)));
} else if n == 1 && m.arc_sweep(x, r_at(c, 0).ok_or_else(|| "Angular needs references".to_string())?).is_some() {
b.form = Form::ArcSweep;
@@ -246,7 +321,7 @@ impl Built {
b.target = target.to_radians();
// Two lines measure a signed angle in [-180, 180] and the sign is re-read from the geometry, so a larger
// target would flip the sign once solved and never be satisfied; only an arc sweep can reach a full turn.
let max = if b.form == Form::LL { std::f64::consts::PI } else { std::f64::consts::TAU };
let max = if matches!(b.form, Form::Rays { .. }) { std::f64::consts::PI } else { std::f64::consts::TAU };
if !b.target.is_finite() || b.target.abs() > max {
return Err("angle out of range".into());
}
@@ -257,7 +332,7 @@ impl Built {
}
b.form = Form::C1;
b.rows = 1;
if !(target.is_finite() && target > 0.0) {
if !target.is_finite() || crate::curves::not_above(target, 0.0) {
return Err(format!("{} value must be positive", c.kind.name()));
}
}
@@ -278,8 +353,47 @@ impl Built {
let pt = |i: usize| m.point(x, r(i)?);
let ln = |i: usize| m.line(x, r(i)?);
let ci = |i: usize| m.circle(x, r(i)?);
let el = |i: usize| m.ellipse(x, r(i)?);
match (self.kind, self.form) {
(_, Form::Lock) => {}
(_, Form::PE { swap }) => {
let (p, e) = if swap { (pt(1)?, el(0)?) } else { (pt(0)?, el(1)?) };
out.push(e.on(p));
}
(_, Form::LE { swap }) => {
let ((a, b), e) = if swap { (ln(1)?, el(0)?) } else { (ln(0)?, el(1)?) };
let d = dir_n(a, b);
out.push(self.sign * d.cross(e.c - a) - e.support(d.perp()));
}
(_, Form::Contact) => {
let (p0, d0) = self.curve_at(m, x, 0, *x.get(self.aux)?)?;
let (p1, d1) = self.curve_at(m, x, 1, *x.get(self.aux + 1)?)?;
out.extend([p0.x - p1.x, p0.y - p1.y, d0.normalized().cross(d1.normalized())]);
}
(_, Form::EndOn { spline, at_end }) => {
let f = m.end_frame(x, r(spline)?, at_end)?;
let o = 1 - spline.min(1);
if let Some((a, b)) = ln(o) {
let d = dir_n(a, b);
out.extend([d.cross(f.p - a), f.t.cross(d)]);
} else if let Some((c, rad)) = ci(o) {
out.extend([f.p.dist(c) - rad, f.t.dot(dir_n(c, f.p))]);
} else {
let e = el(o)?;
out.extend([e.on(f.p), f.t.dot(e.normal(f.p))]);
}
}
(_, Form::Join { a_end, b_end, g2 }) => {
// Orient both so the first curve runs into the joint and the second out of it.
let fa = m.end_frame(x, r(0)?, a_end)?;
let fb = m.end_frame(x, r(1)?, b_end)?;
let fa = if a_end { fa } else { fa.reversed() };
let fb = if b_end { fb.reversed() } else { fb };
out.extend([fa.p.x - fb.p.x, fa.p.y - fb.p.y, fa.t.cross(fb.t)]);
if g2 {
out.push(fa.k - fb.k);
}
}
(_, Form::Anchor(a)) => {
let p = pt(0)?;
out.extend([p.x - a.x, p.y - a.y]);
@@ -297,7 +411,7 @@ impl Built {
out.push(p.dist(c) - rad);
}
(K::Horizontal | K::Vertical, f) => {
let (a, b) = if f == Form::L1 { ln(0)? } else { (pt(0)?, pt(1)?) };
let (a, b) = if f == Form::L1 { ln(0).or_else(|| el(0).map(|e| (e.c - e.mj, e.c + e.mj)))? } else { (pt(0)?, pt(1)?) };
out.push(if self.kind == K::Horizontal { a.y - b.y } else { a.x - b.x });
}
(K::Parallel | K::Smooth, Form::LL) => {
@@ -314,7 +428,7 @@ impl Built {
out.extend([d.cross(a2 - a1), d.cross(b2 - a1)]);
}
(K::Concentric, _) => {
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| pt(i));
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| el(i).map(|e| e.c)).or_else(|| pt(i));
let (p, q) = (center(0)?, center(1)?);
out.extend([p.x - q.x, p.y - q.y]);
}
@@ -371,9 +485,9 @@ impl Built {
(K::Angular, Form::ArcSweep) => {
out.push(m.arc_sweep(x, r(0)?)? - self.target);
}
(K::Angular, _) => {
(K::Angular, Form::Rays { rev }) => {
let ((a1, b1), (a2, b2)) = (ln(0)?, ln(1)?);
let (d1, d2) = (dir_n(a1, b1), dir_n(a2, b2));
let (d1, d2) = (ray(a1, b1, rev[0]), ray(a2, b2, rev[1]));
out.push(wrap(d1.cross(d2).atan2(d1.dot(d2)) - self.sign * self.target));
}
(K::Radius, _) => out.push(ci(0)?.1 - self.target),
@@ -383,6 +497,95 @@ impl Built {
Some(())
}
/// Point and derivative of curve reference `i` (circle, arc or ellipse) at parameter `t`.
fn curve_at(&self, m: &Model, x: &[f64], i: usize, t: f64) -> Option<(Vec2, Vec2)> {
let r = self.refs.get(i)?;
if let Some((c, rad)) = m.circle(x, r) {
return Some(circle_at(c, rad, t));
}
let e = m.ellipse(x, r)?;
Some((e.at(t), e.d1(t)))
}
/// Contact parameters where two curves come closest (sampled), for [`Form::Contact`].
fn contact_guess(&self, m: &Model, x: &[f64]) -> Option<Vec<f64>> {
let step = std::f64::consts::TAU / CONTACT_SAMPLES as f64;
let s0: Vec<(f64, Vec2)> = (0..CONTACT_SAMPLES).filter_map(|k| Some((k as f64 * step, self.curve_at(m, x, 0, k as f64 * step)?.0))).collect();
let s1: Vec<(f64, Vec2)> = (0..CONTACT_SAMPLES).filter_map(|k| Some((k as f64 * step, self.curve_at(m, x, 1, k as f64 * step)?.0))).collect();
let mut best: Option<(f64, f64, f64)> = None;
for (t0, p0) in &s0 {
for (t1, p1) in &s1 {
let d = p0.dist(*p1);
if d.is_finite() && best.is_none_or(|b| d < b.0) {
best = Some((d, *t0, *t1));
}
}
}
best.map(|(_, a, b)| vec![a, b])
}
/// Tangent or Smooth with a spline: the spline end and the other curve's nearest end are
/// joined (Smooth: G2; Tangent between splines: G1), or the spline's end touches a line,
/// circle, arc or ellipse tangentially. A `start`/`end` reference picks the end.
fn spline_form(mut b: Built, m: &Model, x: &[f64]) -> Result<Built, String> {
let (Some(r0), Some(r1)) = (b.refs.first().copied(), b.refs.get(1).copied()) else {
return Err(format!("{} needs two objects", b.kind.name()));
};
let ends = |r: &GeomRef| -> &'static [bool] {
match r.sub {
cadcraft_doc::Sub::Start => &[false],
cadcraft_doc::Sub::End => &[true],
_ => &[false, true],
}
};
let join = b.kind == ConstraintKind::Smooth || (m.is_spline(&r0) && m.is_spline(&r1));
if join {
let mut best: Option<(f64, bool, bool)> = None;
for &ea in ends(&r0) {
for &eb in ends(&r1) {
if let (Some(fa), Some(fb)) = (m.end_frame(x, &r0, ea), m.end_frame(x, &r1, eb)) {
let d = fa.p.dist(fb.p);
if d.is_finite() && best.is_none_or(|bb| d < bb.0) {
best = Some((d, ea, eb));
}
}
}
}
let Some((_, a_end, b_end)) = best else {
return Err(format!("{} needs an open spline and a line, arc, elliptical arc, polyline segment or open spline", b.kind.name()));
};
let g2 = b.kind == ConstraintKind::Smooth;
b.form = Form::Join { a_end, b_end, g2 };
b.rows = if g2 { 4 } else { 3 };
return Ok(b);
}
let (si, rs, ro) = if m.is_spline(&r0) { (0, r0, r1) } else { (1, r1, r0) };
let dist = |p: Vec2| -> Option<f64> {
if let Some((a, bb)) = m.line(x, &ro) {
Some(dir_n(a, bb).cross(p - a).abs())
} else if let Some((c, rad)) = m.circle(x, &ro) {
Some((p.dist(c) - rad).abs())
} else {
m.ellipse(x, &ro).map(|e| e.on(p).abs())
}
};
let mut best: Option<(f64, bool)> = None;
for &e in ends(&rs) {
if let Some(d) = m.end_frame(x, &rs, e).and_then(|f| dist(f.p))
&& d.is_finite()
&& best.is_none_or(|bb| d < bb.0)
{
best = Some((d, e));
}
}
let Some((_, at_end)) = best else {
return Err("Tangent needs an open spline and a line, circle, arc, ellipse or spline".into());
};
b.form = Form::EndOn { spline: si, at_end };
b.rows = 2;
Ok(b)
}
/// The current measured value (degrees for angular), for dimensional constraints.
pub fn measure(&self, m: &Model, x: &[f64]) -> f64 {
let mut b = self.clone();
+26
View File
@@ -463,3 +463,29 @@ fn set_parameter_rejects_out_of_domain_dimension() {
set_parameter(&mut d, "rad1", "2", &opts).unwrap();
assert!(all_satisfied(&d));
}
/// The solver may meet a coincidence with a negative arc radius; the stored arc must still put
/// the referenced point where the solver did (issue #703), through `add` and through `solve`.
#[test]
fn arc_solved_with_a_negative_radius_keeps_its_points() {
use std::f64::consts::FRAC_PI_2;
// (arc centre, radius, start, end, point): a semicircle with the point behind it, and the
// asymmetric case from the issue.
let cases = [((0.0, 0.0), 1.0, -FRAC_PI_2, FRAC_PI_2, (-5.0, 0.0)), ((6.694, -0.686), 0.62075, 3.4824, 1.1766, (-7.562, 4.946))];
for (c, r, a0, a1, p) in cases {
for through_solve in [false, true] {
let mut d = Drawing::default();
let a = arc(&mut d, c, r, a0, a1);
let q = add_e(&mut d, EntityKind::Point(DPoint { p: v(p.0, p.1), angle: 0.0 }));
let k = con(ConstraintKind::Coincident, &[s(a, Sub::Mid), w(q)]);
if through_solve {
d.constraints.push(Constraint { id: 1, ..k });
solve(&mut d, &SolveOptions::default()).unwrap();
} else {
ok(&mut d, k);
}
assert!(all_satisfied(&d), "{c:?} solve {through_solve}: {:?}", residuals(&d));
assert!(circ(&d, a).1 > 0.0);
}
}
}
+384
View File
@@ -0,0 +1,384 @@
//! Degrees of freedom, redundancy hints, ellipse/spline/block geometry and Smooth (G2).
use std::sync::Arc;
use cadcraft_constraints::{DofStatus, SolveError, SolveOptions, add, all_satisfied, dof, solve};
use cadcraft_doc::{
Arc as DArc, Block, Circle as DCircle, Common, Constraint, ConstraintKind as K, DistAxis, Drawing, Ellipse as DEllipse, Entity, EntityKind,
GeomRef, Handle, Insert, Line as DLine, Point as DPoint, Space, Sub,
};
use cadcraft_geom::{Spline as GSpline, Vec2, Vec3};
fn v(x: f64, y: f64) -> Vec3 {
Vec3::new(x, y, 0.0)
}
fn put(d: &mut Drawing, k: EntityKind) -> Handle {
d.add(&Space::Model, Common::default(), k).unwrap()
}
fn line(d: &mut Drawing, a: (f64, f64), b: (f64, f64)) -> Handle {
put(d, EntityKind::Line(DLine { a: v(a.0, a.1), b: v(b.0, b.1) }))
}
fn circle(d: &mut Drawing, c: (f64, f64), r: f64) -> Handle {
put(d, EntityKind::Circle(DCircle { center: v(c.0, c.1), radius: r }))
}
fn point(d: &mut Drawing, p: (f64, f64)) -> Handle {
put(d, EntityKind::Point(DPoint { p: v(p.0, p.1), angle: 0.0 }))
}
fn ellipse(d: &mut Drawing, c: (f64, f64), major: (f64, f64), ratio: f64, start: f64, end: f64) -> Handle {
put(d, EntityKind::Ellipse(DEllipse { center: v(c.0, c.1), major: v(major.0, major.1), ratio, start, end }))
}
fn spline(d: &mut Drawing, pts: &[(f64, f64)]) -> Handle {
let s = GSpline::from_control(pts.iter().map(|p| Vec2::new(p.0, p.1)).collect(), 3);
put(d, EntityKind::Spline(s))
}
fn con(kind: K, refs: &[GeomRef]) -> Constraint {
Constraint { id: 0, kind, refs: refs.to_vec(), name: String::new(), expr: String::new() }
}
fn dim(kind: K, refs: &[GeomRef], expr: &str) -> Constraint {
Constraint { id: 0, kind, refs: refs.to_vec(), name: String::new(), expr: expr.into() }
}
fn w(h: Handle) -> GeomRef {
GeomRef::whole(h)
}
fn s(h: Handle, sub: Sub) -> GeomRef {
GeomRef::new(h, sub)
}
fn ok(d: &mut Drawing, c: Constraint) -> u32 {
let k = c.kind;
add(d, c, &SolveOptions::default()).unwrap_or_else(|e| panic!("{k:?}: {e}"))
}
fn ends(d: &Drawing, h: Handle) -> (Vec2, Vec2) {
match &d.entity(h).unwrap().kind {
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
_ => panic!("not a line"),
}
}
fn ell(d: &Drawing, h: Handle) -> cadcraft_geom::Ellipse {
match &d.entity(h).unwrap().kind {
EntityKind::Ellipse(e) => cadcraft_geom::Ellipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio, start: e.start, end: e.end },
_ => panic!("not an ellipse"),
}
}
fn spl(d: &Drawing, h: Handle) -> GSpline {
match &d.entity(h).unwrap().kind {
EntityKind::Spline(s) => s.clone(),
_ => panic!("not a spline"),
}
}
fn obj_dof(d: &Drawing, h: Handle) -> Option<usize> {
let r = dof(d, &[h]).unwrap();
r.objects.iter().find(|o| o.handle == h.hex()).and_then(|o| o.dof)
}
/// Signed curvature by sampling a curve near a parameter (central differences).
fn curvature(f: impl Fn(f64) -> Vec2, t: f64, h: f64) -> f64 {
let (a, b, c) = (f(t - h), f(t), f(t + h));
let d1 = (c - a) * (0.5 / h);
let d2 = (c - b * 2.0 + a) * (1.0 / (h * h));
d1.cross(d2) / d1.len().powi(3)
}
#[test]
fn rectangle_dof_counts_down_to_fully_constrained() {
let mut d = Drawing::default();
let l = [
line(&mut d, (0.0, 0.0), (10.0, 0.2)),
line(&mut d, (10.0, 0.2), (10.1, 5.0)),
line(&mut d, (10.1, 5.0), (0.0, 5.0)),
line(&mut d, (0.0, 5.0), (0.0, 0.0)),
];
let r = dof(&d, &[]).unwrap();
assert_eq!((r.status, r.dof, r.message.as_str()), (DofStatus::Unconstrained, Some(0), "No constraints"));
// An unconstrained line has its four parameters.
assert_eq!(obj_dof(&d, l[0]), Some(4));
for i in 0..4 {
ok(&mut d, con(K::Coincident, &[s(l[i], Sub::End), s(l[(i + 1) % 4], Sub::Start)]));
}
ok(&mut d, con(K::Horizontal, &[w(l[0])]));
ok(&mut d, con(K::Horizontal, &[w(l[2])]));
ok(&mut d, con(K::Vertical, &[w(l[1])]));
ok(&mut d, con(K::Vertical, &[w(l[3])]));
// 16 parameters − 12 equations: translation, width, height.
let r = dof(&d, &[]).unwrap();
assert_eq!((r.dof, r.status, r.redundant), (Some(4), DofStatus::Under, 0));
assert_eq!(r.objects.len(), 4);
assert!(r.objects.iter().all(|o| o.params == 4 && o.dof == Some(3) && o.status == DofStatus::Under), "{r:?}");
ok(&mut d, con(K::Fix, &[s(l[0], Sub::Start)]));
assert_eq!(dof(&d, &[]).unwrap().dof, Some(2));
ok(&mut d, dim(K::Distance(DistAxis::Aligned), &[w(l[0])], "12"));
// The bottom edge is now fixed; the others still stretch with the height.
assert_eq!(obj_dof(&d, l[0]), Some(0));
assert_eq!(obj_dof(&d, l[2]), Some(1));
ok(&mut d, dim(K::Distance(DistAxis::Aligned), &[w(l[1])], "4"));
let r = dof(&d, &[]).unwrap();
assert_eq!((r.dof, r.status, r.message.as_str()), (Some(0), DofStatus::Fully, "Fully constrained"));
assert!(r.objects.iter().all(|o| o.status == DofStatus::Fully));
// A fully constrained rectangle refuses one more dimension, naming the constraints it repeats.
let e = add(&mut d, dim(K::Distance(DistAxis::Aligned), &[w(l[3])], "4"), &SolveOptions::default()).unwrap_err();
let SolveError::Redundant { ids } = e else { panic!("{e:?}") };
assert!(!ids.is_empty());
}
#[test]
fn redundant_hint_names_the_duplicated_constraints() {
let mut d = Drawing::default();
let a = line(&mut d, (0.0, 0.0), (10.0, 0.1));
let b = line(&mut d, (0.0, 5.0), (10.0, 5.2));
let c = line(&mut d, (20.0, 0.0), (20.0, 9.0));
let ha = ok(&mut d, con(K::Horizontal, &[w(a)]));
let hb = ok(&mut d, con(K::Horizontal, &[w(b)]));
let vc = ok(&mut d, con(K::Vertical, &[w(c)]));
ok(&mut d, con(K::Coincident, &[s(b, Sub::End), s(c, Sub::Start)]));
let before = d.clone();
let e = add(&mut d, con(K::Parallel, &[w(a), w(b)]), &SolveOptions::default()).unwrap_err();
let SolveError::Redundant { ids } = &e else { panic!("{e:?}") };
assert!(ids.contains(&ha) && ids.contains(&hb), "{ids:?}");
assert!(!ids.contains(&vc), "{ids:?}");
assert!(e.to_string().contains(&format!("#{ha}")), "{e}");
assert_eq!(d, before);
}
#[test]
fn over_constrained_drawing_is_reported() {
let mut d = Drawing::default();
let a = line(&mut d, (0.0, 0.0), (10.0, 0.0));
ok(&mut d, con(K::Horizontal, &[w(a)]));
// A file can hold a duplicate the command would have refused.
d.constraints.push(Constraint { id: 99, ..con(K::Horizontal, &[w(a)]) });
let r = dof(&d, &[]).unwrap();
assert_eq!((r.status, r.redundant), (DofStatus::Over, 1));
assert!(r.message.starts_with("Over-constrained"), "{}", r.message);
assert_eq!(r.objects[0].status, DofStatus::Over);
}
#[test]
fn ellipse_constraints() {
let mut d = Drawing::default();
let e = ellipse(&mut d, (0.0, 0.0), (6.0, 0.5), 0.5, 0.0, std::f64::consts::TAU);
assert_eq!(obj_dof(&d, e), Some(5));
// Horizontal applies to the major axis.
ok(&mut d, con(K::Horizontal, &[w(e)]));
assert!(ell(&d, e).major.y.abs() < 1e-9);
// A point on the ellipse.
let p = point(&mut d, (0.3, 3.4));
ok(&mut d, con(K::Coincident, &[w(p), w(e)]));
let g = ell(&d, e);
let pp = match &d.entity(p).unwrap().kind {
EntityKind::Point(q) => q.p.xy(),
_ => unreachable!(),
};
let (a, b) = (g.major.len(), g.major.len() * g.ratio);
let q = pp - g.center;
assert!(((q.x / a).powi(2) + (q.y / b).powi(2) - 1.0).abs() < 1e-7);
// Concentric with a circle.
let c = circle(&mut d, (0.5, -0.4), 1.0);
ok(&mut d, con(K::Concentric, &[w(e), w(c)]));
let cc = match &d.entity(c).unwrap().kind {
EntityKind::Circle(k) => k.center.xy(),
_ => unreachable!(),
};
assert!(cc.near(ell(&d, e).center, 1e-7));
// A line tangent to the ellipse.
let l = line(&mut d, (-10.0, 3.6), (10.0, 3.2));
ok(&mut d, con(K::Tangent, &[w(l), w(e)]));
let (la, lb) = ends(&d, l);
let g = ell(&d, e);
let n = (lb - la).normalized().perp();
let support = (n.dot(g.major).powi(2) + n.dot(g.minor()).powi(2)).sqrt();
assert!(((g.center - la).dot(n).abs() - support).abs() < 1e-7);
// An axis end point coincides with a line end.
let m = line(&mut d, (6.2, 0.3), (9.0, 5.0));
ok(&mut d, con(K::Coincident, &[s(e, Sub::Vertex(0)), s(m, Sub::Start)]));
let g = ell(&d, e);
assert!(ends(&d, m).0.near(g.center + g.major, 1e-7));
assert!(all_satisfied(&d));
}
#[test]
fn circle_tangent_to_ellipse_and_elliptical_arc_ends() {
let mut d = Drawing::default();
let e = ellipse(&mut d, (0.0, 0.0), (5.0, 0.0), 0.6, 0.0, std::f64::consts::TAU);
ok(&mut d, con(K::Fix, &[w(e)]));
let c = circle(&mut d, (7.5, 0.4), 2.0);
ok(&mut d, con(K::Tangent, &[w(c), w(e)]));
let (cc, r) = match &d.entity(c).unwrap().kind {
EntityKind::Circle(k) => (k.center.xy(), k.radius),
_ => unreachable!(),
};
// Closest distance from the circle's centre to the ellipse equals the radius.
let g = ell(&d, e);
let near = (0..20000).map(|i| g.at_param(i as f64 * std::f64::consts::TAU / 20000.0).dist(cc)).fold(f64::INFINITY, f64::min);
assert!((near - r).abs() < 1e-3, "{near} vs {r}");
assert!(all_satisfied(&d));
// Elliptical arc ends are points.
let arc = ellipse(&mut d, (20.0, 0.0), (4.0, 0.0), 0.5, 0.0, std::f64::consts::PI);
assert_eq!(obj_dof(&d, arc), Some(7));
let l = line(&mut d, (24.3, 0.2), (30.0, 0.0));
ok(&mut d, con(K::Coincident, &[s(arc, Sub::Start), s(l, Sub::Start)]));
let g = ell(&d, arc);
assert!(ends(&d, l).0.near(g.at_param(g.start), 1e-7));
}
#[test]
fn spline_points_tangent_and_smooth_g2() {
let mut d = Drawing::default();
// Arc to the left of the spline's start.
let a = put(&mut d, EntityKind::Arc(DArc { center: v(0.0, 3.0), radius: 3.0, start: std::f64::consts::PI, end: 1.5 * std::f64::consts::PI }));
ok(&mut d, con(K::Fix, &[w(a)]));
let sp = spline(&mut d, &[(0.1, 0.1), (3.0, 0.4), (6.0, 2.0), (9.0, 2.0)]);
assert_eq!(obj_dof(&d, sp), Some(8));
ok(&mut d, con(K::Smooth, &[w(sp), w(a)]));
let g = spl(&d, sp);
let (lo, _) = g.domain();
// Joined at the arc's end (0, 0), tangent along +x, curvature 1/3 like the arc.
assert!(g.eval(lo).near(Vec2::new(0.0, 0.0), 1e-7), "{:?}", g.eval(lo));
let t = (g.eval(lo + 1e-6) - g.eval(lo)).normalized();
assert!(t.near(Vec2::new(1.0, 0.0), 1e-4), "{t:?}");
let k = curvature(|u| g.eval(u), lo + 1e-3, 1e-4);
assert!((k - 1.0 / 3.0).abs() < 2e-2, "curvature {k}");
assert!(all_satisfied(&d));
// The spline's control points are constraint points.
let p = point(&mut d, (9.5, 2.5));
ok(&mut d, con(K::Coincident, &[s(sp, Sub::Vertex(3)), w(p)]));
let pp = match &d.entity(p).unwrap().kind {
EntityKind::Point(q) => q.p.xy(),
_ => unreachable!(),
};
assert!(spl(&d, sp).control[3].near(pp, 1e-7));
// Smooth to a line: the far end ends straight.
let l = line(&mut d, (9.2, 2.1), (15.0, 3.0));
ok(&mut d, con(K::Smooth, &[w(sp), w(l)]));
let g = spl(&d, sp);
let (_, hi) = g.domain();
assert!(g.eval(hi).near(ends(&d, l).0, 1e-7));
let k = curvature(|u| g.eval(u), hi - 1e-3, 1e-4);
assert!(k.abs() < 2e-2, "curvature at the line {k}");
assert!(all_satisfied(&d));
}
#[test]
fn spline_tangent_to_circle_and_fit_spline_smooth() {
let mut d = Drawing::default();
let c = circle(&mut d, (0.0, 0.0), 2.0);
ok(&mut d, con(K::Fix, &[w(c)]));
let sp = spline(&mut d, &[(2.1, 0.3), (2.5, 3.0), (5.0, 4.0), (8.0, 4.0)]);
ok(&mut d, con(K::Tangent, &[w(sp), w(c)]));
let g = spl(&d, sp);
let (lo, _) = g.domain();
let p = g.eval(lo);
assert!((p.len() - 2.0).abs() < 1e-7);
let t = (g.eval(lo + 1e-7) - p).normalized();
assert!(t.dot(p.normalized()).abs() < 1e-4);
// A fit-point spline keeps its fit points and is rebuilt through them.
let fit: Vec<Vec2> = [(20.0, 0.0), (23.0, 2.0), (27.0, 1.0), (30.0, 3.0)].iter().map(|p| Vec2::new(p.0, p.1)).collect();
let fs = put(&mut d, EntityKind::Spline(GSpline::from_fit_points(&fit)));
let l = line(&mut d, (10.0, -1.0), (19.8, 0.2));
ok(&mut d, con(K::Fix, &[w(l)]));
ok(&mut d, con(K::Smooth, &[w(fs), w(l)]));
let g = spl(&d, fs);
assert_eq!(g.fit.len(), 4);
assert!(g.fit[0].near(Vec2::new(19.8, 0.2), 1e-7));
let (lo, _) = g.domain();
assert!(g.eval(lo).near(g.fit[0], 1e-9));
assert!(all_satisfied(&d));
}
#[test]
fn block_reference_moves_rigidly() {
let mut d = Drawing::default();
let mut b = Block::new("BAR");
let h = d.new_handle();
b.entities.push(Entity { handle: h, common: Common::default(), kind: EntityKind::Line(DLine { a: v(0.0, 0.0), b: v(4.0, 0.0) }) });
d.blocks.insert("BAR".into(), Arc::new(b));
let ins = put(
&mut d,
EntityKind::Insert(Insert {
block: "BAR".into(),
insert: v(1.0, 1.0),
scale: v(1.0, 1.0),
rotation: 1.2,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
}),
);
assert_eq!(obj_dof(&d, ins), Some(3));
let p0 = point(&mut d, (10.0, 10.0));
let wall = line(&mut d, (10.0, 0.0), (10.0, 20.0));
ok(&mut d, con(K::Fix, &[w(p0)]));
ok(&mut d, con(K::Fix, &[w(wall)]));
// The insertion point onto p0 leaves the turn; the block's far end (rigid point 1) onto the
// wall takes it.
ok(&mut d, con(K::Coincident, &[w(ins), w(p0)]));
assert_eq!(obj_dof(&d, ins), Some(1));
ok(&mut d, con(K::Coincident, &[s(ins, Sub::Vertex(1)), w(wall)]));
let EntityKind::Insert(i) = &d.entity(ins).unwrap().kind else { panic!() };
assert!(i.insert.xy().near(Vec2::new(10.0, 10.0), 1e-7));
assert!((i.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-7, "{}", i.rotation);
// Both points again would be one equation too many.
let p1 = point(&mut d, (10.0, 14.0));
ok(&mut d, con(K::Fix, &[w(p1)]));
assert!(matches!(add(&mut d, con(K::Coincident, &[s(ins, Sub::Vertex(1)), w(p1)]), &SolveOptions::default()), Err(SolveError::Redundant { .. })));
assert_eq!(dof(&d, &[]).unwrap().status, DofStatus::Fully);
}
#[test]
fn hostile_new_geometry_never_panics() {
let mut d = Drawing::default();
let bad_e = ellipse(&mut d, (0.0, 0.0), (0.0, 0.0), f64::NAN, 0.0, 1.0);
let flat_e = ellipse(&mut d, (0.0, 0.0), (1e300, 0.0), 0.0, 0.0, 1.0);
let broken = put(&mut d, EntityKind::Spline(GSpline { degree: 7, knots: vec![f64::NAN; 3], control: vec![Vec2::ZERO; 2], ..Default::default() }));
let one = put(&mut d, EntityKind::Spline(GSpline::from_control(vec![Vec2::new(1.0, 1.0); 3], 2)));
let missing = put(
&mut d,
EntityKind::Insert(Insert {
block: "NOPE".into(),
insert: v(0.0, 0.0),
scale: v(0.0, f64::INFINITY),
rotation: f64::NAN,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
}),
);
let l = line(&mut d, (0.0, 0.0), (0.0, 0.0));
let hs = [bad_e, flat_e, broken, one, missing, l];
let kinds = [K::Coincident, K::Concentric, K::Tangent, K::Smooth, K::Horizontal, K::Fix, K::Equal, K::Symmetric, K::Radius];
let subs = [Sub::Whole, Sub::Start, Sub::End, Sub::Center, Sub::Vertex(0), Sub::Vertex(3), Sub::Vertex(u32::MAX)];
for k in kinds {
for (i, h) in hs.iter().enumerate() {
for sub in subs {
let refs = [s(*h, sub), w(hs[(i + 1) % hs.len()]), w(hs[(i + 2) % hs.len()])];
for n in 0..=3 {
let _ = add(&mut d, dim(k, &refs[..n], "1"), &SolveOptions::default());
}
}
}
}
let _ = solve(&mut d, &SolveOptions::default());
let _ = dof(&d, &hs);
let _ = dof(&d, &[Handle(0), Handle(u64::MAX)]);
}
/// Fit-point vertex constraints retain a known freedom count because they do not reconstruct the spline.
#[test]
fn vertex_constraints_on_large_fit_spline_do_not_charge_reconstruction() {
let mut d = Drawing::default();
let pts: Vec<_> = (0..500).map(|i| Vec2::new(i as f64, (i % 3) as f64)).collect();
let mut sp = GSpline::from_control(pts.clone(), 3);
sp.fit = pts;
let h = put(&mut d, EntityKind::Spline(sp));
for i in 0..5 {
let p = point(&mut d, (i as f64, (i % 3) as f64));
let mut c = con(K::Coincident, &[s(h, Sub::Vertex(i)), w(p)]);
c.id = i + 1;
d.constraints.push(c);
}
let report = dof(&d, &[]).unwrap();
assert_eq!(report.status, DofStatus::Under);
assert_eq!(report.dof, Some(1000));
}
+250
View File
@@ -0,0 +1,250 @@
//! Annotative scaling.
//!
//! An annotation scale ("1:50") says how many drawing units one paper unit stands for. The
//! drawing keeps a list of them (SCALELISTEDIT) and a current one (`CANNOSCALE`). An annotative
//! object (text, MText, dimension, multileader, hatch, block reference) stores its size as it
//! should measure on paper and the set of scales it supports ([`Common::anno_scales`]); in a view
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
//! at its viewport scale, and paper space itself at 1:1.
use serde::{Deserialize, Serialize};
use crate::{Common, Drawing, Entity, EntityKind};
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnnoScale {
pub name: String,
pub paper_units: f64,
pub drawing_units: f64,
}
/// The most scales a drawing's list or one object holds (hostile files and parameters).
pub const MAX_SCALES: usize = 1000;
impl AnnoScale {
pub fn new(name: &str, paper_units: f64, drawing_units: f64) -> Self {
AnnoScale { name: name.to_string(), paper_units, drawing_units }
}
/// The 1:1 scale.
pub fn unit() -> Self {
AnnoScale::new("1:1", 1.0, 1.0)
}
/// Both units finite and positive (and their ratio usable).
pub fn is_valid(&self) -> bool {
let ok = |v: f64| v.is_finite() && v > 0.0;
ok(self.paper_units) && ok(self.drawing_units) && ok(self.drawing_units / self.paper_units)
}
/// Drawing units per paper unit (1:50 → 50): what an annotative object's paper size is
/// multiplied by. 1 for an invalid scale.
pub fn factor(&self) -> f64 {
if self.is_valid() { self.drawing_units / self.paper_units } else { 1.0 }
}
/// Whether this scale has the ratio `factor` (drawing units per paper unit).
pub fn has_factor(&self, factor: f64) -> bool {
same_factor(self.factor(), factor)
}
}
/// Two scale factors are the same ratio (relative tolerance).
pub fn same_factor(a: f64, b: f64) -> bool {
(a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1e-12)
}
/// The default metric scale list.
pub fn metric_scales() -> Vec<AnnoScale> {
let mut v: Vec<AnnoScale> =
[1.0, 2.0, 4.0, 5.0, 8.0, 10.0, 16.0, 20.0, 30.0, 40.0, 50.0, 100.0].iter().map(|n| AnnoScale::new(&format!("1:{n}"), 1.0, *n)).collect();
v.extend([2.0, 4.0, 8.0, 10.0, 100.0].iter().map(|n| AnnoScale::new(&format!("{n}:1"), *n, 1.0)));
v
}
/// The default imperial scale list: the metric ratios, then the architectural inch-to-foot
/// scales.
pub fn imperial_scales() -> Vec<AnnoScale> {
let mut v = metric_scales();
let arch: [(&str, f64); 15] = [
("1/128\" = 1'-0\"", 1.0 / 128.0),
("1/64\" = 1'-0\"", 1.0 / 64.0),
("1/32\" = 1'-0\"", 1.0 / 32.0),
("1/16\" = 1'-0\"", 1.0 / 16.0),
("3/32\" = 1'-0\"", 3.0 / 32.0),
("1/8\" = 1'-0\"", 1.0 / 8.0),
("3/16\" = 1'-0\"", 3.0 / 16.0),
("1/4\" = 1'-0\"", 0.25),
("3/8\" = 1'-0\"", 0.375),
("1/2\" = 1'-0\"", 0.5),
("3/4\" = 1'-0\"", 0.75),
("1\" = 1'-0\"", 1.0),
("1-1/2\" = 1'-0\"", 1.5),
("3\" = 1'-0\"", 3.0),
("6\" = 1'-0\"", 6.0),
];
v.extend(arch.iter().map(|(n, p)| AnnoScale::new(n, *p, 12.0)));
v.push(AnnoScale::new("1'-0\" = 1'-0\"", 12.0, 12.0));
v
}
/// Kinds that can be annotative.
pub fn can_be_annotative(k: &EntityKind) -> bool {
matches!(
k,
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_) | EntityKind::Hatch(_) | EntityKind::Insert(_)
)
}
/// An annotative object: a kind that can be annotative, with at least one supported scale.
pub fn is_annotative(e: &Entity) -> bool {
!e.common.anno_scales.is_empty() && can_be_annotative(&e.kind)
}
/// Make `e` annotative (supporting `current` when it supports no scale yet) or not. Kinds that
/// can't be annotative are left alone.
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
if !on {
e.common.anno_scales.clear();
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
e.common.anno_scales.push(current.clone());
}
}
/// How an object draws in a view.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnnoDraw {
/// Not annotative: as stored.
Plain,
/// Annotative, at this factor (drawing units per paper unit).
Scaled(f64),
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
Hidden,
}
impl Common {
/// Whether these properties list a scale with the ratio `factor`.
pub fn supports_factor(&self, factor: f64) -> bool {
self.anno_scales.iter().any(|s| s.has_factor(factor))
}
/// Whether these properties list the scale named `name`.
pub fn supports_scale(&self, name: &str) -> bool {
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
}
}
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
/// object that doesn't support the view's scale shows at its first scale when `all_visible`.
pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
if !is_annotative(e) {
return AnnoDraw::Plain;
}
if e.common.supports_factor(view) {
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
}
match e.common.anno_scales.first() {
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
_ => AnnoDraw::Hidden,
}
}
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
/// from a stored geometry block. Other kinds come back unchanged.
pub fn anno_scaled(e: &Entity, f: f64) -> Entity {
let f = if f.is_finite() && f > 0.0 { f } else { 1.0 };
let mut out = e.clone();
match &mut out.kind {
EntityKind::Text(t) => t.height *= f,
EntityKind::MText(t) => {
t.height *= f;
t.width *= f;
if let Some(c) = &mut t.columns {
c.scale(f);
}
}
EntityKind::Dimension(dm) => {
dm.overrides.insert("scale".into(), serde_json::json!(f));
dm.block = None;
}
EntityKind::MLeader(m) => {
let land = m.landing;
m.arrow_size *= f;
m.dogleg *= f;
if let Some(t) = &mut m.text {
t.insert = land + (t.insert - land) * f;
t.height *= f;
t.width *= f;
if let Some(c) = &mut t.columns {
c.scale(f);
}
}
if let Some(ins) = &mut m.block {
ins.insert = land + (ins.insert - land) * f;
ins.scale = ins.scale * f;
}
}
EntityKind::Hatch(h) if !h.solid => h.scale *= f,
EntityKind::Insert(ins) => {
let o = ins.insert;
ins.scale = ins.scale * f;
ins.col_spacing *= f;
ins.row_spacing *= f;
for a in &mut ins.attribs {
a.text.insert = o + (a.text.insert - o) * f;
a.text.align_pt = a.text.align_pt.map(|p| o + (p - o) * f);
a.text.height *= f;
if let Some(ml) = &mut a.multiline {
ml.mtext.insert = o + (ml.mtext.insert - o) * f;
ml.mtext.height *= f;
ml.mtext.width *= f;
}
}
}
_ => {}
}
out
}
impl Drawing {
/// The scale named `name` in the drawing's scale list (case-insensitive).
pub fn anno_scale(&self, name: &str) -> Option<&AnnoScale> {
let n = name.trim();
self.scales.iter().find(|s| s.name.eq_ignore_ascii_case(n))
}
/// The current annotation scale (`CANNOSCALE`); 1:1 when it names no scale of the list.
pub fn current_anno_scale(&self) -> AnnoScale {
let name = self.header.str("CANNOSCALE", "1:1");
self.anno_scale(&name).filter(|s| s.is_valid()).cloned().unwrap_or_else(AnnoScale::unit)
}
/// Whether annotative objects that don't support the view's scale show (`ANNOALLVISIBLE`).
pub fn anno_all_visible(&self) -> bool {
self.header.i64("ANNOALLVISIBLE", 1) != 0
}
/// How top-level object `e` draws outside a viewport: in a layout's paper space at 1:1
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
if !is_annotative(e) {
return AnnoDraw::Plain;
}
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
return AnnoDraw::Scaled(1.0);
}
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
}
/// Whether new objects of this kind are annotative: text and MText with an annotative text
/// style, dimensions with an annotative dimension style, multileaders with an annotative
/// multileader style, hatches while `HPANNOTATIVE` is 1, references to annotative blocks.
pub fn annotative_by_style(&self, k: &EntityKind) -> bool {
match k {
EntityKind::Text(t) => self.text_style(&t.style).is_some_and(|s| s.annotative),
EntityKind::MText(t) => self.text_style(&t.style).is_some_and(|s| s.annotative),
EntityKind::Dimension(dm) => self.dim_style(&dm.style).is_some_and(|s| s.annotative),
EntityKind::MLeader(m) => self.mleader_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&m.style)).is_some_and(|s| s.annotative),
EntityKind::Hatch(_) => self.header.i64("HPANNOTATIVE", 0) != 0,
EntityKind::Insert(ins) => self.block(&ins.block).is_some_and(|b| b.annotative),
_ => false,
}
}
}
+347
View File
@@ -0,0 +1,347 @@
//! Associative arrays: the parameters an array keeps, and where they place its items.
//!
//! An associative array is a block reference to an anonymous block (`*U…`, the *array block*)
//! that holds one block reference per item. Each item refers to the array's *source block*
//! (another anonymous block holding the source objects) or, for items replaced with ARRAYEDIT,
//! to another block. Other programs see an ordinary block reference; CADCraft keeps the
//! parameters below on the array block ([`Block::array`](crate::Block)) so the items can be
//! regenerated when the array is edited.
//!
//! All positions are in the array block's coordinates: its origin is the array's base point,
//! which is where the array's block reference is inserted.
use cadcraft_geom::{Vec2, Vec3};
use serde::{Deserialize, Serialize};
use crate::{Common, Drawing, Entity, EntityKind, Insert, Lineweight};
/// Most items one array may have (items × rows × levels), whatever MAXARRAY says.
pub const MAX_ARRAY_ITEMS: u64 = 10_000_000;
fn one() -> u32 {
1
}
/// The parameters of an associative array.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArrayParams {
/// The source block the items refer to.
pub source: String,
pub kind: ArrayKind,
/// Levels: copies of the whole array along Z.
#[serde(default = "one")]
pub levels: u32,
#[serde(default)]
pub level_spacing: f64,
/// Items that refer to another block than the source (ARRAYEDIT REPlace).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub replaced: Vec<ReplacedItem>,
/// The source objects are out for editing (ARRAYEDIT Source, until ARRAYCLOSE). Not saved:
/// a drawing saved meanwhile keeps the objects as separate objects.
#[serde(skip)]
pub editing: Option<SourceEdit>,
}
/// ARRAYEDIT Source in progress: the array's source objects placed in the drawing for editing.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SourceEdit {
/// The array (block reference) being edited.
pub array: crate::Handle,
/// The item the objects were placed at: (i, j, level).
pub item: (u32, u32, u32),
/// The objects placed for editing.
pub objects: Vec<crate::Handle>,
/// Objects with this handle or above were drawn while editing; they join the source too.
pub first_new: u64,
}
/// Rectangular or polar placement.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ArrayKind {
Rect(RectArray),
Polar(PolarArray),
}
/// A rectangular array: columns along the axis angle, rows across it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RectArray {
pub cols: u32,
pub rows: u32,
pub col_spacing: f64,
pub row_spacing: f64,
/// Direction of the rows (the column axis), radians.
#[serde(default)]
pub axis_angle: f64,
/// Elevation added per row.
#[serde(default)]
pub row_elevation: f64,
}
/// A polar array: items around a centre, rows as rings further out.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PolarArray {
pub center: Vec2,
pub items: u32,
/// Angle to fill, degrees (positive = counterclockwise, ±360 = a full circle).
pub fill: f64,
/// Items are rotated as they go around (else they keep their orientation).
pub rotate: bool,
#[serde(default = "one")]
pub rows: u32,
/// Distance between rings, outwards from the centre.
#[serde(default)]
pub row_spacing: f64,
#[serde(default)]
pub row_elevation: f64,
}
/// An item that refers to another block. `i` is the column (rectangular) or the item around the
/// circle (polar), `j` the row.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplacedItem {
pub i: u32,
pub j: u32,
#[serde(default)]
pub level: u32,
pub block: String,
}
/// Where one item goes: its block reference's insertion point (the image of the array's base
/// point) and rotation (radians).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ArrayItem {
pub i: u32,
pub j: u32,
pub level: u32,
pub insert: Vec3,
pub rotation: f64,
}
impl ArrayParams {
/// Items along the first direction (columns or items around) and rows.
pub fn grid(&self) -> (u32, u32) {
match &self.kind {
ArrayKind::Rect(r) => (r.cols, r.rows),
ArrayKind::Polar(p) => (p.items, p.rows),
}
}
/// The number of items, saturating.
pub fn item_count(&self) -> u64 {
let (a, b) = self.grid();
u64::from(a).saturating_mul(u64::from(b)).saturating_mul(u64::from(self.levels))
}
/// Whether the parameters are usable: at least one item in every direction, at most
/// [`MAX_ARRAY_ITEMS`] in all, and finite numbers. Parameters read from files are checked
/// with this before they are kept.
pub fn is_valid(&self) -> bool {
let (a, b) = self.grid();
let nums = match &self.kind {
ArrayKind::Rect(r) => [r.col_spacing, r.row_spacing, r.axis_angle, r.row_elevation, 0.0, 0.0],
ArrayKind::Polar(p) => [p.center.x, p.center.y, p.fill, p.row_spacing, p.row_elevation, 0.0],
};
a >= 1
&& b >= 1
&& self.levels >= 1
&& self.item_count() <= MAX_ARRAY_ITEMS
&& !self.source.trim().is_empty()
&& nums.iter().chain(std::iter::once(&self.level_spacing)).all(|v| v.is_finite())
&& self.replaced.len() as u64 <= MAX_ARRAY_ITEMS
}
/// Where every item goes, row by row and level by level; `None` when the parameters are not
/// [valid](Self::is_valid).
pub fn items(&self) -> Option<Vec<ArrayItem>> {
if !self.is_valid() {
return None;
}
let n = usize::try_from(self.item_count()).ok()?;
let mut out = Vec::with_capacity(n);
for level in 0..self.levels {
let lz = self.level_spacing * f64::from(level);
match &self.kind {
ArrayKind::Rect(r) => {
let (ux, uy) = (Vec2::from_angle(r.axis_angle), Vec2::from_angle(r.axis_angle).perp());
for j in 0..r.rows {
for i in 0..r.cols {
let p = ux * (r.col_spacing * f64::from(i)) + uy * (r.row_spacing * f64::from(j));
out.push(ArrayItem { i, j, level, insert: p.to3(lz + r.row_elevation * f64::from(j)), rotation: 0.0 });
}
}
}
ArrayKind::Polar(p) => {
let total = p.fill.to_radians();
let full = (total.abs() - std::f64::consts::TAU).abs() < 1e-9;
let step = if full { total / f64::from(p.items.max(1)) } else { total / f64::from(p.items.saturating_sub(1).max(1)) };
// Rows move the items outwards: along the line from the centre to the base point.
let out_dir = {
let d = (Vec2::ZERO - p.center).normalized();
if d == Vec2::ZERO { Vec2::X } else { d }
};
for j in 0..p.rows {
let o = out_dir * (p.row_spacing * f64::from(j));
for i in 0..p.items {
let a = step * f64::from(i);
let at = o.rotate_about(p.center, a);
let rotation = if p.rotate { a } else { 0.0 };
out.push(ArrayItem { i, j, level, insert: at.to3(lz + p.row_elevation * f64::from(j)), rotation });
}
}
}
}
}
Some(out)
}
/// The block an item refers to: a replacement, else the source.
pub fn block_for(&self, i: u32, j: u32, level: u32) -> &str {
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())
}
/// 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).
pub fn item_entities(&self, d: &mut Drawing) -> Option<Vec<Entity>> {
let items = self.items()?;
let common = Common {
layer: "0".into(),
color: cadcraft_color::Color::ByBlock,
linetype: "ByBlock".into(),
lineweight: Lineweight::ByBlock,
..Common::default()
};
let mut out = Vec::with_capacity(items.len());
for it in items {
let ins = Insert {
block: self.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,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
};
out.push(Entity { handle: d.new_handle(), common: common.clone(), kind: EntityKind::Insert(ins) });
}
Some(out)
}
/// Take the block names from the array block's items `ents` (in the order [`items`]
/// lists them): the source block is whatever the items that are not replaced refer to, so
/// the parameters follow blocks renamed on paste, on INSERT of a file or by other programs
/// (which may rename anonymous blocks). `false` when the items don't match the parameters
/// (another program changed the block), so the array should be treated as a plain block.
///
/// [`items`]: Self::items
pub fn sync_names<'a>(&mut self, ents: impl Iterator<Item = &'a Entity>) -> bool {
let n = self.item_count();
let ents: Vec<&Entity> = ents.take(usize::try_from(n).unwrap_or(usize::MAX).saturating_add(1)).collect();
if ents.len() as u64 != n {
return false;
}
let Some(items) = self.items() else { return false };
// Index the replacement entries by placement so each item is matched in O(1) instead of
// scanning the whole `replaced` vector per item, which is quadratic when both the items
// and the replacements are large (CWE-407). Last entry wins, as `.rev().find` did.
let mut last_replaced: std::collections::HashMap<(u32, u32, u32), usize> = std::collections::HashMap::with_capacity(self.replaced.len());
for (idx, r) in self.replaced.iter().enumerate() {
last_replaced.insert((r.i, r.j, r.level), idx);
}
let mut source: Option<&str> = None;
for (it, e) in items.iter().zip(&ents) {
let EntityKind::Insert(ins) = &e.kind else { return false };
match last_replaced.get(&(it.i, it.j, it.level)).and_then(|&idx| self.replaced.get_mut(idx)) {
Some(r) => r.block.clone_from(&ins.block),
None => match source {
None => source = Some(&ins.block),
Some(s) if s.eq_ignore_ascii_case(&ins.block) => {}
Some(_) => return false,
},
}
}
if let Some(s) = source {
self.source = s.to_string();
}
true
}
}
impl Drawing {
/// The parameters of `e` when it is an associative array (a block reference to an array
/// block whose items match its parameters), with the block names its items use.
pub fn array_params(&self, e: &Entity) -> Option<ArrayParams> {
let EntityKind::Insert(i) = &e.kind else { return None };
let b = self.block(&i.block)?;
let mut p = b.array.clone()?;
p.sync_names(b.entities.iter().map(|e| e.as_ref())).then_some(p)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rect(cols: u32, rows: u32) -> ArrayParams {
ArrayParams {
source: "*U1".into(),
kind: ArrayKind::Rect(RectArray { cols, rows, col_spacing: 2.0, row_spacing: 3.0, axis_angle: 0.0, row_elevation: 0.0 }),
levels: 2,
level_spacing: 5.0,
replaced: Vec::new(),
editing: None,
}
}
#[test]
fn rect_items_go_column_row_level() {
let items = rect(3, 2).items().unwrap_or_default();
assert_eq!(items.len(), 12);
let last = items.last().copied().map(|i| (i.i, i.j, i.level, i.insert));
assert_eq!(last, Some((2, 1, 1, Vec3::new(4.0, 3.0, 5.0))));
}
#[test]
fn polar_rows_go_outwards() {
let p = ArrayParams {
source: "*U1".into(),
kind: ArrayKind::Polar(PolarArray {
center: Vec2::new(-10.0, 0.0),
items: 4,
fill: 360.0,
rotate: true,
rows: 2,
row_spacing: 1.0,
row_elevation: 0.0,
}),
levels: 1,
level_spacing: 0.0,
replaced: Vec::new(),
editing: None,
};
let items = p.items().unwrap_or_default();
assert_eq!(items.len(), 8);
// Item 1 of row 0 is a quarter turn round: base (0,0) → (-10,10).
assert!(items[1].insert.xy().near(Vec2::new(-10.0, 10.0), 1e-9));
// Row 1 starts one unit further out.
assert!(items[4].insert.xy().near(Vec2::new(1.0, 0.0), 1e-9));
}
#[test]
fn hostile_params_are_invalid() {
let mut p = rect(u32::MAX, u32::MAX);
assert!(!p.is_valid() && p.items().is_none());
p = rect(0, 1);
assert!(!p.is_valid());
p = rect(2, 2);
p.level_spacing = f64::NAN;
assert!(!p.is_valid());
}
}
+3 -2
View File
@@ -35,7 +35,7 @@ impl Sub {
"mid" | "midpoint" | "m" => Sub::Mid,
"center" | "centre" | "c" => Sub::Center,
_ => {
for (p, vertex) in [("vertex", true), ("segment", false), ("seg", false), ("v", true)] {
for (p, vertex) in [("vertex", true), ("segment", false), ("seg", false), ("s", false), ("v", true)] {
if let Some(n) = l.strip_prefix(p) {
let i: u32 = n.trim().parse().ok()?;
return Some(if vertex { Sub::Vertex(i) } else { Sub::Segment(i) });
@@ -99,7 +99,8 @@ pub enum ConstraintKind {
Horizontal,
Vertical,
Tangent,
/// G2 continuity; solved as tangency for now.
/// G2 continuity (common point, tangent and curvature) with a spline; tangency between
/// other curves.
Smooth,
Symmetric,
Equal,
+565
View File
@@ -0,0 +1,565 @@
//! Dynamic blocks made in another program, read from the data CADCraft keeps for them.
//!
//! A dynamic block's behaviour lives in objects CADCraft does not write itself and keeps as
//! [`Foreign`](crate::foreign::Foreign) data: the block's BLOCK_RECORD has an extension dictionary
//! whose `ACAD_ENHANCEDBLOCK` entry is an evaluation graph (`ACAD_EVALUATION_GRAPH`), and the
//! graph lists the block's *parameters* (a distance, a point, visibility states, a lookup…) and
//! *actions* (what changing a parameter does to the block's objects: stretch, move, look up…).
//! [`dynamic_block`] reads them into the model below without changing the kept data, so a drawing
//! saved again still carries them exactly as read.
//!
//! Every count and index here comes from the file: they are capped by the data actually present
//! and unknown or damaged objects are skipped, never trusted.
use std::collections::HashMap;
use cadcraft_geom::{Vec2, Vec3};
use serde::Serialize;
use crate::foreign::ForeignObject;
use crate::{Drawing, Handle, RawTag};
mod apply;
mod grips;
mod reference;
pub use apply::{drag_grip, set_property};
pub use grips::{DynGrip, GripPart, GripShape, grips};
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
/// Most objects one evaluation graph is read with.
const MAX_NODES: usize = 10_000;
/// Handles as hex strings in JSON, as commands report them.
fn hex<S: serde::Serializer>(h: &Handle, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&h.hex())
}
fn hexes<S: serde::Serializer>(hs: &[Handle], s: S) -> Result<S::Ok, S::Error> {
s.collect_seq(hs.iter().map(|h| h.hex()))
}
fn hex_vertices<S: serde::Serializer>(v: &[(Handle, Vec<i32>)], s: S) -> Result<S::Ok, S::Error> {
s.collect_seq(v.iter().map(|(h, i)| (h.hex(), i)))
}
/// A dynamic block's parameters and actions.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DynamicBlock {
pub parameters: Vec<Parameter>,
pub actions: Vec<Action>,
/// Graph members of types not modelled here (grips, constraints…), by DXF type.
pub other: Vec<String>,
/// The grip objects by graph id (parameters name their grips by id; visibility states list
/// the grips shown in them by object).
#[serde(skip)]
pub grip_objects: Vec<(i32, Handle)>,
}
/// One parameter: a property a reference to the block can change.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Parameter {
/// Its id in the evaluation graph (actions and lookups refer to parameters by it).
pub node: i32,
#[serde(serialize_with = "hex")]
pub handle: Handle,
/// The name the block editor shows ("Linear", "Visibility State").
pub element: String,
/// The parameter's properties appear in a reference's Properties palette.
pub show_properties: bool,
pub kind: ParameterKind,
/// Graph ids of its grips: a two-point parameter's base and end grips (0 for none), a
/// one-point parameter's grip. A reference's history records grip drags by these.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub grips: Vec<i32>,
}
/// What a parameter is, with its definition geometry in block coordinates.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum ParameterKind {
/// A distance between two points (Distance1).
Linear {
base: Vec3,
end: Vec3,
label: String,
description: String,
values: ValueSet,
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
from_midpoint: bool,
},
/// A distance and an angle from a base point.
Polar { base: Vec3, end: Vec3 },
/// Horizontal and vertical distances from a base point.
Xy { base: Vec3, end: Vec3 },
/// An angle about a base point.
Rotation { base: Vec3, end: Vec3 },
/// Aligns the reference with nearby geometry.
Alignment { base: Vec3, end: Vec3 },
/// Mirrors the objects about a reflection line.
Flip { base: Vec3, end: Vec3 },
/// A position (Position1).
Point { at: Vec3, label: String, description: String },
/// Named sets of visible objects.
Visibility {
at: Vec3,
label: String,
description: String,
#[serde(serialize_with = "hexes")]
controlled: Vec<Handle>,
states: Vec<VisibilityState>,
},
/// A named value chosen from a lookup table.
Lookup { at: Vec3, label: String, description: String },
/// Moves the block's base point.
BasePoint { at: Vec3 },
/// A parameter type not modelled yet.
Other { dxf_type: String },
}
impl ParameterKind {
/// The property name a reference shows ("Distance1", "Visibility1"), when it has one.
pub fn label(&self) -> Option<&str> {
match self {
ParameterKind::Linear { label, .. }
| ParameterKind::Point { label, .. }
| ParameterKind::Visibility { label, .. }
| ParameterKind::Lookup { label, .. } => Some(label),
_ => None,
}
}
}
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
/// objects are hidden).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VisibilityState {
pub name: String,
#[serde(serialize_with = "hexes")]
pub visible: Vec<Handle>,
/// The parameters and actions active in this state (their objects).
#[serde(serialize_with = "hexes")]
pub active: Vec<Handle>,
}
/// The values a distance or angle may take.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ValueSet {
/// Which of the limits below apply (see the methods).
pub flags: i32,
pub minimum: f64,
pub maximum: f64,
pub increment: f64,
/// The allowed values, for a list.
pub list: Vec<f64>,
}
impl ValueSet {
pub fn has_minimum(&self) -> bool {
self.flags & 1 != 0
}
pub fn has_maximum(&self) -> bool {
self.flags & 2 != 0
}
pub fn has_increment(&self) -> bool {
self.flags & 4 != 0
}
pub fn is_list(&self) -> bool {
self.flags & 8 != 0
}
}
/// One action: what changing parameters does to the block's objects.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Action {
pub node: i32,
#[serde(serialize_with = "hex")]
pub handle: Handle,
/// Its name in the block editor ("Stretch", "Lookup1").
pub name: String,
/// Where the block editor shows it.
pub at: Vec3,
/// The objects it acts on.
#[serde(serialize_with = "hexes")]
pub selection: Vec<Handle>,
/// Graph ids of the parameters it follows, with the parameter value each connection reads
/// ("EndXDelta").
pub connections: Vec<(i32, String)>,
pub kind: ActionKind,
}
/// What an action does.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum ActionKind {
/// Moves the vertices inside `frame` of the objects listed (all of an object not listed).
Stretch {
frame: Vec<Vec2>,
#[serde(serialize_with = "hex_vertices")]
vertices: Vec<(Handle, Vec<i32>)>,
multiplier: f64,
angle_offset: f64,
},
/// A table: each row sets the listed parameter values together.
Lookup {
columns: Vec<LookupColumn>,
rows: Vec<Vec<String>>,
},
/// Moves the objects by the change of the parameter values it follows.
Move {
multiplier: f64,
angle_offset: f64,
},
Scale,
Rotate,
Flip,
Array,
PolarStretch,
/// An action type not modelled yet.
Other {
dxf_type: String,
},
}
/// A lookup table column: the parameter value it reads or sets.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LookupColumn {
/// The parameter's graph id.
pub node: i32,
/// The value it stands for ("VisibilityState", "lookupString").
pub property: String,
/// A lookup property (shown on the reference) rather than an input.
pub lookup: bool,
/// What the reference shows when no row matches ("Custom").
pub unmatched: String,
}
/// The groups of an object split at its subclass markers (100): `(marker, groups after it)`.
fn sections(tags: &[RawTag]) -> Vec<(&str, &[RawTag])> {
let mut out: Vec<(&str, &[RawTag])> = Vec::new();
let mut start = 0;
let mut name = "";
for (i, t) in tags.iter().enumerate() {
if t.code == 100 {
out.push((name, tags.get(start..i).unwrap_or_default()));
name = t.value.as_str();
start = i + 1;
}
}
out.push((name, tags.get(start..).unwrap_or_default()));
out
}
/// The groups after subclass marker `marker`, empty when the object has none.
fn section<'a>(secs: &[(&str, &'a [RawTag])], marker: &str) -> &'a [RawTag] {
secs.iter().find(|(n, _)| n.eq_ignore_ascii_case(marker)).map_or(&[], |(_, t)| t)
}
/// Reads groups in order, as an object writes them.
struct Cursor<'a> {
tags: &'a [RawTag],
at: usize,
/// Groups scanned so far. A missing group neither moves the cursor nor ends the loops that
/// ask for it, so a hostile record could make nested counts rescan it again and again; past
/// `budget` every lookup fails at once and every count is zero.
work: usize,
budget: usize,
}
impl<'a> Cursor<'a> {
fn new(tags: &'a [RawTag]) -> Self {
Cursor { tags, at: 0, work: 0, budget: tags.len().saturating_mul(16).saturating_add(1024) }
}
/// The next group with `code` from here on (the cursor moves past it).
fn next(&mut self, code: i32) -> Option<&'a str> {
if self.work >= self.budget {
return None;
}
let rest = self.tags.get(self.at..)?;
let Some(rel) = rest.iter().position(|t| t.code == code) else {
self.work = self.work.saturating_add(rest.len().max(1));
return None;
};
self.work = self.work.saturating_add(rel + 1);
self.at += rel + 1;
self.tags.get(self.at - 1).map(|t| t.value.as_str())
}
fn string(&mut self, code: i32) -> String {
self.next(code).unwrap_or_default().to_string()
}
fn int(&mut self, code: i32) -> i32 {
self.next(code).and_then(|v| v.trim().parse().ok()).unwrap_or(0)
}
fn real(&mut self, code: i32) -> f64 {
self.next(code).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()).unwrap_or(0.0)
}
/// A count read from the file, capped by the groups left (each item needs at least one).
fn count(&mut self, code: i32) -> usize {
let n = usize::try_from(self.int(code)).unwrap_or(0).min(self.tags.len().saturating_sub(self.at));
if self.work >= self.budget { 0 } else { n }
}
fn handle(&mut self, code: i32) -> Option<Handle> {
self.next(code).and_then(Handle::parse_hex)
}
fn handles(&mut self, code: i32, n: usize) -> Vec<Handle> {
(0..n).filter_map(|_| self.handle(code)).collect()
}
/// A point written with codes `x`, `x + 10`, `x + 20`.
fn point(&mut self, x: i32) -> Vec3 {
let px = self.real(x);
let py = self.real(x + 10);
let at = self.at;
// Z is optional: only take it when it is the very next group.
let pz = match self.tags.get(at) {
Some(t) if t.code == x + 20 => self.real(x + 20),
_ => 0.0,
};
Vec3::new(px, py, pz)
}
}
/// The objects `xdict`'s `ACAD_ENHANCEDBLOCK` evaluation graph lists, when the dictionary has one.
fn graph_members<'a>(objects: &HashMap<Handle, &'a ForeignObject>, xdict: Handle) -> Option<Vec<&'a ForeignObject>> {
let dict = objects.get(&xdict)?;
let mut graph = None;
let mut tags = dict.tags.iter();
while let Some(t) = tags.next() {
if t.code == 3 && t.value.eq_ignore_ascii_case("ACAD_ENHANCEDBLOCK") {
graph = tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value));
break;
}
}
let graph = objects.get(&graph?).filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH"))?;
let members = section(&sections(&graph.tags), "AcDbEvalGraph").iter().filter(|t| t.code == 360).filter_map(|t| Handle::parse_hex(&t.value));
// Deduplicate member handles before resolving them: a graph can list the same member many
// times, and parsing each occurrence into its own owned parameter multiplies a single large
// record into gigabytes of retained allocations (CWE-400).
let mut seen = std::collections::HashSet::new();
Some(members.take(MAX_NODES).filter(|h| seen.insert(*h)).filter_map(|h| objects.get(&h).copied()).collect())
}
/// The dynamic block data of block `name` (any case; `*Model_Space` for a drawing that is a
/// block's own drawing), or `None` when it has none.
pub fn dynamic_block(d: &Drawing, name: &str) -> Option<DynamicBlock> {
let xdict = d.foreign.records.get(&("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()))?.xdict?;
let objects: HashMap<Handle, &ForeignObject> = d.foreign.objects.iter().map(|o| (o.handle, o)).collect();
let mut out = DynamicBlock::default();
for o in graph_members(&objects, xdict)? {
let secs = sections(&o.tags);
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
let element = Cursor::new(section(&secs, "AcDbBlockElement")).string(300);
let kind = o.kind.to_ascii_uppercase();
if kind.ends_with("PARAMETER") {
let show_properties = Cursor::new(section(&secs, "AcDbBlockParameter")).int(280) != 0;
let grips = grip_ids(&secs);
out.parameters.push(Parameter { node, handle: o.handle, element, show_properties, kind: parameter(&kind, &secs), grips });
} else if kind.ends_with("ACTION") {
out.actions.push(action(o.handle, node, element, &kind, &secs));
} else {
if kind.ends_with("GRIP") {
out.grip_objects.push((node, o.handle));
}
out.other.push(o.kind.clone());
}
}
Some(out)
}
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
/// base and end grips (91); after a one-point parameter's point, its grip (93).
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
let two = section(secs, "AcDbBlock2PtParameter");
if !two.is_empty() {
let mut c = Cursor::new(two);
c.point(1010);
c.point(1011);
let n = c.count(170).min(2);
return (0..n).map(|_| c.int(91)).collect();
}
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
c.point(1010);
c.next(93).and_then(|v| v.trim().parse().ok()).into_iter().collect()
}
fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
let two = || {
let mut c = Cursor::new(section(secs, "AcDbBlock2PtParameter"));
(c.point(1010), c.point(1011))
};
let one = || Cursor::new(section(secs, "AcDbBlock1PtParameter")).point(1010);
match kind {
"BLOCKLINEARPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockLinearParameter"));
let label = c.string(305);
let description = c.string(306);
let from_midpoint = Cursor::new(section(secs, "AcDbBlock2PtParameter")).int(177) == 1;
ParameterKind::Linear { base, end, label, description, values: value_set(&mut c), from_midpoint }
}
"BLOCKPOINTPARAMETER" => {
let mut c = Cursor::new(section(secs, "AcDbBlockPointParameter"));
ParameterKind::Point { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKVISIBILITYPARAMETER" => visibility(one(), section(secs, "AcDbBlockVisibilityParameter")),
"BLOCKLOOKUPPARAMETER" => {
let mut c = Cursor::new(section(secs, "AcDbBlockLookupParameter"));
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
let (base, end) = two();
match kind {
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
_ => ParameterKind::Flip { base, end },
}
}
other => ParameterKind::Other { dxf_type: other.to_string() },
}
}
/// A value set after a parameter's name and description: description (307), flags (96),
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
fn value_set(c: &mut Cursor) -> ValueSet {
c.next(307);
let flags = c.int(96);
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
let n = c.count(175);
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
ValueSet { flags, minimum, maximum, increment, list }
}
/// A visibility parameter: its name and description (301, 302), the objects it controls (93
/// count, 331 each), then each state (92 count): name (303), visible objects (94, 332) and the
/// parameters and actions active in it (95, 333).
fn visibility(at: Vec3, tags: &[RawTag]) -> ParameterKind {
let mut c = Cursor::new(tags);
let label = c.string(301);
let description = c.string(302);
let n = c.count(93);
let controlled = c.handles(331, n);
let states = (0..c.count(92))
.map(|_| {
let name = c.string(303);
let n = c.count(94);
let visible = c.handles(332, n);
let n = c.count(95);
VisibilityState { name, visible, active: c.handles(333, n) }
})
.collect();
ParameterKind::Visibility { at, label, description, controlled, states }
}
fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[RawTag])]) -> Action {
let mut c = Cursor::new(section(secs, "AcDbBlockAction"));
c.next(70);
let n = c.count(71);
let selection = c.handles(330, n);
let at = c.point(1010);
let (connections, kind) = match kind {
"BLOCKSTRETCHACTION" => stretch(section(secs, "AcDbBlockStretchAction")),
"BLOCKLOOKUPACTION" => (Vec::new(), lookup(section(secs, "AcDbBlockLookupAction"))),
"BLOCKMOVEACTION" => {
let tags = section(secs, "AcDbBlockMoveAction");
let mut c = Cursor::new(tags);
let (multiplier, angle_offset) = (c.real(140), c.real(141));
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
}
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
};
Action { node, handle, name, at, selection, connections, kind }
}
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let int = |code: i32| first(code).trim().parse().unwrap_or(0);
vec![(int(92), first(301)), (int(93), first(302))]
}
/// A stretch action: its two connections, the frame (72 count, 1011/1021 points), the objects
/// whose vertices it moves (73 count; each a 331 handle, a 74 count and 94 vertex indices), then
/// the distance multiplier (140) and angle offset (141).
fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
let connections = two_connections(tags);
let mut c = Cursor::new(tags);
let n = c.count(72);
let frame = (0..n)
.map(|_| {
let x = c.real(1011);
Vec2::new(x, c.real(1021))
})
.collect();
let objects = c.count(73);
let vertices = (0..objects)
.filter_map(|_| {
let h = c.handle(331)?;
let n = c.count(74);
Some((h, (0..n).map(|_| c.int(94)).collect()))
})
.collect();
c.next(75);
let (multiplier, angle_offset) = (c.real(140), c.real(141));
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
}
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
/// parameter value it stands for (304).
fn lookup(tags: &[RawTag]) -> ActionKind {
let mut c = Cursor::new(tags);
let rows = c.count(92);
let cols = c.count(93);
c.next(301);
let cells = rows.saturating_mul(cols).min(tags.len());
let flat: Vec<String> = (0..cells).map(|_| c.string(302)).collect();
let rows = flat.chunks(cols.max(1)).map(<[String]>::to_vec).collect();
let columns = (0..cols)
.map(|_| {
c.next(303);
let node = c.int(94);
let lookup = c.int(282) != 0;
let unmatched = c.string(305);
let property = c.string(304);
LookupColumn { node, property, lookup, unmatched }
})
.collect();
ActionKind::Lookup { columns, rows }
}
#[cfg(test)]
mod tests {
use super::*;
fn tag(code: i32, value: &str) -> RawTag {
RawTag { code, value: value.to_string() }
}
/// Counts that promise groups the record doesn't have: each nested loop would rescan the
/// record for them. The work budget keeps this linear in the record's size.
#[test]
fn hostile_counts_with_missing_groups_stay_linear() {
let n = 20_000;
let mut tags = vec![tag(93, "0"), tag(92, &n.to_string())];
tags.extend((0..n).map(|_| tag(94, &n.to_string())));
let ParameterKind::Visibility { states, .. } = visibility(Vec3::default(), &tags) else { panic!("a visibility parameter") };
assert!(states.len() <= n && states.iter().all(|s| s.visible.is_empty()));
let mut tags = vec![tag(73, &n.to_string())];
tags.extend((0..n).flat_map(|_| [tag(331, "1F"), tag(74, &n.to_string())]));
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
}
}
+966
View File
@@ -0,0 +1,966 @@
//! Changing a dynamic block reference's custom properties.
//!
//! A changed reference shows an anonymous block (`*U12`) made from its current one with the
//! change applied, and says so the way AutoCAD's own references do, so AutoCAD still reads it as
//! a reference to the dynamic block: the anonymous block's BLOCK_RECORD carries
//! `AcDbBlockRepBTag` xdata naming the dynamic block's record, each copied object keeps the
//! `AcDbBlockRepETag` xdata that pairs it with its object in the dynamic block, and the reference's
//! `AcDbBlockRepresentation` data holds its values (created when it had none) and its history
//! says what was done to it (AutoCAD replays the history when the dynamic block is redefined).
//!
//! What can change so far: a visibility state, a lookup value, a distance and a position, with
//! the stretch and move actions they drive and the lookups that follow. The other parameters'
//! actions come later.
use std::collections::{BTreeMap, HashMap, HashSet};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use super::{ActionKind, DynamicBlock, ParameterKind, Value, dynamic_block, reference};
use crate::foreign::{ForeignExtra, ForeignObject};
use crate::{Block, Drawing, Entity, EntityKind, Handle, RawTag};
/// Xdata application naming a copied object's object in the dynamic block (its element tag).
const ETAG: &str = "AcDbBlockRepETag";
/// Xdata application naming an anonymous block's dynamic block.
const BTAG: &str = "AcDbBlockRepBTag";
fn tag(code: i32, value: impl Into<String>) -> RawTag {
RawTag { code, value: value.into() }
}
/// The element tag (`AcDbBlockRepETag` 1071) of object `h`, if it has one.
fn etag(d: &Drawing, h: Handle) -> Option<i64> {
let x = &d.foreign.entities.get(&h)?.xdata;
let at = x.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ETAG))?;
x.iter().skip(at + 1).take_while(|t| t.code != 1001).find(|t| t.code == 1071).and_then(|t| t.value.trim().parse().ok())
}
/// Each object of `b` keyed by its element tag, or by its position when it has none.
fn by_tag(d: &Drawing, b: &Block) -> Vec<(i64, Handle)> {
b.entities.iter().enumerate().map(|(i, e)| (etag(d, e.handle).unwrap_or(i as i64 + 1_000_000), e.handle)).collect()
}
/// The file handle of block `name`'s BLOCK_RECORD, as the kept data refers to it.
fn record_handle(d: &Drawing, name: &str) -> Option<Handle> {
let key = name.to_ascii_uppercase();
d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == key).map(|(h, _)| *h)
}
/// The object entry `key` of dictionary `dict` refers to.
fn entry(d: &Drawing, dict: Handle, key: &str) -> Option<Handle> {
let o = d.foreign.objects.iter().find(|o| o.handle == dict)?;
let mut tags = o.tags.iter();
while let Some(t) = tags.next() {
if t.code == 3 && t.value.eq_ignore_ascii_case(key) {
return tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value));
}
}
None
}
/// Every entry of dictionary `dict`: (key, object).
fn entries(d: &Drawing, dict: Handle) -> Vec<(String, Handle)> {
let Some(o) = d.foreign.objects.iter().find(|o| o.handle == dict) else { return Vec::new() };
let mut out = Vec::new();
let mut key: Option<&str> = None;
for t in &o.tags {
match t.code {
3 => key = Some(&t.value),
350 | 360 => {
if let (Some(k), Some(h)) = (key.take(), Handle::parse_hex(&t.value)) {
out.push((k.to_string(), h));
}
}
_ => {}
}
}
out
}
/// A parameter's value as a change sets it (block coordinates).
#[derive(Clone, Debug, PartialEq)]
enum Val {
/// A visibility state or lookup value.
Text(String),
/// A point parameter's position.
Point(Vec3),
/// A two-point parameter's base and end points.
Points(Vec3, Vec3),
}
/// A parameter's current value on the reference: the value it was given, else the block's own.
fn current(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option<Val> {
let p = m.parameters.iter().find(|p| p.node == node)?;
let given = values.get(&node);
Some(match (&p.kind, given) {
(_, Some(Value::Text { value })) => Val::Text(value.clone()),
(_, Some(Value::Point { at })) => Val::Point(*at),
(_, Some(Value::Points { base, end })) => Val::Points(*base, *end),
(ParameterKind::Visibility { states, .. }, None) => Val::Text(states.first().map(|s| s.name.clone()).unwrap_or_default()),
(ParameterKind::Point { at, .. }, None) => Val::Point(*at),
(
ParameterKind::Linear { base, end, .. }
| ParameterKind::Polar { base, end }
| ParameterKind::Xy { base, end }
| ParameterKind::Rotation { base, end }
| ParameterKind::Alignment { base, end }
| ParameterKind::Flip { base, end },
None,
) => Val::Points(*base, *end),
_ => return None,
})
}
/// `v` as a value set allows it: the nearest listed value, a multiple of the increment from the
/// minimum, within the minimum and maximum.
fn allowed(set: &super::ValueSet, v: f64) -> f64 {
let mut v = v;
if set.is_list() && !set.list.is_empty() {
v = set.list.iter().copied().fold(f64::NAN, |best, x| if best.is_nan() || (x - v).abs() < (best - v).abs() { x } else { best });
}
if set.has_increment() && set.increment > 0.0 {
let from = if set.has_minimum() { set.minimum } else { 0.0 };
v = from + ((v - from) / set.increment).round() * set.increment;
}
if set.has_minimum() {
v = v.max(set.minimum);
}
if set.has_maximum() && set.maximum > 0.0 {
v = v.min(set.maximum);
}
v
}
/// A linear parameter's points for distance `dist`: the end point moves along the parameter, or
/// both points move apart from the midpoint.
fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool) -> (Vec3, Vec3) {
let dir = end - base;
let len = dir.len();
let u = if len > 1e-12 { dir * (1.0 / len) } else { Vec3::new(1.0, 0.0, 0.0) };
if from_midpoint {
let mid = (base + end) * 0.5;
(mid - u * (dist / 2.0), mid + u * (dist / 2.0))
} else {
(base, base + u * dist)
}
}
/// The changes one property change makes, before actions run: parameter values by graph id.
#[derive(Default)]
struct Plan {
set: BTreeMap<i32, Val>,
}
impl Plan {
/// Set the value a lookup table cell gives property `property` of parameter `node`.
fn cell(&mut self, m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32, property: &str, cell: &str) -> Result<(), String> {
let p = m.parameters.iter().find(|p| p.node == node).ok_or("A lookup table refers to a missing parameter.")?;
match (&p.kind, property.to_ascii_lowercase().as_str()) {
(_, "lookupstring") | (ParameterKind::Visibility { .. }, "visibilitystate") => {
self.set.insert(node, Val::Text(cell.to_string()));
}
(ParameterKind::Linear { from_midpoint, .. }, "updateddistance" | "distance") => {
let dist = cell
.trim()
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| format!("A lookup table gives \"{cell}\" for a distance."))?;
let Some(Val::Points(b, e)) = self.set.get(&node).cloned().or_else(|| current(m, values, node)) else { return Ok(()) };
let (b2, e2) = linear_points(b, e, dist, *from_midpoint);
self.set.insert(node, Val::Points(b2, e2));
}
(_, other) => return Err(format!("A lookup table sets {other}, which CADCraft can't change yet.")),
}
Ok(())
}
/// Lookup parameter `node` set to `value`: every lookup table that sets it gives its row's
/// inputs. A table without that value is left alone; none having it is an error.
fn lookup(&mut self, m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32, value: &str, skip: Option<usize>) -> Result<bool, String> {
let mut found = false;
for (i, a) in m.actions.iter().enumerate() {
let ActionKind::Lookup { columns, rows } = &a.kind else { continue };
if Some(i) == skip {
continue;
}
let Some(out) = columns.iter().position(|c| c.lookup && c.node == node) else { continue };
let Some(row) = rows.iter().find(|r| r.get(out).is_some_and(|v| v.trim().eq_ignore_ascii_case(value.trim()))) else { continue };
found = true;
for (c, cell) in columns.iter().zip(row) {
self.cell(m, values, c.node, &c.property, cell)?;
}
}
Ok(found)
}
/// After input property `property` of parameter `node` changed: a lookup table with that input
/// whose inputs (with the new value) match a row gives its lookup value, and the lookup's
/// other tables then set their inputs for that value (as AutoCAD does).
fn chain(&mut self, m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32, property: &str) -> Result<(), String> {
let read = |plan: &Plan, n: i32, prop: &str| -> Option<String> {
let v = plan.set.get(&n).cloned().or_else(|| current(m, values, n))?;
match (v, prop.to_ascii_lowercase().as_str()) {
(Val::Text(t), "visibilitystate" | "lookupstring") => Some(t),
(Val::Points(b, e), "updateddistance" | "distance") => Some(format!("{}", (e - b).len())),
_ => None,
}
};
for (i, a) in m.actions.iter().enumerate() {
let ActionKind::Lookup { columns, rows } = &a.kind else { continue };
if !columns.iter().any(|c| !c.lookup && c.node == node && c.property.eq_ignore_ascii_case(property)) {
continue;
}
let Some(out) = columns.iter().position(|c| c.lookup) else { continue };
let lookup_node = columns.get(out).map_or(0, |c| c.node);
let hit = rows.iter().find(|r| {
columns.iter().enumerate().filter(|(_, c)| !c.lookup).all(|(j, c)| match (r.get(j), read(self, c.node, &c.property)) {
(Some(cell), Some(v)) => same(cell, &v),
_ => false,
})
});
if let Some(v) = hit.and_then(|r| r.get(out)).cloned() {
self.set.insert(lookup_node, Val::Text(v.clone()));
self.lookup(m, values, lookup_node, &v, Some(i))?;
}
}
Ok(())
}
}
/// Whether table cell `cell` reads as `value` (numbers compare as numbers).
fn same(cell: &str, value: &str) -> bool {
match (cell.trim().parse::<f64>(), value.trim().parse::<f64>()) {
(Ok(a), Ok(b)) => (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0),
_ => cell.trim().eq_ignore_ascii_case(value.trim()),
}
}
/// A number typed for a property, in drawing units.
fn number(value: &str) -> Result<f64, String> {
value.trim().parse::<f64>().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("\"{value}\" is not a number."))
}
/// Set custom property `name` (as the Properties palette names it, any case) of dynamic block
/// reference `insert` to `value` (lengths and positions in drawing units, as Properties shows them).
pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> Result<(), String> {
let r = reference(d, insert).ok_or("Not a dynamic block reference.")?;
let m = dynamic_block(d, &r.definition).ok_or("Not a dynamic block reference.")?;
let EntityKind::Insert(ins) = &d.entity(insert).ok_or("No such object.")?.kind else { return Err("Not a block reference.".into()) };
let (sx, sy) = (ins.scale.x.abs().max(1e-12), ins.scale.y.abs().max(1e-12));
let block_base = d.block(&r.definition).map(|b| b.base).unwrap_or_default();
let want = name.trim();
// A point parameter's position is two properties, "Position1 X" and "Position1 Y".
let (label, axis) = match want.rsplit_once(' ') {
Some((l, a)) if a.eq_ignore_ascii_case("X") || a.eq_ignore_ascii_case("Y") => (l, Some(a.eq_ignore_ascii_case("X"))),
_ => (want, None),
};
let p = m
.parameters
.iter()
.find(|p| {
p.show_properties && p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(want) || (axis.is_some() && l.eq_ignore_ascii_case(label)))
})
.ok_or_else(|| format!("The reference has no property \"{name}\"."))?;
let mut plan = Plan::default();
match (&p.kind, axis) {
(ParameterKind::Visibility { states, label, .. }, _) => {
let s = states.iter().find(|s| s.name.eq_ignore_ascii_case(value.trim())).ok_or_else(|| {
format!("\"{value}\" is not a state of {label}: {}.", states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>().join(", "))
})?;
plan.set.insert(p.node, Val::Text(s.name.clone()));
plan.chain(&m, &r.values, p.node, "VisibilityState")?;
}
(ParameterKind::Lookup { label, .. }, _) => {
plan.set.insert(p.node, Val::Text(value.trim().to_string()));
if !plan.lookup(&m, &r.values, p.node, value, None)? {
return Err(format!("\"{value}\" is not a value of {label}."));
}
}
(ParameterKind::Linear { values, from_midpoint, .. }, None) => {
let typed = number(value)? / sx;
if typed <= 0.0 {
return Err(format!("{name} must be more than 0."));
}
let dist = allowed(values, typed);
if dist <= 0.0 {
return Err(format!("{name} must be more than 0."));
}
let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) };
let (b2, e2) = linear_points(b, e, dist, *from_midpoint);
plan.set.insert(p.node, Val::Points(b2, e2));
plan.chain(&m, &r.values, p.node, "UpdatedDistance")?;
}
(ParameterKind::Point { .. }, Some(is_x)) => {
let Some(Val::Point(at)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no position.")) };
let v = number(value)?;
let at = if is_x { Vec3::new(block_base.x + v / sx, at.y, at.z) } else { Vec3::new(at.x, block_base.y + v / sy, at.z) };
plan.set.insert(p.node, Val::Point(at));
}
_ => return Err(format!("CADCraft can't change {name} yet.")),
}
apply(d, insert, &r.definition, &r.values, &plan.set, p.node)
}
/// Drag grip `part` of parameter `node` of dynamic block reference `insert` to `to` (drawing
/// coordinates), as AutoCAD's dynamic grips do: a distance's end grip (or base grip) changes the
/// distance by the drag along the parameter, snapped to its value set (both ends move when the
/// distance is measured from its midpoint); a position grip moves the position. The actions and
/// lookups follow as for [`set_property`].
pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPart, to: Vec2) -> Result<(), String> {
use super::GripPart;
if !to.is_finite() {
return Err("Invalid point.".into());
}
let r = reference(d, insert).ok_or("Not a dynamic block reference.")?;
let m = dynamic_block(d, &r.definition).ok_or("Not a dynamic block reference.")?;
let EntityKind::Insert(ins) = &d.entity(insert).ok_or("No such object.")?.kind else { return Err("Not a block reference.".into()) };
let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default();
let q = ins.transform(base).inverse().ok_or("The reference has a zero scale.")?.apply(to);
let p = m.parameters.iter().find(|p| p.node == node).ok_or("The reference has no such parameter.")?;
let mut plan = Plan::default();
match (&p.kind, part) {
(ParameterKind::Linear { values, from_midpoint, label, .. }, GripPart::Base | GripPart::End) => {
let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) };
let len = (e - b).len();
if len < 1e-12 {
return Err(format!("{label} has no direction."));
}
let u = (e - b) * (1.0 / len);
let q = Vec3::new(q.x, q.y, b.z);
let raw = if *from_midpoint {
2.0 * (q - (b + e) * 0.5).dot(u).abs()
} else if part == GripPart::End {
(q - b).dot(u)
} else {
(e - q).dot(u)
};
let dist = allowed(values, raw);
if !(raw > 0.0 && dist > 0.0 && dist.is_finite()) {
return Err(format!("{label} must be more than 0."));
}
let (b2, e2) = match (from_midpoint, part) {
(true, _) => linear_points(b, e, dist, true),
(false, GripPart::Base) => (e - u * dist, e),
(false, _) => (b, b + u * dist),
};
plan.set.insert(node, Val::Points(b2, e2));
plan.chain(&m, &r.values, node, "UpdatedDistance")?;
}
(ParameterKind::Point { label, .. }, GripPart::At) => {
let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) };
plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z)));
}
_ => return Err("That grip can't be dragged.".into()),
}
apply(d, insert, &r.definition, &r.values, &plan.set, node)
}
/// The change of each parameter value an action can follow, by parameter graph id and the
/// connection's name ("EndXDelta", "XDelta"…), from `old` and `new` values.
fn delta(old: &Val, new: &Val, connection: &str) -> f64 {
let c = connection.to_ascii_lowercase();
let pick = |v: Vec3| if c.contains('x') { v.x } else { v.y };
match (old, new) {
(Val::Point(a), Val::Point(b)) => pick(*b - *a),
(Val::Points(ab, ae), Val::Points(bb, be)) => {
if c.starts_with("base") || c.starts_with("updatedbase") {
pick(*bb - *ab)
} else {
pick(*be - *ae)
}
}
_ => 0.0,
}
}
/// Move entity `e` by `v`: the listed vertices of a line or polyline, else the whole object.
fn move_entity(e: &mut Entity, vertices: Option<&[i32]>, v: Vec2) {
match (&mut e.kind, vertices) {
(EntityKind::LwPolyline(pl), Some(idx)) => {
for i in idx {
if let Some(p) = usize::try_from(*i).ok().and_then(|i| pl.vertices.get_mut(i)) {
p.p += v;
}
}
}
(EntityKind::Line(l), Some(idx)) => {
for i in idx {
match i {
0 => l.a = l.a + v.to3(0.0),
1 => l.b = l.b + v.to3(0.0),
_ => {}
}
}
}
_ => e.kind.transform(&Mat3::translate(v)),
}
}
/// Whether point `p` lies inside a stretch frame (two corners, or a polygon).
fn in_frame(frame: &[Vec2], p: Vec2) -> bool {
match frame {
[a, b] => p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y),
f if f.len() >= 3 => {
let mut inside = false;
let mut j = f.len() - 1;
for i in 0..f.len() {
let (Some(pi), Some(pj)) = (f.get(i), f.get(j)) else { break };
if (pi.y > p.y) != (pj.y > p.y) && p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x {
inside = !inside;
}
j = i;
}
inside
}
_ => true,
}
}
/// Give `insert` a new anonymous block with the plan's values applied (visibility states, and
/// the stretch and move actions of the changed parameters, with the parameters in their selections
/// carried along), and record the new values on it.
fn apply(
d: &mut Drawing,
insert: Handle,
definition: &str,
values: &BTreeMap<i32, Value>,
set: &BTreeMap<i32, Val>,
direct: i32,
) -> Result<(), String> {
let m = dynamic_block(d, definition).ok_or("Not a dynamic block reference.")?;
let EntityKind::Insert(ins) = &d.entity(insert).ok_or("No such object.")?.kind else { return Err("Not a block reference.".into()) };
let ins = ins.clone();
let def = d.block(definition).cloned().ok_or("The dynamic block is missing.")?;
let src = d.block(&ins.block).cloned().ok_or("The reference's block is missing.")?;
// The dynamic block's objects and the reference's copies of them, by element tag.
let def_tags: HashMap<Handle, i64> = by_tag(d, &def).into_iter().map(|(t, h)| (h, t)).collect();
let src_by_tag: HashMap<i64, Handle> = by_tag(d, &src).into_iter().collect();
let copy_of = |dh: &Handle| def_tags.get(dh).and_then(|t| src_by_tag.get(t)).copied();
// New values, starting from the change; actions add the parameters they carry along.
let mut new: BTreeMap<i32, Val> = set.clone();
let mut moves: HashMap<Handle, Vec<(Option<Vec<i32>>, Vec2)>> = HashMap::new();
let param_of: HashMap<Handle, i32> = m.parameters.iter().map(|p| (p.handle, p.node)).collect();
for a in &m.actions {
let changed: Vec<&(i32, String)> = a.connections.iter().filter(|(n, _)| set.contains_key(n)).collect();
if changed.is_empty() {
continue;
}
let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec<i32>)]) = match &a.kind {
ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices),
ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]),
_ => continue,
};
// The two connections give the change in x and y.
let comp = |i: usize| {
a.connections.get(i).map_or(0.0, |(n, conn)| match (set.get(n), current(&m, values, *n)) {
(Some(nv), Some(ov)) => delta(&ov, nv, conn),
_ => 0.0,
})
};
let mult = if mult == 0.0 { 1.0 } else { mult };
let v = Vec2::new(comp(0), comp(1)).rotate(angle) * mult;
if !(v.x.is_finite() && v.y.is_finite()) || (v.x == 0.0 && v.y == 0.0) {
continue;
}
// Index this action's vertex lists by handle once, and skip handles already handled in
// this action's selection, so a selection that repeats a handle does not re-scan the
// vertex list and re-clone its index vector per occurrence (CWE-400).
let vtx_by_handle: HashMap<Handle, &Vec<i32>> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect();
let mut handled: HashSet<Handle> = HashSet::new();
for h in &a.selection {
if !handled.insert(*h) {
continue;
}
if let Some(node) = param_of.get(h) {
// A parameter in the selection is carried along: its points in the frame. Which
// points are in it is decided where the dynamic block has them (AutoCAD evaluates
// the actions from the block itself, so a point another action has moved out of
// the frame still follows).
if set.contains_key(node) {
continue;
}
let Some(cur) = new.get(node).cloned().or_else(|| current(&m, values, *node)) else { continue };
let home = current(&m, &BTreeMap::new(), *node);
let shift = |p: Vec3, at: Option<Vec3>| {
if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p }
};
let moved = match (cur, home) {
(Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))),
(Val::Point(p), _) => Val::Point(shift(p, None)),
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))),
(Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)),
(t, _) => t,
};
new.insert(*node, moved);
continue;
}
let Some(c) = copy_of(h) else { continue };
let idx = vtx_by_handle.get(h).map(|i| (*i).clone());
moves.entry(c).or_default().push((idx, v));
}
}
// Visibility states.
let mut shown: HashMap<Handle, bool> = HashMap::new();
for (node, v) in &new {
let (Some(ParameterKind::Visibility { controlled, states, .. }), Val::Text(state)) =
(m.parameters.iter().find(|p| p.node == *node).map(|p| &p.kind), v)
else {
continue;
};
let visible: HashSet<Handle> =
states.iter().find(|s| s.name.eq_ignore_ascii_case(state)).map(|s| s.visible.iter().copied().collect()).unwrap_or_default();
for h in controlled {
shown.insert(*h, visible.contains(h));
}
}
let shown_copy: HashMap<Handle, bool> = shown.iter().filter_map(|(dh, v)| copy_of(dh).map(|c| (c, *v))).collect();
// The new anonymous block.
let name = d.anonymous_block_name("*U");
// AutoCAD's anonymous copies have no units of their own.
let mut b =
Block { name: name.clone(), anonymous: true, xref_path: None, array: None, units: 0, entities: crate::EntityStore::new(), ..(*src).clone() };
let mut copies: HashMap<Handle, Handle> = HashMap::new();
for e in src.entities.iter() {
copies.insert(e.handle, d.new_handle());
}
// How far each attribute definition moves (block coordinates): the reference's attribute of
// that tag moves with it, as AutoCAD moves it.
let attrib_moves: HashMap<String, Vec2> = src
.entities
.iter()
.filter_map(|e| match &e.kind {
EntityKind::AttDef(ad) => {
let v = moves.get(&e.handle).into_iter().flatten().fold(Vec2::ZERO, |acc, (_, v)| acc + *v);
(v != Vec2::ZERO).then(|| (ad.tag.to_ascii_uppercase(), v))
}
_ => None,
})
.collect();
for e in src.entities.iter() {
let Some(nh) = copies.get(&e.handle).copied() else { continue };
let mut c: Entity = (**e).clone();
c.handle = nh;
if let Some(v) = shown_copy.get(&e.handle) {
c.common.visible = *v;
}
for (idx, v) in moves.get(&e.handle).into_iter().flatten() {
move_entity(&mut c, idx.as_deref(), *v);
}
if let EntityKind::Hatch(h) = &mut c.kind {
for l in &mut h.loops {
l.sources = l.sources.iter().map(|s| copies.get(s).copied().unwrap_or(*s)).collect();
}
}
b.entities.push(c);
}
refill_hatches(&mut b);
let def_record = Some(record_handle(d, definition).unwrap_or_else(|| {
let h = d.new_handle();
let f = std::sync::Arc::make_mut(&mut d.foreign);
f.targets.insert(h, ("BLOCK_RECORD".to_string(), definition.to_ascii_uppercase()));
h
}));
let old = ins.block.clone();
d.blocks.insert(name.clone(), std::sync::Arc::new(b));
let f = std::sync::Arc::make_mut(&mut d.foreign);
for (old_h, new_h) in &copies {
if let Some(mut x) = f.entities.get(old_h).cloned() {
for t in &mut x.xdata {
if t.code == 1005 && Handle::parse_hex(&t.value) == Some(*old_h) {
t.value = new_h.hex();
}
}
x.xdict = None;
// Reactors within the block (an associative hatch's outline) follow to the copies;
// ones outside it are not ours.
x.reactors = x.reactors.iter().filter_map(|r| copies.get(r).copied()).collect();
f.entities.insert(*new_h, x);
}
}
if let Some(rec) = def_record {
let xdata = vec![tag(1001, BTAG), tag(1070, "1"), tag(1005, rec.hex())];
f.records.insert(("BLOCK_RECORD".into(), name.to_ascii_uppercase()), ForeignExtra { xdata, ..Default::default() });
}
// The block-to-drawing transform's linear part turns a block-coordinate move into the move of
// the reference's attribute.
let to_world = ins.transform(src.base.xy());
let origin = to_world.apply(Vec2::ZERO);
d.modify_entity(insert, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.block = name.clone();
for a in &mut i.attribs {
if let Some(v) = attrib_moves.get(&a.tag.to_ascii_uppercase()) {
let w = to_world.apply(*v) - origin;
let mut k = EntityKind::Text(a.text.clone());
k.transform(&Mat3::translate(w));
if let EntityKind::Text(t) = k {
a.text = t;
}
}
}
}
})
.map_err(|e| e.to_string())?;
let was = current(&m, values, direct);
record_values(d, insert, def_record, &m, &new, (direct, was.as_ref()));
drop_if_unused(d, &old);
Ok(())
}
/// 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) {
let outlines: HashMap<Handle, Vec<cadcraft_geom::PolyVertex>> = b
.entities
.iter()
.filter_map(|e| match &e.kind {
EntityKind::LwPolyline(pl) if pl.closed => Some((e.handle, pl.vertices.clone())),
_ => None,
})
.collect();
let hatches: Vec<Handle> = b.entities.iter().filter(|e| matches!(&e.kind, EntityKind::Hatch(h) if h.associative)).map(|e| e.handle).collect();
for h in hatches {
b.entities.modify(h, |e| {
if let EntityKind::Hatch(hh) = &mut e.kind {
for l in &mut hh.loops {
if let [s] = l.sources.as_slice()
&& let Some(vs) = outlines.get(s)
{
l.vertices.clone_from(vs);
}
}
}
});
}
}
/// The value records of the references to the dynamic block whose record is `def_record` (from
/// any one of them, by graph id): AutoCAD's layout of each record, class ids included.
fn templates(d: &Drawing, def_record: Handle) -> HashMap<String, Vec<RawTag>> {
let objects: HashMap<Handle, &ForeignObject> = d.foreign.objects.iter().map(|o| (o.handle, o)).collect();
let mut out: HashMap<String, Vec<RawTag>> = HashMap::new();
for rep in d.foreign.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("DICTIONARY")) {
// A representation dictionary whose data names this dynamic block.
let Some(rd) = entry(d, rep.handle, "AcDbRepData").and_then(|h| objects.get(&h)) else { continue };
if !rd.tags.iter().any(|t| t.code == 340 && Handle::parse_hex(&t.value) == Some(def_record)) {
continue;
}
let Some(values) = entry(d, rep.handle, "AppDataCache").and_then(|c| entry(d, c, "ACAD_ENHANCEDBLOCKDATA")) else { continue };
for (k, h) in entries(d, values) {
if let Some(x) = objects.get(&h).filter(|x| x.kind.eq_ignore_ascii_case("XRECORD")) {
out.entry(k).or_insert_with(|| x.tags.clone());
}
}
}
out
}
/// A dictionary object `h` owned by `owner` with `entries`.
fn dictionary(h: Handle, owner: Handle, entries: &[(&str, Handle)]) -> ForeignObject {
let mut tags = vec![tag(5, h.hex()), tag(330, owner.hex()), tag(100, "AcDbDictionary"), tag(280, "1"), tag(281, "1")];
for (k, v) in entries {
tags.push(tag(3, *k));
tags.push(tag(360, v.hex()));
}
ForeignObject { handle: h, kind: "DICTIONARY".into(), tags }
}
/// `tags` (a template's groups) as new record `h` owned by `owner`: the template's handle, owner
/// and reactors are not ours (inside reactor brackets, 102, everything goes).
fn own(mut tags: Vec<RawTag>, h: Handle, owner: Handle) -> Vec<RawTag> {
let mut inside = false;
tags.retain(|t| {
if t.code == 102 {
inside = t.value.starts_with('{');
return false;
}
!(inside || t.code == 5 || t.code == 330)
});
let at = tags.iter().position(|t| t.code == 100).unwrap_or(0);
tags.insert(at, tag(330, owner.hex()));
tags.insert(0, tag(5, h.hex()));
tags
}
/// Record values `set` (by parameter graph id) in `insert`'s representation data, and the direct
/// change (of parameter `direct`, from value `old`) in its history, creating them when the reference has none. A
/// new reference's data gets a record for everything other references of the dynamic block have
/// (AutoCAD keeps one for each parameter and stretch action), with its own values; with no other
/// reference to copy, a changed value gets a minimal record.
fn record_values(
d: &mut Drawing,
insert: Handle,
def_record: Option<Handle>,
m: &DynamicBlock,
set: &BTreeMap<i32, Val>,
(direct, old): (i32, Option<&Val>),
) {
let xdict = d.foreign.entities.get(&insert).and_then(|x| x.xdict);
let rep = xdict.and_then(|x| entry(d, x, "AcDbBlockRepresentation"));
let cache = rep.and_then(|r| entry(d, r, "AppDataCache"));
let data = cache.and_then(|c| entry(d, c, "ACAD_ENHANCEDBLOCKDATA"));
let templates = def_record.map(|r| templates(d, r)).unwrap_or_default();
let param = |node: i32| m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind);
let at = |node: i32| match param(node) {
Some(
ParameterKind::Visibility { at, .. }
| ParameterKind::Lookup { at, .. }
| ParameterKind::Point { at, .. }
| ParameterKind::BasePoint { at },
) => *at,
_ => Vec3::ZERO,
};
let mut objects: Vec<ForeignObject> = Vec::new();
let mut fresh: Vec<(String, Vec<RawTag>)> = Vec::new();
let (cache, data) = match (cache, data) {
(Some(c), Some(h)) => (c, h),
_ => {
// Create the representation: reference xdict ▸ AcDbBlockRepresentation ▸ AcDbRepData
// (the dynamic block's record) and AppDataCache ▸ ACAD_ENHANCEDBLOCKDATA.
let Some(rec) = def_record else { return };
let xd = xdict.unwrap_or_else(|| d.new_handle());
let (rep, rd, cache, data) = (d.new_handle(), d.new_handle(), d.new_handle(), d.new_handle());
objects.push(dictionary(rep, xd, &[("AcDbRepData", rd), ("AppDataCache", cache)]));
objects.push(ForeignObject {
handle: rd,
kind: "ACDB_BLOCKREPRESENTATION_DATA".into(),
tags: vec![tag(5, rd.hex()), tag(330, rep.hex()), tag(100, "AcDbBlockRepresentationData"), tag(70, "1"), tag(340, rec.hex())],
});
objects.push(dictionary(cache, rep, &[("ACAD_ENHANCEDBLOCKDATA", data)]));
objects.push(dictionary(data, cache, &[]));
// Every record the other references have, with this reference's values: its
// parameters' positions and defaults (lookups as Properties shows them); action
// records as they are.
let lookups: HashMap<String, String> = super::custom_properties(d, insert)
.map(|(_, ps)| ps.into_iter().map(|p| (p.name.to_ascii_uppercase(), p.value)).collect())
.unwrap_or_default();
let mut keys: Vec<&String> = templates.keys().collect();
keys.sort();
for k in keys {
let (Ok(node), Some(t)) = (k.parse::<i32>(), templates.get(k)) else { continue };
let mut tags = t.clone();
match param(node) {
Some(ParameterKind::Visibility { .. } | ParameterKind::Point { .. } | ParameterKind::BasePoint { .. }) => {
write_value(&mut tags, &Val::Point(at(node)));
}
Some(ParameterKind::Lookup { label, .. }) => {
write_value(&mut tags, &Val::Point(at(node)));
if let Some(v) = lookups.get(&label.to_ascii_uppercase()) {
write_value(&mut tags, &Val::Text(v.clone()));
}
}
_ => {}
}
if let Some(v) = current(m, &BTreeMap::new(), node) {
write_value(&mut tags, &v);
}
fresh.push((k.clone(), tags));
}
let f = std::sync::Arc::make_mut(&mut d.foreign);
match f.objects.iter_mut().find(|o| Some(o.handle) == xdict) {
Some(x) => {
x.tags.push(tag(3, "AcDbBlockRepresentation"));
x.tags.push(tag(360, rep.hex()));
}
None => {
objects.push(dictionary(xd, insert, &[("AcDbBlockRepresentation", rep)]));
f.entities.entry(insert).or_default().xdict = Some(xd);
}
}
(cache, data)
}
};
let existing: HashMap<String, Handle> = match objects.iter().find(|o| o.handle == data) {
Some(_) => HashMap::new(),
None => entries(d, data).into_iter().collect(),
};
let mut add: Vec<(String, Handle)> = Vec::new();
for (key, mut tags) in fresh {
if let Some(v) = key.parse::<i32>().ok().and_then(|n| set.get(&n)) {
write_value(&mut tags, v);
}
let h = d.new_handle();
objects.push(ForeignObject { handle: h, kind: "XRECORD".into(), tags: own(tags, h, data) });
add.push((key, h));
}
for (node, v) in set {
let key = node.to_string();
if add.iter().any(|(k, _)| *k == key) {
continue;
}
match existing.get(&key) {
Some(h) => {
let f = std::sync::Arc::make_mut(&mut d.foreign);
if let Some(x) = f.objects.iter_mut().find(|o| o.handle == *h) {
write_value(&mut x.tags, v);
}
}
None => {
let h = d.new_handle();
let mut tags = templates.get(&key).cloned().unwrap_or_else(|| {
let p = at(*node);
vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())]
});
write_value(&mut tags, v);
objects.push(ForeignObject { handle: h, kind: "XRECORD".into(), tags: own(tags, h, data) });
add.push((key, h));
}
}
}
// The history: AutoCAD replays it over the dynamic block (when the block is redefined), so
// it must say what was done to this reference.
let history = entry(d, cache, "ACAD_ENHANCEDBLOCKHISTORY").filter(|h| d.foreign.objects.iter().any(|o| o.handle == *h));
let mut new_history = None;
if let (Some(v), Some(p)) = (set.get(&direct), m.parameters.iter().find(|p| p.node == direct)) {
match history {
Some(h) => {
let f = std::sync::Arc::make_mut(&mut d.foreign);
if let Some(x) = f.objects.iter_mut().find(|o| o.handle == h) {
write_history(&mut x.tags, p, old, v);
}
}
None => {
let h = d.new_handle();
let mut tags = vec![tag(5, h.hex()), tag(330, cache.hex()), tag(100, "AcDbXrecord"), tag(280, "1"), tag(1070, "3")];
write_history(&mut tags, p, old, v);
objects.push(ForeignObject { handle: h, kind: "XRECORD".into(), tags });
new_history = Some(h);
}
}
}
let f = std::sync::Arc::make_mut(&mut d.foreign);
f.objects.extend(objects);
if let Some(x) = f.objects.iter_mut().find(|o| o.handle == data) {
for (k, h) in add {
x.tags.push(tag(3, k));
x.tags.push(tag(360, h.hex()));
}
}
if let (Some(h), Some(x)) = (new_history, f.objects.iter_mut().find(|o| o.handle == cache)) {
x.tags.push(tag(3, "ACAD_ENHANCEDBLOCKHISTORY"));
x.tags.push(tag(360, h.hex()));
}
}
/// Record the direct change of parameter `p` to `v` in a reference's history (groups `tags`):
/// after its header (`280 1`, `1070 3`), an entry per change: `1071` the id, `300` what, then
/// the value. A visibility state or lookup value goes by the property's name (`1` the text), as
/// does a distance (`40`, in block units: typed in Properties, it replaces its grips' drags); a
/// position as the drag of its grip, `GRIPLOC` with how far it is from where the dynamic block
/// has it (`11/21/31`), when the change moves it (from `old`). An entry for the same id is
/// replaced; a grip back in its place has none.
fn write_history(tags: &mut Vec<RawTag>, p: &super::Parameter, old: Option<&Val>, v: &Val) {
let grip = |id: i32, moved: Vec3| {
let home = moved.x.abs() < 1e-9 && moved.y.abs() < 1e-9 && moved.z.abs() < 1e-9;
let e = vec![
tag(1071, id.to_string()),
tag(300, "GRIPLOC"),
tag(11, moved.x.to_string()),
tag(21, moved.y.to_string()),
tag(31, moved.z.to_string()),
];
(id, if home { Vec::new() } else { e })
};
// Each grip with where it was, where it is and where the dynamic block has it.
let grips = |places: &[(Vec3, Vec3, Vec3)]| -> Vec<(i32, Vec<RawTag>)> {
p.grips
.iter()
.zip(places)
.filter(|(g, (was, is, _))| **g != 0 && (*was - *is).len() > 1e-9)
.map(|(g, (_, is, home))| grip(*g, *is - *home))
.collect()
};
let was = match old {
Some(Val::Point(q)) => Some(*q),
_ => None,
};
let changes: Vec<(i32, Vec<RawTag>)> = match (&p.kind, v) {
(ParameterKind::Visibility { label, .. } | ParameterKind::Lookup { label, .. }, Val::Text(t)) => {
vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(1, t.clone())])]
}
(ParameterKind::Linear { label, .. }, Val::Points(b, e)) => {
let mut c: Vec<(i32, Vec<RawTag>)> = p.grips.iter().filter(|g| **g != 0).map(|g| (*g, Vec::new())).collect();
c.push((p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, (*e - *b).len().to_string())]));
c
}
(ParameterKind::Point { at, .. }, Val::Point(q)) => grips(&[(was.unwrap_or(*at), *q, *at)]),
_ => return,
};
// The header, then the entries (each from its 1071).
let start = tags.iter().position(|t| t.code == 1071).unwrap_or(tags.len());
let mut entries: Vec<Vec<RawTag>> = Vec::new();
for t in tags.drain(start..) {
if t.code == 1071 || entries.is_empty() {
entries.push(Vec::new());
}
if let Some(e) = entries.last_mut() {
e.push(t);
}
}
let id = |e: &[RawTag]| e.first().filter(|t| t.code == 1071).and_then(|t| t.value.trim().parse::<i32>().ok());
entries.retain(|e| !changes.iter().any(|(c, _)| id(e) == Some(*c)));
entries.extend(changes.into_iter().map(|(_, e)| e).filter(|e| !e.is_empty()));
tags.extend(entries.into_iter().flatten());
}
/// Write value `v` into a value record's groups: its text (group 1), or its points in order over
/// the record's points (10/20/30), adding them when it has fewer.
fn write_value(tags: &mut Vec<RawTag>, v: &Val) {
let points: Vec<Vec3> = match v {
Val::Text(t) => {
match tags.iter_mut().find(|x| x.code == 1) {
Some(x) => x.value.clone_from(t),
None => tags.push(tag(1, t.clone())),
}
return;
}
Val::Point(p) => vec![*p],
Val::Points(b, e) => vec![*b, *e],
};
for (i, p) in points.iter().enumerate() {
// The i-th point's groups, else new ones before any text.
let find = |tags: &[RawTag], code: i32, n: usize| tags.iter().enumerate().filter(|(_, t)| t.code == code).nth(n).map(|(j, _)| j);
match (find(tags, 10, i), find(tags, 20, i)) {
(Some(jx), Some(jy)) => {
if let Some(t) = tags.get_mut(jx) {
t.value = p.x.to_string();
}
if let Some(t) = tags.get_mut(jy) {
t.value = p.y.to_string();
}
if let Some(t) = find(tags, 30, i).and_then(|jz| tags.get_mut(jz)) {
t.value = p.z.to_string();
}
}
_ => {
let at = tags.iter().position(|t| t.code == 1).unwrap_or(tags.len());
tags.splice(at..at, [tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())]);
}
}
}
}
/// Remove anonymous block `name` when nothing refers to it any more (the block a changed
/// reference used to show), with the data kept for its record.
fn drop_if_unused(d: &mut Drawing, name: &str) {
if !name.starts_with('*') {
return;
}
let refers = |e: &Entity| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(name));
let used = d.model.iter().any(|e| refers(e))
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| refers(e)))
|| d.blocks.values().any(|b| b.entities.iter().any(|e| refers(e)));
if used {
return;
}
if let Some(b) = d.blocks.remove(name) {
let f = std::sync::Arc::make_mut(&mut d.foreign);
f.records.remove(&("BLOCK_RECORD".to_string(), name.to_ascii_uppercase()));
f.records.remove(&("BLOCK".to_string(), name.to_ascii_uppercase()));
for e in b.entities.iter() {
f.entities.remove(&e.handle);
}
}
}
+215
View File
@@ -0,0 +1,215 @@
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
//!
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
use std::collections::{HashMap, HashSet};
use cadcraft_geom::{Vec2, Vec3};
use serde::Serialize;
use super::{DynamicBlock, ParameterKind, Value, custom_properties, dynamic_block, reference};
use crate::{Drawing, EntityKind, Handle};
/// Most grips listed for one reference.
const MAX_GRIPS: usize = 200;
/// Which of a parameter's points a grip is at.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum GripPart {
/// A distance's base point.
Base,
/// A distance's end point.
End,
/// A one-point parameter's point (a position, a visibility or lookup grip).
At,
}
impl GripPart {
pub fn name(self) -> &'static str {
match self {
GripPart::Base => "base",
GripPart::End => "end",
GripPart::At => "at",
}
}
pub fn from_name(s: &str) -> Option<GripPart> {
match s.trim().to_ascii_lowercase().as_str() {
"base" => Some(GripPart::Base),
"end" => Some(GripPart::End),
"at" => Some(GripPart::At),
_ => None,
}
}
}
/// How a grip looks and what it does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum GripShape {
/// An arrow pointing away from the distance: drag it to change the distance.
Linear,
/// A square: drag it to move the position.
Point,
/// A down-pointing triangle: click it for the property's choices.
List,
}
/// One grip of a dynamic block reference.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DynGrip {
/// The parameter's graph id.
pub node: i32,
pub part: GripPart,
pub shape: GripShape,
/// Where it is, in drawing coordinates.
#[serde(serialize_with = "point")]
pub at: Vec2,
/// The way an arrow points (a unit vector in drawing coordinates; zero for the others).
#[serde(serialize_with = "point")]
pub dir: Vec2,
/// The property it changes, as Properties names it.
pub property: String,
/// A list grip's choices.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub choices: Vec<String>,
}
/// Which ends of two-point parameter `node` the block's actions follow, as (base, end): a
/// connection to one point's change (BaseXDelta, EndYDelta, UpdatedEnd…) follows that end, one to
/// the value itself (a distance, an angle) follows both. None when no action is attached to the
/// parameter: its grips are all kept, as the block has them.
fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
let mut used: Option<(bool, bool)> = None;
for (n, name) in m.actions.iter().flat_map(|a| a.connections.iter()) {
if *n != node {
continue;
}
let c = name.to_ascii_lowercase();
let (base, end) = used.unwrap_or((false, false));
used = Some(if c.starts_with("base") || c.starts_with("updatedbase") {
(true, end)
} else if c.starts_with("end") || c.starts_with("updatedend") {
(base, true)
} else {
(true, true)
});
}
used
}
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
[p.x, p.y].serialize(s)
}
/// The grips of dynamic block reference `insert` (none when it is not one).
pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
let Some(r) = reference(d, insert) else { return Vec::new() };
let Some(m) = dynamic_block(d, &r.definition) else { return Vec::new() };
let Some(EntityKind::Insert(ins)) = d.entity(insert).map(|e| &e.kind) else { return Vec::new() };
let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default();
let xf = ins.transform(base);
let world = |p: Vec3| xf.apply(p.xy());
let toward = |p: Vec3, u: Vec3| {
let v = xf.apply(p.xy() + u.xy()) - xf.apply(p.xy());
if v.len() > 1e-12 { v * (1.0 / v.len()) } else { Vec2::ZERO }
};
// The grips the current visibility state shows (all of them without visibility states).
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
let mut shown_in_state: Option<HashSet<Handle>> = None;
let mut visibility_node = None;
for p in &m.parameters {
if let ParameterKind::Visibility { states, .. } = &p.kind {
let current = match r.values.get(&p.node) {
Some(Value::Text { value }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
_ => states.first(),
};
if let Some(s) = current {
shown_in_state = Some(s.active.iter().copied().collect());
}
visibility_node = Some(p.node);
break;
}
}
// A grip shows in the current visibility state when the state lists it, or lists its
// parameter (AutoCAD shows a listed parameter's grips though the grips aren't listed).
let param_handle: HashMap<i32, Handle> = m.parameters.iter().map(|p| (p.node, p.handle)).collect();
let shown = |node: i32, id: i32| {
id != 0
&& (Some(node) == visibility_node
|| shown_in_state
.as_ref()
.is_none_or(|a| objects.get(&id).is_some_and(|h| a.contains(h)) || param_handle.get(&node).is_some_and(|h| a.contains(h))))
};
let choices: HashMap<String, Vec<String>> =
custom_properties(d, insert).map(|(_, ps)| ps.into_iter().map(|p| (p.name.to_ascii_uppercase(), p.choices)).collect()).unwrap_or_default();
let mut out = Vec::new();
for p in &m.parameters {
let grip = |i: usize| p.grips.get(i).copied().unwrap_or(0);
match &p.kind {
ParameterKind::Linear { base, end, label, from_midpoint, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let u = e - b;
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
// An end no action follows has no grip (dragging it would change nothing); a
// distance from its midpoint moves both ends.
let used = match ends_used(&m, p.node) {
Some((base, end)) if !*from_midpoint => [base, end],
_ => [true, true],
};
for (i, part, at, way) in [(0, GripPart::Base, b, u * -1.0), (1, GripPart::End, e, u)] {
if used[i] && shown(p.node, grip(i)) {
let (at, dir) = (world(at), toward(at, way));
out.push(DynGrip { node: p.node, part, shape: GripShape::Linear, at, dir, property: label.clone(), choices: Vec::new() });
}
}
}
ParameterKind::Point { at, label, .. } => {
let at = match r.values.get(&p.node) {
Some(Value::Point { at }) => *at,
_ => *at,
};
if shown(p.node, grip(0)) {
let at = world(at);
out.push(DynGrip {
node: p.node,
part: GripPart::At,
shape: GripShape::Point,
at,
dir: Vec2::ZERO,
property: label.clone(),
choices: Vec::new(),
});
}
}
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
if shown(p.node, grip(0)) {
let at = world(*at);
out.push(DynGrip {
node: p.node,
part: GripPart::At,
shape: GripShape::List,
at,
dir: Vec2::ZERO,
property: label.clone(),
choices: list.clone(),
});
}
}
_ => {}
}
if out.len() >= MAX_GRIPS {
break;
}
}
out.retain(|g| g.at.is_finite());
out
}
+283
View File
@@ -0,0 +1,283 @@
//! Dynamic block references: which dynamic block a block reference shows, the values it was given
//! and the custom properties those make.
//!
//! A reference whose values differ from the block's own refers to an anonymous block (`*U12`)
//! holding the result, and its extension dictionary says what it is: `AcDbBlockRepresentation`
//! has `AcDbRepData` (pointing at the dynamic block's BLOCK_RECORD) and an `AppDataCache` whose
//! `ACAD_ENHANCEDBLOCKDATA` dictionary holds one XRECORD per parameter, keyed by its graph id, with
//! the value in block coordinates. A reference to the dynamic block itself has the block's values.
use std::collections::{BTreeMap, HashMap};
use cadcraft_geom::Vec3;
use serde::Serialize;
use super::{ActionKind, DynamicBlock, ParameterKind, dynamic_block};
use crate::foreign::ForeignObject;
use crate::{Drawing, EntityKind, Handle};
/// Most values one reference is read with.
const MAX_VALUES: usize = 10_000;
/// A parameter's value on one reference, in block coordinates.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Value {
/// A visibility state's name or a lookup value.
Text { value: String },
/// A point parameter's position.
Point { at: Vec3 },
/// A two-point parameter's points.
Points { base: Vec3, end: Vec3 },
}
/// A dynamic block reference.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Reference {
/// The dynamic block it shows (its name in the drawing).
pub definition: String,
/// The values it was given, by parameter graph id; parameters missing here have the block's
/// own values.
pub values: BTreeMap<i32, Value>,
}
/// One custom property of a reference, as the Properties palette shows it.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomProperty {
pub name: String,
pub value: String,
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
/// distance's list).
pub choices: Vec<String>,
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
/// position, or a lookup whose tables set only those.
pub editable: bool,
}
fn objects(d: &Drawing) -> HashMap<Handle, &ForeignObject> {
d.foreign.objects.iter().map(|o| (o.handle, o)).collect()
}
/// The object entry `key` of dictionary `dict` refers to.
fn entry(objects: &HashMap<Handle, &ForeignObject>, dict: Handle, key: &str) -> Option<Handle> {
let o = objects.get(&dict)?;
let mut tags = o.tags.iter();
while let Some(t) = tags.next() {
if t.code == 3 && t.value.eq_ignore_ascii_case(key) {
return tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value));
}
}
None
}
/// Every entry of dictionary `dict`: (key, object).
fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(String, Handle)> {
let Some(o) = objects.get(&dict) else { return Vec::new() };
let mut out = Vec::new();
let mut key: Option<&str> = None;
for t in &o.tags {
match t.code {
3 => key = Some(t.value.as_str()),
350 | 360 => {
if let (Some(k), Some(h)) = (key.take(), Handle::parse_hex(&t.value)) {
out.push((k.to_string(), h));
}
}
_ => {}
}
}
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
}
let num = |code: i32, i: usize| {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
match (point(0), point(1)) {
(Some(base), Some(end)) => Some(Value::Points { base, end }),
(Some(at), None) => Some(Value::Point { at }),
_ => None,
}
}
/// The dynamic block reference `insert` is, or `None` when it isn't one.
pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
let EntityKind::Insert(ins) = &d.entity(insert)?.kind else { return None };
let objects = objects(d);
let rep = d.foreign.entities.get(&insert).and_then(|x| x.xdict).and_then(|x| entry(&objects, x, "AcDbBlockRepresentation"));
let Some(rep) = rep else {
// No representation: a reference to a dynamic block with its own values.
return dynamic_block(d, &ins.block)
.is_some()
.then(|| Reference { definition: d.block(&ins.block).map_or_else(|| ins.block.clone(), |b| b.name.clone()), values: BTreeMap::new() });
};
let data = entry(&objects, rep, "AcDbRepData").and_then(|h| objects.get(&h).copied())?;
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
let (kind, name) = d.foreign.targets.get(&target)?;
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
dynamic_block(d, &definition)?;
let mut values = BTreeMap::new();
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
values.insert(node, v);
}
}
Some(Reference { definition, values })
}
/// A number as the drawing shows lengths (LUPREC decimals).
fn number(d: &Drawing, v: f64) -> String {
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
format!("{v:.prec$}")
}
/// Whether table cell `cell` reads as `value` (numbers compare as numbers).
fn same(cell: &str, value: &str) -> bool {
match (cell.trim().parse::<f64>(), value.trim().parse::<f64>()) {
(Ok(a), Ok(b)) => (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0),
_ => cell.trim().eq_ignore_ascii_case(value.trim()),
}
}
/// The current values of a reference's parameters, for evaluating its lookup tables.
struct Current<'a> {
m: &'a DynamicBlock,
values: &'a BTreeMap<i32, Value>,
}
impl Current<'_> {
/// Parameter `node`'s value of property `property`, as table cells write it.
fn property(&self, node: i32, property: &str) -> Option<String> {
let p = self.m.parameters.iter().find(|p| p.node == node)?;
let v = self.values.get(&node);
match (&p.kind, property.to_ascii_lowercase().as_str()) {
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => states.first().map(|s| s.name.clone()),
},
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
Some(format!("{}", (e - b).len()))
}
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => None,
},
_ => None,
}
}
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
/// current inputs, or the tables' "no match" name ("Custom") when they don't agree or a table
/// has no matching row. Also the values it may be set to.
fn lookup(&self, node: i32) -> (String, Vec<String>) {
let mut found: Option<Option<String>> = None;
let mut unmatched = String::from("Custom");
let mut choices: Vec<String> = Vec::new();
for a in &self.m.actions {
let ActionKind::Lookup { columns, rows } = &a.kind else { continue };
let Some(out) = columns.iter().position(|c| c.lookup && c.node == node) else { continue };
if rows.is_empty() {
continue;
}
if let Some(c) = columns.get(out) {
unmatched = c.unmatched.clone();
}
for r in rows {
if let Some(v) = r.get(out).filter(|v| !choices.contains(v)) {
choices.push(v.clone());
}
}
let hit = rows.iter().find(|r| {
columns.iter().enumerate().filter(|(_, c)| !c.lookup).all(|(i, c)| match (r.get(i), self.property(c.node, &c.property)) {
(Some(cell), Some(v)) => same(cell, &v),
_ => false,
})
});
let v = hit.and_then(|r| r.get(out).cloned());
found = Some(match found {
None => v,
Some(prev) if prev == v => prev,
Some(_) => None,
});
}
(found.flatten().unwrap_or(unmatched), choices)
}
}
/// The custom properties block reference `insert` shows (the Properties palette's Custom
/// section): its dynamic block's name and, in parameter order, each parameter shown in Properties
/// with its value. Lengths and positions are in drawing units (block units × the reference's
/// scale); positions are relative to the block's base point.
pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<CustomProperty>)> {
let r = reference(d, insert)?;
let EntityKind::Insert(ins) = &d.entity(insert)?.kind else { return None };
let m = dynamic_block(d, &r.definition)?;
let base = d.block(&r.definition).map(|b| b.base).unwrap_or_default();
let (sx, sy) = (ins.scale.x.abs(), ins.scale.y.abs());
let cur = Current { m: &m, values: &r.values };
let mut out = Vec::new();
for p in m.parameters.iter().filter(|p| p.show_properties) {
let v = r.values.get(&p.node);
match &p.kind {
ParameterKind::Linear { base: b, end: e, label, values, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
}
ParameterKind::Point { at, label, .. } => {
let at = match v {
Some(Value::Point { at }) => *at,
_ => *at,
};
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Visibility { label, states, .. } => {
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
}
ParameterKind::Lookup { label, .. } => {
let (value, choices) = cur.lookup(p.node);
let editable = lookup_sets_what_changes(&m, p.node);
out.push(CustomProperty { name: label.clone(), value, choices, editable });
}
_ => {}
}
}
Some((r.definition, out))
}
/// Whether every lookup table that sets lookup parameter `node` sets only what
/// [`super::set_property`] can apply with it: visibility states and distances.
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
let mut any = false;
for a in &m.actions {
let ActionKind::Lookup { columns, rows } = &a.kind else { continue };
if rows.is_empty() || !columns.iter().any(|c| c.lookup && c.node == node) {
continue;
}
any = true;
if !columns
.iter()
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
{
return false;
}
}
any
}
+429 -7
View File
@@ -6,6 +6,9 @@ use cadcraft_geom::{
};
use serde::{Deserialize, Serialize};
mod mline;
pub use mline::*;
/// A database handle (DXF group 5), unique per drawing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Handle(pub u64);
@@ -94,6 +97,17 @@ pub struct Common {
pub visible: bool,
pub thickness: f64,
pub extrusion: Vec3,
/// Named plot style: `ByLayer`, `ByBlock` or a style of the layout's named (`.stb`) plot
/// style table.
pub plot_style: String,
/// The annotation scales an annotative object supports (empty: not annotative).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub anno_scales: Vec<crate::AnnoScale>,
/// Other applications' extended data (xdata) as read from the drawing file: whole
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub xdata: Vec<RawTag>,
}
impl Default for Common {
@@ -108,6 +122,9 @@ impl Default for Common {
visible: true,
thickness: 0.0,
extrusion: Vec3::Z,
plot_style: "ByLayer".into(),
anno_scales: Vec::new(),
xdata: Vec::new(),
}
}
}
@@ -233,6 +250,9 @@ fn one() -> f64 {
fn standard() -> String {
"Standard".into()
}
mod helix;
pub use helix::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MText {
@@ -252,10 +272,69 @@ pub struct MText {
pub contents: String,
#[serde(default = "one")]
pub line_spacing: f64,
/// Line spacing style (DXF 73): Exactly (`true`) keeps `line_spacing` whatever the character
/// heights; At least (`false`, the default) lets taller characters push lines apart.
#[serde(default)]
pub line_spacing_exact: bool,
/// Columns the text flows through, each `width` wide (DXF 75/76/78/79/48/49/50); `None`:
/// one column.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub columns: Option<MTextColumns>,
}
fn attach_tl() -> u8 {
1
}
/// Static columns: a fixed number of columns of one height. Dynamic columns: as many columns
/// as the text needs, of one height (auto height) or each its own (manual heights).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MTextColumnType {
#[default]
Static,
Dynamic,
}
/// MTEXT columns (MTEXT Columns option, DXF Reference MTEXT groups 75–79, 48–50).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct MTextColumns {
#[serde(rename = "type")]
pub kind: MTextColumnType,
/// Number of columns (static columns: the columns there are).
pub count: u16,
/// Space between two columns.
pub gutter: f64,
/// Height of every column (static, and dynamic with auto height).
pub height: f64,
/// Dynamic columns: one height for all columns (`height`) instead of `heights`.
pub auto_height: bool,
/// Dynamic columns with manual heights: the height of each column.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub heights: Vec<f64>,
/// Columns run right to left.
pub flow_reversed: bool,
}
impl MTextColumns {
/// The width of `count` columns of `column_width` and their gutters.
pub fn total_width(&self, column_width: f64) -> f64 {
let n = f64::from(self.count.max(1));
column_width * n + self.gutter.max(0.0) * (n - 1.0)
}
/// The tallest column.
pub fn max_height(&self) -> f64 {
self.heights.iter().copied().fold(self.height, f64::max).max(0.0)
}
/// Scale every length (SCALE, block insertion).
pub fn scale(&mut self, s: f64) {
self.gutter *= s;
self.height *= s;
self.heights.iter_mut().for_each(|h| *h *= s);
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Attrib {
@@ -270,6 +349,98 @@ pub struct Attrib {
/// An attribute's own properties; each one left unset follows the attribute definition.
#[serde(default, skip_serializing_if = "AttribProps::is_empty")]
pub props: AttribProps,
/// A multiline attribute (DXF attribute type 2, or 4 for a definition): its text as
/// multiline text. `text.value` holds the plain text, which value edits change.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub multiline: Option<MultilineAttrib>,
/// Its other modes: Verify, Preset and Lock position.
#[serde(default, skip_serializing_if = "AttribModes::is_default")]
pub modes: AttribModes,
}
/// An attribute's modes beyond invisible and constant.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AttribModes {
/// Verify: the value is asked for twice when the block is inserted (DXF flag 4).
#[serde(default)]
pub verify: bool,
/// Preset: the default value is used without asking (DXF flag 8).
#[serde(default)]
pub preset: bool,
/// Lock position: the attribute can't be moved on its own within a reference (DXF group
/// 280 after the flags). A reference's attributes take it from their definitions.
#[serde(default)]
pub lock_position: bool,
}
impl AttribModes {
pub fn is_default(&self) -> bool {
*self == Self::default()
}
/// The modes of a reference's attribute made from a definition with these: AutoCAD keeps
/// only Lock position there.
pub fn for_reference(self) -> Self {
AttribModes { lock_position: self.lock_position, ..Self::default() }
}
}
/// The multiline text of a multiline attribute.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MultilineAttrib {
pub mtext: MText,
/// The plain text `mtext`'s contents read as: an attribute whose value differs was edited
/// since, and its value replaces the contents.
pub read_as: String,
}
impl MultilineAttrib {
/// This text placed by `m` (a block reference's transform, for its attribute made from a
/// definition).
pub fn transformed(&self, m: &Mat3) -> MultilineAttrib {
let mut k = EntityKind::MText(self.mtext.clone());
k.transform(m);
let mtext = if let EntityKind::MText(t) = k { t } else { self.mtext.clone() };
MultilineAttrib { mtext, read_as: self.read_as.clone() }
}
}
impl Attrib {
/// Move a multiline attribute's text by `m` along with the attribute (nothing for others).
pub fn transform_multiline(&mut self, m: &Mat3) {
if let Some(ml) = &mut self.multiline {
*ml = ml.transformed(m);
}
}
/// A multiline attribute's text as drawn and saved: its multiline text, with the contents
/// replaced by the value when the value was edited since it was read.
pub fn multiline_text(&self) -> Option<MText> {
let m = self.multiline.as_ref()?;
let mut t = m.mtext.clone();
if self.text.value != m.read_as {
t.contents = mtext_literal(&self.text.value);
}
Some(t)
}
}
/// `s` as MTEXT contents that read back as `s`: backslashes and braces escaped, line breaks as
/// paragraph breaks.
pub fn mtext_literal(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'{' => out.push_str("\\{"),
'}' => out.push_str("\\}"),
'\n' => out.push_str("\\P"),
'\r' => {}
c => out.push(c),
}
}
out
}
/// Properties set on one attribute of a block reference (an ATTRIB's layer, colour, linetype and
@@ -394,6 +565,89 @@ pub struct Dimension {
/// Associativity: which definition points follow which objects.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assoc: Vec<DimAssoc>,
/// Oblique extension lines, jogs, breaks and inspection frames.
#[serde(default, skip_serializing_if = "DimMarks::is_empty")]
pub marks: DimMarks,
}
/// What dimension edits add to a dimension's drawing: DIMEDIT Oblique, DIMJOGLINE, DIMJOGGED,
/// DIMBREAK and DIMINSPECT.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DimMarks {
/// Angle (radians) of the extension lines of a linear or aligned dimension; None =
/// perpendicular to the dimension line.
#[serde(skip_serializing_if = "Option::is_none")]
pub oblique: Option<f64>,
/// A jog on the dimension line of a linear or aligned dimension, at this point (DIMJOGLINE).
#[serde(skip_serializing_if = "Option::is_none")]
pub jog_line: Option<Vec3>,
/// A jogged radius dimension (DIMJOGGED).
#[serde(skip_serializing_if = "Option::is_none")]
pub jogged: Option<JoggedRadius>,
/// Gaps in the dimension and extension lines (DIMBREAK).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub breaks: Vec<DimBreak>,
/// Inspection frame, label and rate (DIMINSPECT).
#[serde(skip_serializing_if = "Option::is_none")]
pub inspect: Option<Inspection>,
}
impl DimMarks {
pub fn is_empty(&self) -> bool {
*self == DimMarks::default()
}
/// Transform the points and angles (part of [`EntityKind::transform`]).
fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
if let Some(a) = &mut self.oblique {
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
}
if let Some(j) = &mut self.jog_line {
t3(j);
}
if let Some(j) = &mut self.jogged {
t3(&mut j.center);
t3(&mut j.jog);
}
for b in &mut self.breaks {
t3(&mut b.at);
b.size *= s;
}
}
}
/// The definition of a jogged radius dimension: the dimension line starts at an overriding
/// centre and jogs on its way to the arc.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct JoggedRadius {
/// Where the dimension line starts instead of the true centre.
pub center: Vec3,
/// The middle of the jog.
pub jog: Vec3,
}
/// A gap in a dimension's lines: everything within `size / 2` of `at` is left out.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DimBreak {
pub at: Vec3,
pub size: f64,
/// Made by DIMBREAK Auto (recomputed by the next Auto) rather than picked by hand.
pub auto: bool,
}
/// An inspection dimension (DIMINSPECT).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Inspection {
/// Frame shape: 0 round ends, 1 angular ends, 2 none.
pub shape: u8,
/// Text left of the value ("" = none).
pub label: String,
/// Inspection rate right of the value ("" = none).
pub rate: String,
}
/// A dimension definition point that follows an object (associative dimensions).
@@ -456,6 +710,26 @@ pub struct MLeader {
pub style: String,
#[serde(default = "one")]
pub arrow_size: f64,
/// Leader lines are smooth curves through their points (leader type Spline). An empty
/// `leaders` is a multileader without a leader line (leader type None).
#[serde(default)]
pub spline: bool,
/// Block content in place of the text: a block reference placed at the landing.
#[serde(default)]
pub block: Option<Insert>,
}
impl MLeader {
/// Each leader line as drawn: through its points to the landing, smoothed for spline leaders.
pub fn leader_paths(&self) -> Vec<Vec<Vec2>> {
self.leaders
.iter()
.map(|l| {
let pts: Vec<Vec2> = l.iter().map(|v| v.xy()).chain(std::iter::once(self.landing.xy())).collect();
if self.spline && pts.len() > 2 { GSpline::from_fit_points(&pts).tessellate(1e-3) } else { pts }
})
.collect()
}
}
/// A hatch boundary loop: closed polyline with bulges.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -463,6 +737,10 @@ pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
/// hatch re-fills the loop from them when they change.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sources: Vec<Handle>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -537,6 +815,30 @@ pub struct Viewport {
/// Per-viewport layer colour overrides (VP Color in the Layer Properties Manager).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub layer_colors: Vec<(String, Color)>,
/// The paper-space entity whose outline clips the viewport (a closed polyline, circle,
/// ellipse or spline; DXF group 340). `None`: the rectangle `center`/`width`/`height`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<Handle>,
/// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space.
#[serde(default = "yes")]
pub on: bool,
}
impl Default for Viewport {
fn default() -> Self {
Viewport {
center: Vec3::ZERO,
width: 1.0,
height: 1.0,
view_center: Vec2::ZERO,
view_height: 1.0,
id: 0,
locked: false,
frozen_layers: Vec::new(),
layer_colors: Vec::new(),
clip: None,
on: true,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -609,12 +911,22 @@ impl Default for Image {
pub struct Wipeout {
pub boundary: Vec<Vec2>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableCell {
pub text: String,
#[serde(default)]
pub merged: Option<(u32, u32)>,
/// The cell's own cell style; empty: its row's.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub style: String,
/// A formula (`=Sum(A1:B3)`); `text` holds its value.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub formula: Option<String>,
/// The cell's own text height (DXF 140 in the cell record), before the table's scale;
/// `None`: its cell style's.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text_height: Option<f64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -633,10 +945,22 @@ pub struct Table {
/// The row after the title holds column headers.
#[serde(default)]
pub header: bool,
/// The cell style of each row; missing or empty: by position (Title, Header, Data).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub row_styles: Vec<String>,
/// Table breaking (TABLEBREAK): the table drawn in several parts.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub breaks: Option<crate::TableBreak>,
/// The CSV file the cells come from (DATALINK).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_link: Option<crate::DataLink>,
}
fn default_text_h() -> f64 {
0.18
}
mod region;
pub use region::*;
/// A raw DXF group: kept for round-tripping entities we do not model.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RawTag {
@@ -660,6 +984,7 @@ pub enum EntityKind {
LwPolyline(LwPolyline),
Polyline3d(Polyline3d),
Spline(GSpline),
Helix(Helix),
Ray(RayLine),
XLine(RayLine),
Text(Text),
@@ -667,16 +992,19 @@ pub enum EntityKind {
AttDef(Attrib),
Insert(Insert),
Dimension(Dimension),
MLine(MLine),
Leader(Leader),
MLeader(MLeader),
Hatch(Hatch),
Solid(Solid),
Trace(Solid),
Face3d(Face3d),
Region(Region),
Viewport(Viewport),
Image(Image),
Wipeout(Wipeout),
Table(Table),
Tolerance(crate::Tolerance),
Unknown(Unknown),
}
@@ -710,6 +1038,7 @@ impl EntityKind {
EntityKind::LwPolyline(_) => "Polyline",
EntityKind::Polyline3d(_) => "3D Polyline",
EntityKind::Spline(_) => "Spline",
EntityKind::Helix(_) => "Helix",
EntityKind::Ray(_) => "Ray",
EntityKind::XLine(_) => "Xline",
EntityKind::Text(_) => "Text",
@@ -717,16 +1046,19 @@ impl EntityKind {
EntityKind::AttDef(_) => "Attribute Definition",
EntityKind::Insert(_) => "Block Reference",
EntityKind::Dimension(_) => "Dimension",
EntityKind::MLine(_) => "MLine",
EntityKind::Leader(_) => "Leader",
EntityKind::MLeader(_) => "Multileader",
EntityKind::Hatch(_) => "Hatch",
EntityKind::Solid(_) => "2D Solid",
EntityKind::Trace(_) => "Trace",
EntityKind::Face3d(_) => "3D Face",
EntityKind::Region(_) => "Region",
EntityKind::Viewport(_) => "Viewport",
EntityKind::Image(_) => "Raster Image",
EntityKind::Wipeout(_) => "Wipeout",
EntityKind::Table(_) => "Table",
EntityKind::Tolerance(_) => "Tolerance",
EntityKind::Unknown(_) => "Proxy",
}
}
@@ -741,6 +1073,7 @@ impl EntityKind {
EntityKind::LwPolyline(_) => "LWPOLYLINE",
EntityKind::Polyline3d(_) => "POLYLINE",
EntityKind::Spline(_) => "SPLINE",
EntityKind::Helix(_) => "HELIX",
EntityKind::Ray(_) => "RAY",
EntityKind::XLine(_) => "XLINE",
EntityKind::Text(_) => "TEXT",
@@ -748,16 +1081,19 @@ impl EntityKind {
EntityKind::AttDef(_) => "ATTDEF",
EntityKind::Insert(_) => "INSERT",
EntityKind::Dimension(_) => "DIMENSION",
EntityKind::MLine(_) => "MLINE",
EntityKind::Leader(_) => "LEADER",
EntityKind::MLeader(_) => "MULTILEADER",
EntityKind::Hatch(_) => "HATCH",
EntityKind::Solid(_) => "SOLID",
EntityKind::Trace(_) => "TRACE",
EntityKind::Face3d(_) => "3DFACE",
EntityKind::Region(_) => "REGION",
EntityKind::Viewport(_) => "VIEWPORT",
EntityKind::Image(_) => "IMAGE",
EntityKind::Wipeout(_) => "WIPEOUT",
EntityKind::Table(_) => "ACAD_TABLE",
EntityKind::Tolerance(_) => "TOLERANCE",
EntityKind::Unknown(u) => u.dxf_type.as_str(),
}
}
@@ -788,6 +1124,7 @@ impl EntityKind {
v
}
EntityKind::Spline(s) => vec![Prim::Spline(s.clone())],
EntityKind::Helix(h) => vec![Prim::Spline(h.spline())],
EntityKind::Ray(r) => vec![Prim::Infinite { base: r.base.xy(), dir: r.dir.xy().normalized(), ray: true }],
EntityKind::XLine(r) => vec![Prim::Infinite { base: r.base.xy(), dir: r.dir.xy().normalized(), ray: false }],
EntityKind::Solid(s) | EntityKind::Trace(s) => {
@@ -799,6 +1136,7 @@ impl EntityKind {
let pts = [c[0].xy(), c[1].xy(), c[2].xy(), c[3].xy(), c[0].xy()];
pts.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect()
}
EntityKind::Region(r) => r.segments().into_iter().map(Prim::Seg).collect(),
EntityKind::Hatch(h) => {
h.loops.iter().flat_map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.segments()).map(Prim::Seg).collect()
}
@@ -823,13 +1161,16 @@ impl EntityKind {
EntityKind::AttDef(a) => vec![Prim::Point(a.text.insert.xy())],
EntityKind::Insert(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Dimension(d) => vec![Prim::Point(d.defpt.xy())],
EntityKind::MLine(m) => m.segments().into_iter().map(Prim::Seg).collect(),
EntityKind::MLeader(m) => m
.leaders
.iter()
.flat_map(|l| l.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(w.first()?.xy(), w.get(1)?.xy()))))))
.chain(m.block.iter().map(|b| Prim::Point(b.insert.xy())))
.collect(),
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Unknown(_) => Vec::new(),
}
}
@@ -900,21 +1241,33 @@ impl EntityKind {
p.const_width *= s;
}
EntityKind::Polyline3d(p) => p.points.iter_mut().for_each(t3),
EntityKind::Spline(sp) => {
for c in sp.control.iter_mut().chain(sp.fit.iter_mut()) {
*c = m.apply(*c);
}
EntityKind::Spline(sp) => sp.transform(m),
EntityKind::Helix(h) => {
let sp = m.apply(h.start_point().xy());
t3(&mut h.center);
h.base_radius *= s;
h.top_radius *= s;
h.height *= s;
h.start_angle = h.center.xy().angle_to(sp);
// Mirrored, the twist turns the other way.
h.ccw ^= mirror;
}
EntityKind::Ray(r) | EntityKind::XLine(r) => {
t3(&mut r.base);
r.dir = m.apply_vec(r.dir.xy()).normalized().to3(0.0);
}
EntityKind::Text(t) => transform_text(t, m, s, rot, mirror),
EntityKind::AttDef(a) => transform_text(&mut a.text, m, s, rot, mirror),
EntityKind::AttDef(a) => {
transform_text(&mut a.text, m, s, rot, mirror);
a.transform_multiline(m);
}
EntityKind::MText(t) => {
t3(&mut t.insert);
t.height *= s;
t.width *= s;
if let Some(c) = &mut t.columns {
c.scale(s);
}
t.rotation = cadcraft_geom::norm_angle(t.rotation + rot);
}
EntityKind::Insert(i) => {
@@ -929,6 +1282,7 @@ impl EntityKind {
}
for a in &mut i.attribs {
transform_text(&mut a.text, m, s, rot, false);
a.transform_multiline(m);
}
i.col_spacing *= s;
i.row_spacing *= s;
@@ -940,8 +1294,15 @@ impl EntityKind {
if let DimKind::Linear { rotation } = &mut d.kind {
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
}
d.marks.transform(&t3, rot, s, mirror);
d.block = None;
}
EntityKind::MLine(ml) => {
ml.vertices.iter_mut().for_each(|v| t3(&mut v.p));
ml.vertices.iter_mut().flat_map(|v| v.cuts.iter_mut()).for_each(|c| (c.start, c.end) = (c.start * s, c.end * s));
// Mirrored, the elements change sides.
ml.scale *= if mirror { -s } else { s };
}
EntityKind::Leader(l) => l.vertices.iter_mut().for_each(t3),
EntityKind::MLeader(ml) => {
for l in &mut ml.leaders {
@@ -951,6 +1312,18 @@ impl EntityKind {
if let Some(t) = &mut ml.text {
t3(&mut t.insert);
t.height *= s;
t.width *= s;
if let Some(c) = &mut t.columns {
c.scale(s);
}
}
if let Some(b) = &mut ml.block {
// Transformed exactly like a block reference.
let mut k = EntityKind::Insert(b.clone());
k.transform(m);
if let EntityKind::Insert(nb) = k {
*b = nb;
}
}
}
EntityKind::Hatch(h) => {
@@ -968,6 +1341,14 @@ impl EntityKind {
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(t3),
EntityKind::Face3d(f) => f.corners.iter_mut().for_each(t3),
EntityKind::Region(r) => {
for v in r.loops.iter_mut().flat_map(|l| l.vertices.iter_mut()) {
v.p = m.apply(v.p);
if mirror {
v.bulge = -v.bulge;
}
}
}
EntityKind::Viewport(v) => {
t3(&mut v.center);
v.width *= s;
@@ -980,17 +1361,33 @@ impl EntityKind {
}
EntityKind::Wipeout(w) => w.boundary.iter_mut().for_each(|p| *p = m.apply(*p)),
EntityKind::Table(t) => {
if let Some(b) = &mut t.breaks {
b.height *= s;
b.spacing *= s;
b.heights.iter_mut().for_each(|h| *h *= s);
b.offsets.iter_mut().for_each(|o| *o = m.apply_vec(*o));
}
t3(&mut t.insert);
t.col_widths.iter_mut().for_each(|w| *w *= s);
t.row_heights.iter_mut().for_each(|h| *h *= s);
t.text_height *= s;
}
EntityKind::Tolerance(t) => {
t3(&mut t.insert);
// Like text with MIRRTEXT = 0: a mirrored frame keeps reading left to right.
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(_) => {}
}
}
/// Grip points (editable defining points), in display order.
pub fn grips(&self) -> Vec<Vec2> {
// A broken table has a grip for each part.
if let EntityKind::Table(t) = self {
return t.grip_points();
}
match self {
EntityKind::Line(l) => vec![l.a.xy(), l.a.xy().mid(l.b.xy()), l.b.xy()],
EntityKind::Point(p) => vec![p.p.xy()],
@@ -1011,9 +1408,12 @@ impl EntityKind {
EntityKind::LwPolyline(p) => {
let mut g: Vec<Vec2> = Vec::new();
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
// Compute the segments once, not once per vertex: rebuilding the whole segment
// vector inside the loop is quadratic in the vertex count (CWE-407).
let segs = pl.segments();
for (i, v) in p.vertices.iter().enumerate() {
g.push(v.p);
if let Some(s) = pl.segments().get(i) {
if let Some(s) = segs.get(i) {
g.push(s.mid());
}
}
@@ -1027,12 +1427,14 @@ impl EntityKind {
s.fit.clone()
}
}
EntityKind::Helix(h) => vec![h.center.xy(), h.start_point().xy(), h.end_point().xy()],
EntityKind::Ray(r) | EntityKind::XLine(r) => vec![r.base.xy(), r.base.xy() + r.dir.xy()],
EntityKind::Text(t) => vec![t.justify_point()],
EntityKind::MText(t) => vec![t.insert.xy()],
EntityKind::AttDef(a) => vec![a.text.justify_point()],
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
EntityKind::MLine(m) => m.points(),
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
EntityKind::MLeader(m) => m.leaders.iter().flat_map(|l| l.iter().map(|v| v.xy())).chain(std::iter::once(m.landing.xy())).collect(),
EntityKind::Hatch(h) => {
@@ -1041,6 +1443,7 @@ impl EntityKind {
}
EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.iter().map(|c| c.xy()).collect(),
EntityKind::Face3d(f) => f.corners.iter().map(|c| c.xy()).collect(),
EntityKind::Region(r) => vec![r.bounds().center()],
EntityKind::Viewport(v) => {
let c = v.center.xy();
let h = Vec2::new(v.width / 2.0, v.height / 2.0);
@@ -1049,6 +1452,7 @@ impl EntityKind {
EntityKind::Image(i) => vec![i.insert.xy()],
EntityKind::Wipeout(w) => w.boundary.clone(),
EntityKind::Table(t) => vec![t.insert.xy()],
EntityKind::Tolerance(t) => vec![t.insert.xy()],
EntityKind::Unknown(_) => Vec::new(),
}
}
@@ -1067,3 +1471,21 @@ fn transform_text(t: &mut Text, m: &Mat3, s: f64, rot: f64, mirror: bool) {
// MIRRTEXT = 0 (the default): mirrored text keeps reading left to right.
t.rotation = cadcraft_geom::norm_angle(t.rotation + if mirror { 0.0 } else { rot });
}
#[cfg(test)]
mod grip_tests {
use super::*;
use cadcraft_geom::PolyVertex;
#[test]
fn polyline_grips_are_vertices_and_midpoints() {
// Grips are each vertex plus the midpoint of each segment; the segment vector is computed
// once rather than rebuilt per vertex (CWE-407, row 35).
let verts: Vec<PolyVertex> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
let e = EntityKind::LwPolyline(LwPolyline { vertices: verts, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false });
let g = e.grips();
// 3 vertices + 2 segment midpoints.
assert_eq!(g.len(), 5, "{g:?}");
assert!(g.contains(&Vec2::new(0.0, 0.0)) && g.contains(&Vec2::new(5.0, 0.0)));
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Helices (HELIX): a spiral round a vertical axis from a base radius to a top radius, drawn as
//! the cubic spline through points on it (DXF Reference: HELIX, a SPLINE with AcDbHelix data).
use cadcraft_geom::{FitOptions, KnotParam, Spline as GSpline, TAU, Vec2, Vec3};
use serde::{Deserialize, Serialize};
/// Most turns a helix has (as the reference program allows).
pub const MAX_HELIX_TURNS: f64 = 500.0;
/// Points on the helix per turn that its spline runs through.
const POINTS_PER_TURN: f64 = 8.0;
/// What stays fixed when the helix is edited (DXF group 280).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HelixConstrain {
TurnHeight,
Turns,
#[default]
Height,
}
impl HelixConstrain {
pub fn to_dxf(self) -> i64 {
match self {
HelixConstrain::TurnHeight => 0,
HelixConstrain::Turns => 1,
HelixConstrain::Height => 2,
}
}
pub fn from_dxf(v: i64) -> HelixConstrain {
match v {
0 => HelixConstrain::TurnHeight,
1 => HelixConstrain::Turns,
_ => HelixConstrain::Height,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Helix {
/// Centre of the base (the axis base point).
pub center: Vec3,
pub base_radius: f64,
pub top_radius: f64,
/// Along the axis (+Z); negative goes down.
pub height: f64,
pub turns: f64,
/// Angle of the start point from the centre, radians.
#[serde(default)]
pub start_angle: f64,
/// Twist: counter-clockwise seen from above (right-handed).
#[serde(default = "yes")]
pub ccw: bool,
#[serde(default)]
pub constrain: HelixConstrain,
}
fn yes() -> bool {
true
}
impl Helix {
/// The values made safe: finite, radii >= 0, turns within (0, 500].
pub fn sanitized(mut self) -> Helix {
let fin = |v: f64, d: f64| if v.is_finite() { v } else { d };
self.center = Vec3::new(fin(self.center.x, 0.0), fin(self.center.y, 0.0), fin(self.center.z, 0.0));
self.base_radius = fin(self.base_radius, 1.0).abs().min(1e12);
self.top_radius = fin(self.top_radius, self.base_radius).abs().min(1e12);
self.height = fin(self.height, 0.0).clamp(-1e12, 1e12);
self.turns = fin(self.turns, 3.0).clamp(1e-3, MAX_HELIX_TURNS);
self.start_angle = fin(self.start_angle, 0.0);
self
}
/// Distance between turns.
pub fn turn_height(&self) -> f64 {
if self.turns > 0.0 { self.height / self.turns } else { 0.0 }
}
/// The point at `t` (0 = start, 1 = end) along the helix.
pub fn point_at(&self, t: f64) -> Vec3 {
let sign = if self.ccw { 1.0 } else { -1.0 };
let a = self.start_angle + sign * TAU * self.turns * t;
let r = self.base_radius + (self.top_radius - self.base_radius) * t;
let p = Vec2::polar(self.center.xy(), r, a);
Vec3::new(p.x, p.y, self.center.z + self.height * t)
}
pub fn start_point(&self) -> Vec3 {
self.point_at(0.0)
}
pub fn end_point(&self) -> Vec3 {
self.point_at(1.0)
}
/// The points the spline runs through, evenly spaced in angle.
pub fn fit_points(&self) -> Vec<Vec3> {
let turns = if self.turns.is_finite() { self.turns.clamp(1e-3, MAX_HELIX_TURNS) } else { 1.0 };
let n = ((turns * POINTS_PER_TURN).ceil() as usize).max(4);
(0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect()
}
/// The helix as a cubic spline seen from above, and the height of each control point: the
/// spline through [`Helix::fit_points`] with evenly spaced knots, so the height, linear in
/// the parameter, is exact at each control point's Greville abscissa.
pub fn spline3(&self) -> (GSpline, Vec<f64>) {
let fit = self.fit_points();
let xy: Vec<Vec2> = fit.iter().map(|p| p.xy()).collect();
let sp = GSpline::fit_with(&xy, false, FitOptions { knots: KnotParam::Uniform, ..FitOptions::default() });
let (lo, hi) = sp.domain();
let span = if hi - lo > 1e-12 { hi - lo } else { 1.0 };
let p = sp.degree.max(1);
let z = (0..sp.control.len())
.map(|j| {
let g = (1..=p).map(|k| sp.knots.get(j + k).copied().unwrap_or(hi)).sum::<f64>() / p as f64;
self.center.z + self.height * ((g - lo) / span).clamp(0.0, 1.0)
})
.collect();
(sp, z)
}
/// The helix seen from above.
pub fn spline(&self) -> GSpline {
self.spline3().0
}
}
+428
View File
@@ -0,0 +1,428 @@
//! Multilines (MLINE) and multiline styles (MLINESTYLE): parallel lines — the style's
//! elements — run at fixed offsets along a path of vertices, with optional caps, joints and a
//! fill between the outermost elements (DXF Reference: MLINE entity, MLINESTYLE object).
//!
//! An [`MLine`] carries a copy of its style ([`MLine::def`]), so its geometry needs nothing
//! else from the drawing: snapping, selection and trimming work from the entity alone.
use cadcraft_color::Color;
use cadcraft_geom::{Arc as GArc, Line as GLine, PI, Segment, Vec2, Vec3};
use serde::{Deserialize, Serialize};
/// Most elements a multiline style has (as in the style dialog of the reference program).
pub const MAX_MLINE_ELEMENTS: usize = 16;
/// Most vertices of one multiline (hostile files).
pub const MAX_MLINE_VERTICES: usize = 100_000;
/// Most breaks per vertex (all elements together).
pub const MAX_MLINE_CUTS: usize = 1_000;
/// The style every drawing has.
pub const STANDARD_MLINE_STYLE: &str = "STANDARD";
/// One line of a multiline style: its offset from the style's zero line (+ = left of the
/// drawing direction), colour and linetype.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct MLineElement {
pub offset: f64,
pub color: Color,
pub linetype: String,
}
impl Default for MLineElement {
fn default() -> Self {
MLineElement { offset: 0.0, color: Color::ByLayer, linetype: "ByLayer".into() }
}
}
/// The caps at one end of a multiline.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct MLineCaps {
/// A line across all elements.
pub line: bool,
/// A half circle joining the outermost elements.
pub outer_arc: bool,
/// Half circles joining pairs of inner elements.
pub inner_arcs: bool,
/// Angle of the end against the drawing direction, radians (π/2 = square).
pub angle: f64,
}
impl Default for MLineCaps {
fn default() -> Self {
MLineCaps { line: false, outer_arc: false, inner_arcs: false, angle: PI / 2.0 }
}
}
/// A multiline style (MLSTYLE).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct MLineStyle {
pub name: String,
pub description: String,
/// Elements from the largest offset down.
pub elements: Vec<MLineElement>,
pub start_caps: MLineCaps,
pub end_caps: MLineCaps,
/// Lines across all elements at every vertex ("display joints").
pub joints: bool,
/// Fill colour between the outermost elements; `None` = no fill.
pub fill: Option<Color>,
}
impl Default for MLineStyle {
/// The STANDARD style: two lines one unit apart, no caps, no fill.
fn default() -> Self {
MLineStyle {
name: STANDARD_MLINE_STYLE.into(),
description: String::new(),
elements: vec![MLineElement { offset: 0.5, ..Default::default() }, MLineElement { offset: -0.5, ..Default::default() }],
start_caps: MLineCaps::default(),
end_caps: MLineCaps::default(),
joints: false,
fill: None,
}
}
}
impl MLineStyle {
/// The style with hostile values made safe: 1..=16 finite elements sorted by offset (largest
/// first), cap angles within 10°..170°.
pub fn sanitized(mut self) -> MLineStyle {
self.elements.retain(|e| e.offset.is_finite() && e.offset.abs() < 1e12);
self.elements.truncate(MAX_MLINE_ELEMENTS);
if self.elements.is_empty() {
self.elements.push(MLineElement::default());
}
self.elements.sort_by(|a, b| b.offset.total_cmp(&a.offset));
for c in [&mut self.start_caps, &mut self.end_caps] {
c.angle = if c.angle.is_finite() { c.angle.clamp(10f64.to_radians(), 170f64.to_radians()) } else { PI / 2.0 };
}
self
}
pub fn max_offset(&self) -> f64 {
self.elements.iter().map(|e| e.offset).fold(f64::NEG_INFINITY, f64::max).max(-1e12)
}
pub fn min_offset(&self) -> f64 {
self.elements.iter().map(|e| e.offset).fold(f64::INFINITY, f64::min).min(1e12)
}
}
/// Which line of the style runs through the picked points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MLineJust {
/// The element with the largest offset.
#[default]
Top,
/// The style's zero line.
Zero,
/// The element with the smallest offset.
Bottom,
}
impl MLineJust {
/// DXF group 70 of MLINE (and CMLJUST).
pub fn to_dxf(self) -> i64 {
match self {
MLineJust::Top => 0,
MLineJust::Zero => 1,
MLineJust::Bottom => 2,
}
}
pub fn from_dxf(v: i64) -> MLineJust {
match v {
1 => MLineJust::Zero,
2 => MLineJust::Bottom,
_ => MLineJust::Top,
}
}
pub fn name(self) -> &'static str {
match self {
MLineJust::Top => "Top",
MLineJust::Zero => "Zero",
MLineJust::Bottom => "Bottom",
}
}
}
/// A break in one element along the segment that starts at a vertex: distances from the
/// element's start on that segment (MLEDIT Cut).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct MLineCut {
pub element: usize,
pub start: f64,
pub end: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MLineVertex {
pub p: Vec3,
/// Breaks in the segment that starts here.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cuts: Vec<MLineCut>,
}
impl MLineVertex {
pub fn new(p: Vec3) -> Self {
MLineVertex { p, cuts: Vec::new() }
}
}
/// A multiline.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MLine {
/// Style name (the MLINESTYLE it was drawn with).
pub style: String,
/// The style's elements, caps, joints and fill as this multiline uses them.
#[serde(default)]
pub def: MLineStyle,
/// Element offsets are multiplied by this; negative flips the elements to the other side.
#[serde(default = "one")]
pub scale: f64,
#[serde(default)]
pub justification: MLineJust,
#[serde(default)]
pub closed: bool,
#[serde(default)]
pub no_start_caps: bool,
#[serde(default)]
pub no_end_caps: bool,
pub vertices: Vec<MLineVertex>,
}
fn one() -> f64 {
1.0
}
/// A multiline's drawn geometry.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MLineGeometry {
/// Element pieces: (element index into `def.elements`, from, to).
pub lines: Vec<(usize, Vec2, Vec2)>,
/// Caps and joints, drawn with the multiline's own properties.
pub caps: Vec<Segment>,
/// The fill between the outermost elements (even-odd loops); empty without fill.
pub fill: Vec<Vec<Vec2>>,
}
impl MLine {
/// A multiline through `pts` in style `def`.
pub fn new(def: &MLineStyle, pts: &[Vec2], closed: bool, just: MLineJust, scale: f64) -> MLine {
MLine {
style: def.name.clone(),
def: def.clone(),
scale,
justification: just,
closed,
no_start_caps: false,
no_end_caps: false,
vertices: pts.iter().map(|p| MLineVertex::new(p.to3(0.0))).collect(),
}
}
/// The offset the vertex path sits at, in style units.
pub fn ref_offset(&self) -> f64 {
match self.justification {
MLineJust::Top => self.def.max_offset(),
MLineJust::Zero => 0.0,
MLineJust::Bottom => self.def.min_offset(),
}
}
/// Each element's distance from the vertex path (+ = left of the drawing direction).
pub fn offsets(&self) -> Vec<f64> {
let r = self.ref_offset();
let s = if self.scale.is_finite() { self.scale } else { 1.0 };
self.def.elements.iter().map(|e| (e.offset - r) * s).collect()
}
pub fn points(&self) -> Vec<Vec2> {
self.vertices.iter().map(|v| v.p.xy()).collect()
}
/// Number of segments (the closing one included).
pub fn segment_count(&self) -> usize {
let n = self.vertices.len();
if n < 2 {
0
} else if self.closed {
n
} else {
n - 1
}
}
/// Unit direction of each segment (zero for a degenerate one).
pub fn directions(&self) -> Vec<Vec2> {
let pts = self.points();
let n = pts.len();
(0..self.segment_count())
.map(|i| (pts.get((i + 1) % n.max(1)).copied().unwrap_or_default() - pts.get(i).copied().unwrap_or_default()).normalized())
.collect()
}
/// The miter vector at each vertex: the element at offset `d` passes through `v + m * d`.
pub fn miters(&self) -> Vec<Vec2> {
let dirs = self.directions();
let n = self.vertices.len();
let nseg = dirs.len();
// A degenerate segment takes its neighbour's direction.
let dir = |i: usize| -> Vec2 {
(0..nseg).map(|k| dirs.get((i + k) % nseg.max(1)).copied().unwrap_or_default()).find(|d| *d != Vec2::ZERO).unwrap_or(Vec2::X)
};
let dir_back = |i: usize| -> Vec2 {
(0..nseg)
.map(|k| dirs.get((i + nseg - k % nseg) % nseg.max(1)).copied().unwrap_or_default())
.find(|d| *d != Vec2::ZERO)
.unwrap_or(Vec2::X)
};
let end = |d: Vec2, angle: f64| {
let u = d.rotate(angle);
let s = angle.sin();
if s.abs() < 1e-6 { d.perp() } else { u / s }
};
(0..n)
.map(|i| {
if nseg == 0 {
return Vec2::Y;
}
let open_end = !self.closed && (i == 0 || i + 1 == n);
if open_end {
return if i == 0 { end(dir(0), self.def.start_caps.angle) } else { end(dir_back(n - 2), PI - self.def.end_caps.angle) };
}
let d_in = dir_back((i + nseg - 1) % nseg);
let d_out = dir(i % nseg);
let (n1, n2) = (d_in.perp(), d_out.perp());
let b = (n1 + n2).normalized();
if b == Vec2::ZERO {
return n1;
}
// Keep sharp corners finite.
b / b.dot(n1).max(0.05)
})
.collect()
}
/// The drawn geometry: element pieces (breaks taken out), caps, joints and fill.
pub fn geometry(&self) -> MLineGeometry {
let mut g = MLineGeometry::default();
let pts = self.points();
let n = pts.len();
let nseg = self.segment_count();
if nseg == 0 || pts.iter().any(|p| !p.is_finite()) {
return g;
}
let miters = self.miters();
let offs = self.offsets();
let at = |k: usize, d: f64| pts.get(k % n).copied().unwrap_or_default() + miters.get(k % n).copied().unwrap_or_default() * d;
for k in 0..nseg {
let cuts = self.vertices.get(k).map(|v| v.cuts.as_slice()).unwrap_or(&[]);
for (e, d) in offs.iter().enumerate() {
let (a, b) = (at(k, *d), at(k + 1, *d));
let len = a.dist(b);
if len <= 1e-12 {
continue;
}
let dir = (b - a) / len;
for (s, t) in pieces(len, cuts.iter().filter(|c| c.element == e).map(|c| (c.start, c.end))) {
g.lines.push((e, a + dir * s, a + dir * t));
}
}
}
// Elements by offset, largest (leftmost) first.
let mut order: Vec<usize> = (0..offs.len()).collect();
order.sort_by(|a, b| offs.get(*b).copied().unwrap_or(0.0).total_cmp(&offs.get(*a).copied().unwrap_or(0.0)));
let (Some(&top), Some(&bottom)) = (order.first(), order.last()) else { return g };
let off = |e: usize| offs.get(e).copied().unwrap_or(0.0);
let across = |k: usize| Segment::Line(GLine::new(at(k, off(top)), at(k, off(bottom))));
if !self.closed {
for (k, caps, skip, start) in [(0, self.def.start_caps, self.no_start_caps, true), (n - 1, self.def.end_caps, self.no_end_caps, false)] {
if skip {
continue;
}
if caps.line && order.len() > 1 {
g.caps.push(across(k));
}
let pairs = order.len() / 2;
for i in 0..pairs {
if (i == 0 && !caps.outer_arc) || (i > 0 && !caps.inner_arcs) {
continue;
}
let (Some(&ea), Some(&eb)) = (order.get(i), order.get(order.len() - 1 - i)) else { continue };
let (a, b) = (at(k, off(ea)), at(k, off(eb)));
if let Some(arc) = half_circle(a, b, start) {
g.caps.push(arc);
}
}
}
}
if self.def.joints && order.len() > 1 {
let inner = if self.closed { 0..n } else { 1..n.saturating_sub(1) };
for k in inner {
g.caps.push(across(k));
}
}
if self.def.fill.is_some() {
let side = |e: usize| (0..n).map(|k| at(k, off(e))).collect::<Vec<Vec2>>();
if self.closed {
g.fill = vec![side(top), side(bottom)];
} else {
let mut poly = side(top);
poly.extend(side(bottom).into_iter().rev());
g.fill = vec![poly];
}
}
g
}
/// Segments of every element piece, cap and joint.
pub fn segments(&self) -> Vec<Segment> {
let g = self.geometry();
g.lines.iter().map(|(_, a, b)| Segment::Line(GLine::new(*a, *b))).chain(g.caps).collect()
}
}
/// The parts of `[0, len]` left after taking out the `gaps` (each `(start, end)`, any order).
fn pieces(len: f64, gaps: impl Iterator<Item = (f64, f64)>) -> Vec<(f64, f64)> {
let mut gaps: Vec<(f64, f64)> =
gaps.filter(|(a, b)| a.is_finite() && b.is_finite()).map(|(a, b)| (a.min(b).max(0.0), a.max(b).min(len))).filter(|(a, b)| b > a).collect();
gaps.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut out = Vec::new();
let mut from = 0.0;
for (a, b) in gaps {
if a > from + 1e-12 {
out.push((from, a));
}
from = f64::max(from, b);
}
if len > from + 1e-12 {
out.push((from, len));
}
out
}
/// A half circle from `a` to `b` bulging backwards (`start`) or forwards along the multiline.
fn half_circle(a: Vec2, b: Vec2, start: bool) -> Option<Segment> {
let r = a.dist(b) / 2.0;
if r <= 1e-12 {
return None;
}
let c = a.mid(b);
let (sa, sb) = (c.angle_to(a), c.angle_to(b));
// From the left element to the right one: counter-clockwise passes behind the start.
Some(if start { Segment::Arc { arc: GArc::new(c, r, sa, sb), ccw: true } } else { Segment::Arc { arc: GArc::new(c, r, sb, sa), ccw: false } })
}
impl crate::Drawing {
/// The multiline style named `name` (any case).
pub fn mline_style(&self, name: &str) -> Option<&MLineStyle> {
self.mline_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name.trim()))
}
/// The current multiline style (CMLSTYLE), STANDARD when it is missing.
pub fn current_mline_style(&self) -> MLineStyle {
let name = self.header.str("CMLSTYLE", STANDARD_MLINE_STYLE);
self.mline_style(&name).or_else(|| self.mline_style(STANDARD_MLINE_STYLE)).cloned().unwrap_or_default()
}
}
+130
View File
@@ -0,0 +1,130 @@
//! Regions (REGION): a closed planar area bounded by loops of lines and arcs. Outer loops add
//! area, island loops (holes) take it away; loops don't cross.
use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Segment, Vec2, point_in_polygon};
use serde::{Deserialize, Serialize};
use super::HatchLoop;
/// Most loops one region has (hostile files and edits).
pub const MAX_REGION_LOOPS: usize = 10_000;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Region {
/// Closed loops with bulges; `outer` false for islands.
pub loops: Vec<HatchLoop>,
}
/// Area properties of a region (MASSPROP), in drawing units.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RegionProps {
pub area: f64,
pub perimeter: f64,
pub bounds: Bounds2,
pub centroid: Vec2,
/// ∫y² dA and ∫x² dA about the origin.
pub ixx: f64,
pub iyy: f64,
/// ∫xy dA about the origin.
pub ixy: f64,
/// The same three about the centroid.
pub centroid_moments: [f64; 3],
}
impl Region {
/// A region bounded by one closed loop.
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
}
pub fn polylines(&self) -> Vec<Polyline> {
self.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect()
}
/// The boundary: every loop's lines and arcs.
pub fn segments(&self) -> Vec<Segment> {
self.polylines().iter().flat_map(Polyline::segments).collect()
}
/// Each loop as points, arcs within `tol`.
pub fn tessellate(&self, tol: f64) -> Vec<Vec<Vec2>> {
self.polylines().iter().map(|p| p.tessellate(tol)).collect()
}
pub fn bounds(&self) -> Bounds2 {
self.polylines().iter().fold(Bounds2::EMPTY, |b, p| b.union(&p.bounds()))
}
/// Outer loops' area less the islands'.
pub fn area(&self) -> f64 {
self.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.area().abs() * if l.outer { 1.0 } else { -1.0 }).sum()
}
pub fn perimeter(&self) -> f64 {
self.polylines().iter().map(Polyline::len).sum()
}
/// A chord tolerance fine enough for measuring: 1e-5 of the region's size.
fn fine_tol(&self) -> f64 {
let b = self.bounds();
if b.is_empty() { 1e-6 } else { ((b.width() + b.height()) * 1e-5).max(1e-12) }
}
/// Whether `p` lies inside the region (odd parity over its loops).
pub fn contains(&self, p: Vec2) -> bool {
self.tessellate(self.fine_tol()).iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1
}
/// Set each loop's `outer` flag from how deeply other loops enclose it: an even depth is
/// an outer loop, odd an island.
pub fn renest(&mut self) {
let polys = self.tessellate(self.fine_tol());
let depth: Vec<usize> = polys
.iter()
.enumerate()
.map(|(i, l)| {
let Some(p) = probe(l) else { return 0 };
polys.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count()
})
.collect();
for (l, d) in self.loops.iter_mut().zip(depth) {
l.outer = d % 2 == 0;
}
}
/// Area, perimeter, bounding box, centroid and second moments (outer loops counted
/// counter-clockwise, islands clockwise).
pub fn props(&self) -> RegionProps {
let tol = self.fine_tol();
let (mut a, mut cx, mut cy, mut ixx, mut iyy, mut ixy) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
for (l, pts) in self.loops.iter().zip(self.tessellate(tol)) {
let signed = cadcraft_geom::shoelace(&pts);
// Outer loops add, islands subtract, whatever way they run.
let flip = if (signed >= 0.0) == l.outer { 1.0 } else { -1.0 };
let n = pts.len();
for i in 0..n {
let (Some(p), Some(q)) = (pts.get(i), pts.get((i + 1) % n)) else { continue };
let c = (p.x * q.y - q.x * p.y) * flip;
a += c / 2.0;
cx += (p.x + q.x) * c / 6.0;
cy += (p.y + q.y) * c / 6.0;
ixx += (p.y * p.y + p.y * q.y + q.y * q.y) * c / 12.0;
iyy += (p.x * p.x + p.x * q.x + q.x * q.x) * c / 12.0;
ixy += (p.x * q.y + 2.0 * p.x * p.y + 2.0 * q.x * q.y + q.x * p.y) * c / 24.0;
}
}
let c = if a.abs() > 1e-300 { Vec2::new(cx / a, cy / a) } else { Vec2::ZERO };
// Shifted with the area of the same outline the moments were taken from.
let centroid_moments = [ixx - a * c.y * c.y, iyy - a * c.x * c.x, ixy - a * c.x * c.y];
RegionProps { area: self.area(), perimeter: self.perimeter(), bounds: self.bounds(), centroid: c, ixx, iyy, ixy, centroid_moments }
}
}
/// A point of a loop to test its nesting with: the middle of its first non-degenerate edge.
fn probe(l: &[Vec2]) -> Option<Vec2> {
let n = l.len();
(0..n).find_map(|i| {
let (a, b) = (*l.get(i)?, *l.get((i + 1) % n)?);
(a.dist(b) > 1e-12).then(|| (a + b) * 0.5).filter(|m| m.is_finite())
})
}
+132 -45
View File
@@ -48,40 +48,59 @@ fn blank(s: &str) -> bool {
s.replace("\\~", " ").chars().all(char::is_whitespace)
}
/// Approximate box of an MTEXT, from its attachment point, width and line count.
fn mtext_box(t: &crate::MText) -> Bounds2 {
let lines = t.contents.split("\\P").count().max(1);
let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1);
let mut w = if t.width > 0.0 { t.width } else { t.height * 0.8 * longest as f64 };
let mut h = t.height * 1.66 * lines as f64;
if let Some(c) = t.columns.as_ref().filter(|_| t.width > 0.0) {
// Columns side by side, the text flowing down each in turn.
w = c.total_width(t.width);
h = if c.max_height() > 0.0 { c.max_height() } else { h };
}
let (dx, dy) = match t.attach {
2 | 5 | 8 => (-w / 2.0, 0.0),
3 | 6 | 9 => (-w, 0.0),
_ => (0.0, 0.0),
};
let top = match t.attach {
4..=6 => h / 2.0,
7..=9 => h,
_ => 0.0,
};
let o = t.insert.xy();
let pts = [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)]
.map(|p| o + p.rotate(t.rotation));
Bounds2::from_points(pts)
}
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 {
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, &mut HashMap::new()),
}
}
bounds_in(d, e, depth, &mut HashMap::new())
}
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
/// by block name: every further reference to a block reuses them instead of expanding the block
/// again, so nested or self-referencing blocks cost one pass over each definition instead of one
/// per reference (which grows exponentially with the nesting depth).
fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String, Bounds2>) -> Bounds2 {
/// by block name and depth: every further reference to a block at that depth reuses them instead of
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
/// definition per depth instead of one per reference (which grows exponentially with the nesting
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
/// bounds must not stand in for a shallower reference to the same block (#706).
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 {
match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
EntityKind::Text(t) => text_box(t, t.value.chars().count()),
EntityKind::AttDef(a) => text_box(&a.text, a.tag.chars().count()),
EntityKind::MText(t) => {
let lines = t.contents.split("\\P").count().max(1);
let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1);
let w = if t.width > 0.0 { t.width } else { t.height * 0.8 * longest as f64 };
let h = t.height * 1.66 * lines as f64;
let (dx, dy) = match t.attach {
2 | 5 | 8 => (-w / 2.0, 0.0),
3 | 6 | 9 => (-w, 0.0),
_ => (0.0, 0.0),
};
let top = match t.attach {
4..=6 => h / 2.0,
7..=9 => h,
_ => 0.0,
};
let o = t.insert.xy();
let pts = [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)]
.map(|p| o + p.rotate(t.rotation));
Bounds2::from_points(pts)
}
EntityKind::MText(t) => mtext_box(t),
EntityKind::Insert(ins) => {
if depth >= MAX_BLOCK_DEPTH {
return Bounds2::EMPTY;
@@ -89,28 +108,34 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
// A reference to a missing block (an unloaded xref, a purged definition) or to an empty
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let Some(blk) = d.block(&ins.block) else { return Bounds2::EMPTY };
let m = ins.transform(blk.base.xy());
let inner = match blocks.get(&blk.name) {
Some(b) => *b,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks));
let mut b = Bounds2::EMPTY;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
Some(b) => *b,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
blocks.insert(blk.name.clone(), inner);
inner
};
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
if ins.cols > 1 || ins.rows > 1 {
let off =
Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1)))
.rotate(ins.rotation);
b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off)));
}
};
let mut b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
if ins.cols > 1 || ins.rows > 1 {
let off = Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1)))
.rotate(ins.rotation);
b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off)));
}
for a in &ins.attribs {
if !a.invisible {
b = b.union(&text_box(&a.text, a.text.value.chars().count()));
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
});
}
}
b
@@ -140,9 +165,21 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n))
&& depth < MAX_BLOCK_DEPTH
{
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
b = b.union(&bounds_in(d, be, depth + 1, blocks));
}
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
// block with branching or self-referencing children costs one pass per definition
// per depth, not one per reference (which grows exponentially) (CWE-400).
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
Some(cached) => *cached,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
b = b.union(&inner);
}
b
}
@@ -150,6 +187,13 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
let mut b = Bounds2::from_points(m.leaders.iter().flatten().map(|v| v.xy()).chain(std::iter::once(m.landing.xy())));
if let Some(t) = &m.text {
b.add(t.insert.xy());
if !blank(&t.contents) {
b = b.union(&mtext_box(t));
}
}
if let Some(ins) = &m.block {
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
b = b.union(&bounds_in(d, &be, depth, blocks));
}
b
}
@@ -158,6 +202,8 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
let h: f64 = t.row_heights.iter().sum();
Bounds2::new(t.insert.xy(), t.insert.xy() + Vec2::new(w, -h))
}
// Text widths estimated like `text_box`; the renderer measures the font.
EntityKind::Tolerance(t) => t.layout(d, &|s, h| h * 0.9 * s.chars().count() as f64).bounds,
EntityKind::Image(i) => {
let o = i.insert.xy();
let u = i.u.xy() * i.size.x;
@@ -283,8 +329,49 @@ mod tests {
#[test]
fn right_justified_attdef_is_left_of_alignment_point() {
let text = text(HAlign::Right, VAlign::Baseline);
let a = crate::Attrib { tag: "HELLO".into(), text, invisible: false, constant: false, prompt: String::new(), props: Default::default() };
let a = crate::Attrib {
tag: "HELLO".into(),
text,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let b = bounds(EntityKind::AttDef(a));
assert!(b.min.x <= -4.4 && b.max.x < 1.0);
}
#[test]
fn multileader_text_is_inside_its_bounds() {
let mtext = crate::MText {
insert: Vec3::new(25.45, 0.0, 0.0),
height: 5.0,
width: 0.0,
attach: 4,
rotation: 0.0,
style: "Standard".into(),
contents: "N".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
let ml = crate::MLeader {
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]],
landing: Vec3::new(25.0, 0.0, 0.0),
dogleg: 0.45,
text: Some(mtext.clone()),
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: None,
};
let b = bounds(EntityKind::MLeader(ml.clone()));
// The glyph spans x 25.45..28.78, y -2.5..2.5.
assert!(b.min.x <= 0.0 && b.max.x >= 28.79 && b.min.y <= -2.5 && b.max.y >= 2.5);
let mut empty = ml;
empty.text = Some(crate::MText { contents: " ".into(), ..mtext });
assert!(bounds(EntityKind::MLeader(empty)).max.x < 26.0);
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Data from a drawing file that CADCraft does not model, kept so that saving the drawing writes
//! it back: other programs' objects, extension dictionaries, xdata and properties (#528).
//!
//! It is kept as the file's own DXF groups, with the file's handles. The file reader fills it and
//! the writer puts it back, pointing references at whatever now has the referenced role (the
//! named object dictionary, a table record, a block, an entity); references to objects that are
//! gone are dropped. Commands don't edit it.
use std::collections::BTreeMap;
use crate::{Handle, RawTag};
/// What a file handle stood for when the object it named is one CADCraft writes itself (under a
/// new handle on save): a kind and an upper-case name, e.g. `("LAYER", "WALLS")`,
/// `("TABLE", "LAYER")`, `("BLOCK", "DOOR")`, `("NOD", "")` for the named object dictionary and
/// `("NOD", "ACAD_GROUP")` for one of its entries.
pub type ForeignKey = (String, String);
/// A non-graphical object of a type or role CADCraft does not model.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ForeignObject {
/// Its handle in the file it came from (kept on save).
pub handle: Handle,
/// Its DXF type (group 0), e.g. `XRECORD`.
pub kind: String,
/// Its groups after the type, as read.
pub tags: Vec<RawTag>,
}
/// What an entity, table record or block carries beyond what CADCraft models.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ForeignExtra {
/// Its extension dictionary (one of [`Foreign::objects`]).
pub xdict: Option<Handle>,
/// Objects of [`Foreign::objects`] that react to it (persistent reactors).
pub reactors: Vec<Handle>,
/// Other applications' extended data of a table record or block: groups from `1001` on. An
/// entity's is part of the entity ([`crate::Common::xdata`]), so it follows the entity's copies.
pub xdata: Vec<RawTag>,
/// The colour book colour (group 430) and the true colour (group 420) it was read with: it is
/// written back while the colour is unchanged.
pub color_book: Option<(String, String)>,
/// Other unmodelled property groups (material 347, shadow mode 284).
pub props: Vec<RawTag>,
}
impl ForeignExtra {
pub fn is_empty(&self) -> bool {
self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty()
}
}
/// Everything of a file CADCraft keeps without modelling it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Foreign {
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
pub classes: Vec<Vec<RawTag>>,
/// Kept objects, in file order.
pub objects: Vec<ForeignObject>,
/// Entries of the named object dictionary that CADCraft doesn't write itself: (key, object).
pub dictionary: Vec<(String, Handle)>,
/// Extras of entities, by handle.
pub entities: BTreeMap<Handle, ForeignExtra>,
/// Extras of table records (`("LAYER", "WALLS")`), tables (`("TABLE", "LAYER")`) and blocks
/// (`("BLOCK", "DOOR")`), by [`ForeignKey`].
pub records: BTreeMap<ForeignKey, ForeignExtra>,
/// The roles of the file handles the kept data refers to, for objects CADCraft rewrites.
pub targets: BTreeMap<Handle, ForeignKey>,
/// The file's data store section (ACDSDATA, AutoCAD 2013 and later), as read: its groups
/// after the section name. It holds the ACIS geometry of 3D solids, regions, bodies and
/// 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<RawTag>,
}
impl Foreign {
pub fn is_empty(&self) -> bool {
self.objects.is_empty()
&& self.dictionary.is_empty()
&& self.entities.is_empty()
&& self.records.is_empty()
&& self.classes.is_empty()
&& self.targets.is_empty()
&& self.data_store.is_empty()
}
/// The entities the data store has records for (their 320 handles).
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect()
}
}
+626
View File
@@ -0,0 +1,626 @@
//! Geometric tolerancing (GD&T): the TOLERANCE entity (feature control frames) and its layout.
//!
//! The frame is stored as the DXF Reference's "visual representation string" (TOLERANCE group 1):
//! frame lines separated by `^J`, compartments separated by `%%v`, and the geometric symbols as
//! characters of the `gdt` font inside `{\Fgdt;…}` runs. CADCraft never uses that font: every
//! symbol is drawn by [`symbol_prims`] from our own geometry (standard ISO/ASME symbol shapes).
use cadcraft_geom::{Bounds2, Vec2, Vec3};
use serde::{Deserialize, Serialize};
/// Caps for hostile frame strings (files, command parameters).
pub const MAX_FRAME_CHARS: usize = 4096;
pub const MAX_FRAME_ROWS: usize = 8;
pub const MAX_FRAME_CELLS: usize = 12;
/// A TOLERANCE entity: a feature control frame.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tolerance {
/// Insertion point: the middle of the left edge of the first frame line.
pub insert: Vec3,
/// The frame's X-axis direction (DXF group 11).
#[serde(default = "x_axis")]
pub dir: Vec3,
/// Dimension style: text height (DIMTXT × DIMSCALE), gap, colours, text style.
#[serde(default = "standard")]
pub style: String,
/// The frame contents (DXF group 1).
pub text: String,
}
fn x_axis() -> Vec3 {
Vec3::new(1.0, 0.0, 0.0)
}
fn standard() -> String {
"Standard".into()
}
impl Tolerance {
/// The frame's rotation (radians from +X); 0 when the direction is unusable.
pub fn rotation(&self) -> f64 {
let d = self.dir.xy();
if d.is_finite() && d.len() > 1e-12 { d.angle() } else { 0.0 }
}
/// Text height and padding from the dimension style: DIMTXT and DIMGAP times the style's
/// DIMSCALE (the drawing's when 0), or the text style's fixed height.
pub fn text_size(&self, d: &crate::Drawing) -> (f64, f64) {
let st = d.dim_style(&self.style).cloned().unwrap_or_default();
let k = st.effective_scale(d.header.f64("DIMSCALE", 1.0));
let fixed = d.text_style(&st.text_style).map(|t| t.height).filter(|h| h.is_finite() && *h > 0.0);
let h = fixed.unwrap_or(st.text_height * k);
(if h.is_finite() && h > 0.0 { h } else { 0.18 }, st.text_gap * k)
}
/// The frame laid out with `measure(text, height)` as the width of plain text.
pub fn layout(&self, d: &crate::Drawing, measure: &dyn Fn(&str, f64) -> f64) -> GdtLayout {
let (h, gap) = self.text_size(d);
layout_frame(&self.text, self.insert.xy(), self.rotation(), h, gap, measure)
}
}
/// A geometric characteristic, material condition or zone symbol.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GdtSymbol {
Position,
Concentricity,
Symmetry,
Parallelism,
Perpendicularity,
Angularity,
Cylindricity,
Flatness,
Circularity,
Straightness,
SurfaceProfile,
LineProfile,
CircularRunout,
TotalRunout,
Diameter,
/// Maximum material condition (circled M).
Mmc,
/// Least material condition (circled L).
Lmc,
/// Regardless of feature size (circled S).
Rfs,
/// Projected tolerance zone (circled P).
Projected,
}
/// Every symbol with its `gdt` font character and its name.
const SYMBOLS: [(GdtSymbol, char, &str); 19] = [
(GdtSymbol::Position, 'j', "position"),
(GdtSymbol::Concentricity, 'r', "concentricity"),
(GdtSymbol::Symmetry, 'i', "symmetry"),
(GdtSymbol::Parallelism, 'f', "parallelism"),
(GdtSymbol::Perpendicularity, 'b', "perpendicularity"),
(GdtSymbol::Angularity, 'a', "angularity"),
(GdtSymbol::Cylindricity, 'g', "cylindricity"),
(GdtSymbol::Flatness, 'c', "flatness"),
(GdtSymbol::Circularity, 'e', "circularity"),
(GdtSymbol::Straightness, 'u', "straightness"),
(GdtSymbol::SurfaceProfile, 'd', "surfaceprofile"),
(GdtSymbol::LineProfile, 'k', "lineprofile"),
(GdtSymbol::CircularRunout, 'h', "circularrunout"),
(GdtSymbol::TotalRunout, 't', "totalrunout"),
(GdtSymbol::Diameter, 'n', "diameter"),
(GdtSymbol::Mmc, 'm', "mmc"),
(GdtSymbol::Lmc, 'l', "lmc"),
(GdtSymbol::Rfs, 's', "rfs"),
(GdtSymbol::Projected, 'p', "projected"),
];
impl GdtSymbol {
/// The symbol's character in the frame string's `{\Fgdt;…}` runs.
pub fn code(self) -> char {
SYMBOLS.iter().find(|(s, _, _)| *s == self).map(|(_, c, _)| *c).unwrap_or('j')
}
pub fn from_code(c: char) -> Option<GdtSymbol> {
SYMBOLS.iter().find(|(_, k, _)| *k == c).map(|(s, _, _)| *s)
}
/// Lower-case name ("position", "mmc", …).
pub fn name(self) -> &'static str {
SYMBOLS.iter().find(|(s, _, _)| *s == self).map(|(_, _, n)| *n).unwrap_or("position")
}
/// A symbol by name (case, spaces, dashes and underscores ignored) or by a few common
/// alternatives ("true position", "runout", "profile", "M", "L", "S").
pub fn parse(s: &str) -> Option<GdtSymbol> {
let k: String = s.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).flat_map(char::to_lowercase).collect();
let alias = match k.as_str() {
"trueposition" | "pos" => Some(GdtSymbol::Position),
"coaxiality" => Some(GdtSymbol::Concentricity),
"roundness" => Some(GdtSymbol::Circularity),
"profile" | "surface" | "profileofasurface" => Some(GdtSymbol::SurfaceProfile),
"line" | "profileofaline" => Some(GdtSymbol::LineProfile),
"runout" => Some(GdtSymbol::CircularRunout),
"total" => Some(GdtSymbol::TotalRunout),
"m" => Some(GdtSymbol::Mmc),
"l" => Some(GdtSymbol::Lmc),
"s" => Some(GdtSymbol::Rfs),
"dia" | "ø" | "⌀" | "%%c" => Some(GdtSymbol::Diameter),
_ => None,
};
alias.or_else(|| SYMBOLS.iter().find(|(_, _, n)| *n == k).map(|(s, _, _)| *s))
}
/// A geometric characteristic (the first compartment of a frame line).
pub fn is_characteristic(self) -> bool {
!matches!(self, GdtSymbol::Diameter | GdtSymbol::Mmc | GdtSymbol::Lmc | GdtSymbol::Rfs | GdtSymbol::Projected)
}
/// A material condition modifier.
pub fn is_material(self) -> bool {
matches!(self, GdtSymbol::Mmc | GdtSymbol::Lmc | GdtSymbol::Rfs)
}
}
/// A piece of a compartment: plain text or a symbol.
#[derive(Clone, Debug, PartialEq)]
pub enum GdtRun {
Text(String),
Symbol(GdtSymbol),
}
/// One compartment's runs.
pub type Compartment = Vec<GdtRun>;
/// Parse a frame string into lines of compartments. Unknown formatting codes are skipped, an
/// unterminated code ends the string, and the sizes are capped ([`MAX_FRAME_CHARS`],
/// [`MAX_FRAME_ROWS`], [`MAX_FRAME_CELLS`]).
pub fn parse_frame(text: &str) -> Vec<Vec<Compartment>> {
let cs: Vec<char> = text.chars().take(MAX_FRAME_CHARS).collect();
let at = |i: usize| cs.get(i).copied();
let mut rows: Vec<Vec<Compartment>> = vec![vec![Vec::new()]];
// Font stack: whether the `gdt` font is current, per brace level.
let mut gdt = false;
let mut stack: Vec<bool> = Vec::new();
let push = |rows: &mut Vec<Vec<Compartment>>, run: GdtRun| {
let Some(cell) = rows.last_mut().and_then(|r| r.last_mut()) else { return };
match (cell.last_mut(), run) {
(Some(GdtRun::Text(t)), GdtRun::Text(s)) => t.push_str(&s),
(_, run) => cell.push(run),
}
};
let mut i = 0;
while let Some(c) = at(i) {
let next = at(i + 1);
let lower = |k: usize| at(k).map(|c| c.to_ascii_lowercase());
// Line break: `^J`, `\P` or a raw newline.
if (c == '^' && matches!(next, Some('J' | 'j'))) || (c == '\\' && next == Some('P')) || c == '\n' {
if rows.len() >= MAX_FRAME_ROWS {
break;
}
rows.push(vec![Vec::new()]);
i += if c == '\n' { 1 } else { 2 };
continue;
}
if c == '\r' {
i += 1;
continue;
}
if c == '%' && next == Some('%') {
match lower(i + 2) {
Some('v') => {
if let Some(r) = rows.last_mut()
&& r.len() < MAX_FRAME_CELLS
{
r.push(Vec::new());
}
}
Some('c') => push(&mut rows, GdtRun::Symbol(GdtSymbol::Diameter)),
Some('d') => push(&mut rows, GdtRun::Text("°".into())),
Some('p') => push(&mut rows, GdtRun::Text("±".into())),
Some('%') => push(&mut rows, GdtRun::Text("%".into())),
Some(o) => push(&mut rows, GdtRun::Text(format!("%%{o}"))),
None => break,
}
i += 3;
continue;
}
match c {
'{' => {
if stack.len() < 64 {
stack.push(gdt);
}
i += 1;
}
'}' => {
gdt = stack.pop().unwrap_or(false);
i += 1;
}
'\\' => match next {
Some('\\' | '{' | '}') => {
if let Some(n) = next {
push(&mut rows, GdtRun::Text(n.to_string()));
}
i += 2;
}
// Font switch `\Fname;` / `\fname|b0|i0;`: the gdt font draws symbols.
Some('F' | 'f') => {
let Some(end) = (i + 2..cs.len()).find(|k| at(*k) == Some(';')) else { break };
let name: String = cs.get(i + 2..end).unwrap_or(&[]).iter().take_while(|c| **c != '|').collect();
gdt = name.trim().to_ascii_lowercase().starts_with("gdt");
i = end + 1;
}
// Codes with a value up to `;` (height, colour, tracking, width, oblique, alignment…).
Some('A' | 'C' | 'c' | 'H' | 'Q' | 'T' | 'W' | 'S') => {
let Some(end) = (i + 2..cs.len()).find(|k| at(*k) == Some(';')) else { break };
i = end + 1;
}
// On/off toggles (underline, overline, strike-through) and the non-breaking space.
Some('L' | 'l' | 'O' | 'o' | 'K' | 'k') => i += 2,
Some('~') => {
push(&mut rows, GdtRun::Text(" ".into()));
i += 2;
}
Some(_) => {
push(&mut rows, GdtRun::Text("\\".into()));
i += 1;
}
None => break,
},
c if gdt => {
push(&mut rows, GdtSymbol::from_code(c).map(GdtRun::Symbol).unwrap_or_else(|| GdtRun::Text(c.to_string())));
i += 1;
}
c => {
push(&mut rows, GdtRun::Text(c.to_string()));
i += 1;
}
}
}
rows
}
/// A compartment with nothing to show.
pub fn compartment_is_empty(c: &Compartment) -> bool {
c.iter().all(|r| matches!(r, GdtRun::Text(t) if t.trim().is_empty()))
}
/// A tolerance value: optional diameter symbol, the value, optional material condition.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GdtTol {
#[serde(default)]
pub diameter: bool,
#[serde(default)]
pub value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub material: Option<String>,
}
/// A datum reference: the letter(s) and an optional material condition.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GdtDatum {
#[serde(default)]
pub letter: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub material: Option<String>,
}
/// One frame line as the Geometric Tolerance dialog fills it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GdtLine {
pub symbol: Option<GdtSymbol>,
pub tol1: Option<GdtTol>,
pub tol2: Option<GdtTol>,
pub datums: Vec<GdtDatum>,
}
/// A whole feature control frame: up to two tolerance lines, the projected tolerance zone and
/// the datum identifier.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GdtFrame {
pub lines: Vec<GdtLine>,
/// Projected tolerance zone height ("" = none).
pub height: String,
pub projected: bool,
/// Datum identifier ("" = none).
pub datum_id: String,
}
/// Escape free text for a frame string (no line or compartment breaks, no formatting codes).
fn escape(s: &str) -> String {
let mut out = String::new();
for c in s.chars().take(256) {
match c {
'\\' => out.push_str("\\\\"),
'{' => out.push_str("\\{"),
'}' => out.push_str("\\}"),
// `%%%` is a literal percent sign (a lone `%` could start a `%%` code).
'%' => out.push_str("%%%"),
'\n' | '\r' | '^' => out.push(' '),
c => out.push(c),
}
}
out
}
fn sym(s: GdtSymbol) -> String {
format!("{{\\Fgdt;{}}}", s.code())
}
/// The material condition symbol named by `m` ("M", "L", "S", "mmc"…).
fn material(m: &Option<String>) -> Option<GdtSymbol> {
m.as_deref().and_then(GdtSymbol::parse).filter(|s| s.is_material())
}
/// The frame string for `f` (DXF group 1 of a TOLERANCE).
pub fn compose_frame(f: &GdtFrame) -> String {
let mut lines: Vec<String> = Vec::new();
let tol = |t: &Option<GdtTol>| -> String {
let Some(t) = t else { return String::new() };
let mut s = String::new();
if t.diameter {
s.push_str(&sym(GdtSymbol::Diameter));
}
s.push_str(&escape(t.value.trim()));
if let Some(m) = material(&t.material) {
s.push_str(&sym(m));
}
if t.value.trim().is_empty() && !t.diameter && material(&t.material).is_none() { String::new() } else { s }
};
for l in f.lines.iter().take(MAX_FRAME_ROWS) {
let mut cells = vec![l.symbol.map(sym).unwrap_or_default(), tol(&l.tol1), tol(&l.tol2)];
for d in l.datums.iter().take(3) {
let mut s = escape(d.letter.trim());
if let Some(m) = material(&d.material) {
s.push_str(&sym(m));
}
cells.push(s);
}
while cells.last().is_some_and(String::is_empty) {
cells.pop();
}
if !cells.is_empty() {
lines.push(cells.join("%%v"));
}
}
if !f.height.trim().is_empty() || f.projected {
let mut s = escape(f.height.trim());
if f.projected {
s.push_str(&sym(GdtSymbol::Projected));
}
lines.push(s);
}
if !f.datum_id.trim().is_empty() {
lines.push(escape(f.datum_id.trim()));
}
lines.join("^J")
}
/// A primitive of a laid-out frame, in WCS.
#[derive(Clone, Debug, PartialEq)]
pub enum GdtPrim {
Line(Vec<Vec2>),
Circle {
center: Vec2,
radius: f64,
},
/// Counter-clockwise from `start` to `end` (radians).
Arc {
center: Vec2,
radius: f64,
start: f64,
end: f64,
},
/// A filled triangle (arrowheads).
Fill([Vec2; 3]),
}
/// A text run of a laid-out frame: left baseline point (WCS), height and rotation.
#[derive(Clone, Debug, PartialEq)]
pub struct GdtText {
pub pos: Vec2,
pub height: f64,
pub rotation: f64,
pub value: String,
}
/// A laid-out feature control frame.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GdtLayout {
/// The frame's boxes (drawn with the dimension line colour).
pub frame: Vec<GdtPrim>,
/// The symbols (drawn with the text colour).
pub symbols: Vec<GdtPrim>,
pub texts: Vec<GdtText>,
pub bounds: Bounds2,
}
/// Lay out the frame `text` at `insert`, rotated by `rotation`, with text height `h` and
/// horizontal padding `gap`. `measure(s, h)` is the width of plain text `s` at height `h`.
pub fn layout_frame(text: &str, insert: Vec2, rotation: f64, h: f64, gap: f64, measure: &dyn Fn(&str, f64) -> f64) -> GdtLayout {
let h = if h.is_finite() && h > 0.0 { h.min(1e12) } else { 0.18 };
let gap = if gap.is_finite() { gap.abs().clamp(h * 0.25, h * 2.0) } else { h * 0.5 };
let rotation = if rotation.is_finite() { rotation } else { 0.0 };
let (insert, row_h) = (if insert.is_finite() { insert } else { Vec2::ZERO }, 2.0 * h);
let to_w = |p: Vec2| insert + p.rotate(rotation);
let mut out = GdtLayout::default();
let mut prev_width = 0.0;
let rows: Vec<Vec<Compartment>> = parse_frame(text)
.into_iter()
.map(|r| r.into_iter().filter(|c| !compartment_is_empty(c)).collect::<Vec<_>>())
.filter(|r| !r.is_empty())
.collect();
let run_w = |r: &GdtRun| match r {
GdtRun::Symbol(_) => h,
GdtRun::Text(t) => {
let w = measure(t, h);
if w.is_finite() { w.clamp(0.0, h * 4096.0) } else { 0.0 }
}
};
for (k, row) in rows.iter().enumerate() {
let top = h - k as f64 * row_h;
let (bot, mid) = (top - row_h, top - h);
let mut x = 0.0;
for cell in row {
// Runs a little apart, so a modifier doesn't touch the value before it.
let sep = 0.25 * h;
let w: f64 = cell.iter().map(run_w).sum::<f64>() + sep * cell.len().saturating_sub(1) as f64;
let cw = (w + 2.0 * gap).max(row_h);
// The separator on the cell's left (the frame's left edge for the first cell).
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(x, top)), to_w(Vec2::new(x, bot))]));
let mut cx = x + (cw - w) / 2.0;
for r in cell {
match r {
GdtRun::Symbol(s) => {
let o = Vec2::new(cx, mid - h / 2.0);
out.symbols.extend(symbol_prims(*s).into_iter().map(|p| map_prim(p, |q| to_w(o + q * h), h, rotation)));
}
GdtRun::Text(t) => {
out.texts.push(GdtText { pos: to_w(Vec2::new(cx, mid - h / 2.0)), height: h, rotation, value: t.clone() });
}
}
cx += run_w(r) + sep;
}
x += cw;
}
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(x, top)), to_w(Vec2::new(x, bot))]));
// Top edge: the first line's, or the part sticking out past the line above.
if k == 0 {
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(0.0, top)), to_w(Vec2::new(x, top))]));
} else if x > prev_width {
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(prev_width, top)), to_w(Vec2::new(x, top))]));
}
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(0.0, bot)), to_w(Vec2::new(x, bot))]));
out.bounds = out.bounds.union(&Bounds2::from_points([
to_w(Vec2::new(0.0, top)),
to_w(Vec2::new(x, bot)),
to_w(Vec2::new(0.0, bot)),
to_w(Vec2::new(x, top)),
]));
prev_width = x;
}
if rows.is_empty() {
out.bounds = Bounds2::from_points([insert]);
}
out
}
/// Map a unit-box primitive through `f` (scale `s`, rotation `rot`).
fn map_prim(p: GdtPrim, f: impl Fn(Vec2) -> Vec2, s: f64, rot: f64) -> GdtPrim {
match p {
GdtPrim::Line(v) => GdtPrim::Line(v.into_iter().map(f).collect()),
GdtPrim::Circle { center, radius } => GdtPrim::Circle { center: f(center), radius: radius * s },
GdtPrim::Arc { center, radius, start, end } => GdtPrim::Arc { center: f(center), radius: radius * s, start: start + rot, end: end + rot },
GdtPrim::Fill(t) => GdtPrim::Fill(t.map(f)),
}
}
/// An arrowhead at `tip` pointing along `d` (unit box units).
fn arrow(tip: Vec2, d: Vec2) -> GdtPrim {
let d = d.normalized();
let back = tip - d * 0.3;
GdtPrim::Fill([tip, back + d.perp() * 0.1, back - d.perp() * 0.1])
}
/// A symbol drawn in a unit box (x and y in 0..1, the baseline at y = 0).
pub fn symbol_prims(s: GdtSymbol) -> Vec<GdtPrim> {
use std::f64::consts::{FRAC_PI_2, PI};
let v = Vec2::new;
let line = |pts: &[(f64, f64)]| GdtPrim::Line(pts.iter().map(|(x, y)| v(*x, *y)).collect());
let circle = |x: f64, y: f64, r: f64| GdtPrim::Circle { center: v(x, y), radius: r };
// Circled letters: the circle plus the letter's strokes.
let circled = |mut letter: Vec<GdtPrim>| {
letter.insert(0, circle(0.5, 0.5, 0.5));
letter
};
match s {
GdtSymbol::Position => vec![circle(0.5, 0.5, 0.3), line(&[(0.0, 0.5), (1.0, 0.5)]), line(&[(0.5, 0.0), (0.5, 1.0)])],
GdtSymbol::Concentricity => vec![circle(0.5, 0.5, 0.45), circle(0.5, 0.5, 0.25)],
GdtSymbol::Symmetry => vec![line(&[(0.0, 0.5), (1.0, 0.5)]), line(&[(0.2, 0.2), (0.8, 0.2)]), line(&[(0.2, 0.8), (0.8, 0.8)])],
GdtSymbol::Parallelism => vec![line(&[(0.1, 0.05), (0.5, 0.95)]), line(&[(0.5, 0.05), (0.9, 0.95)])],
GdtSymbol::Perpendicularity => vec![line(&[(0.05, 0.05), (0.95, 0.05)]), line(&[(0.5, 0.05), (0.5, 0.95)])],
GdtSymbol::Angularity => vec![line(&[(0.95, 0.05), (0.05, 0.05), (0.85, 0.75)])],
GdtSymbol::Cylindricity => {
let (c, r) = (v(0.5, 0.5), 0.3);
let d = Vec2::from_angle(65f64.to_radians());
let n = d.perp() * r;
vec![circle(0.5, 0.5, r), GdtPrim::Line(vec![c + n - d * 0.5, c + n + d * 0.5]), GdtPrim::Line(vec![c - n - d * 0.5, c - n + d * 0.5])]
}
GdtSymbol::Flatness => vec![line(&[(0.0, 0.25), (0.7, 0.25), (1.0, 0.75), (0.3, 0.75), (0.0, 0.25)])],
GdtSymbol::Circularity => vec![circle(0.5, 0.5, 0.45)],
GdtSymbol::Straightness => vec![line(&[(0.0, 0.5), (1.0, 0.5)])],
GdtSymbol::SurfaceProfile => {
vec![GdtPrim::Arc { center: v(0.5, 0.2), radius: 0.45, start: 0.0, end: PI }, line(&[(0.05, 0.2), (0.95, 0.2)])]
}
GdtSymbol::LineProfile => vec![GdtPrim::Arc { center: v(0.5, 0.2), radius: 0.45, start: 0.0, end: PI }],
GdtSymbol::CircularRunout => vec![line(&[(0.2, 0.05), (0.7, 0.95)]), arrow(v(0.7, 0.95), v(0.5, 0.9))],
GdtSymbol::TotalRunout => vec![
line(&[(0.05, 0.05), (0.5, 0.05)]),
line(&[(0.05, 0.05), (0.45, 0.95)]),
line(&[(0.5, 0.05), (0.9, 0.95)]),
arrow(v(0.45, 0.95), v(0.4, 0.9)),
arrow(v(0.9, 0.95), v(0.4, 0.9)),
],
GdtSymbol::Diameter => vec![circle(0.5, 0.5, 0.35), line(&[(0.1, 0.0), (0.9, 1.0)])],
GdtSymbol::Mmc => circled(vec![line(&[(0.3, 0.25), (0.3, 0.75), (0.5, 0.45), (0.7, 0.75), (0.7, 0.25)])]),
GdtSymbol::Lmc => circled(vec![line(&[(0.38, 0.75), (0.38, 0.25), (0.65, 0.25)])]),
GdtSymbol::Rfs => circled(vec![
GdtPrim::Arc { center: v(0.5, 0.625), radius: 0.125, start: 20f64.to_radians(), end: 3.0 * FRAC_PI_2 },
GdtPrim::Arc { center: v(0.5, 0.375), radius: 0.125, start: 200f64.to_radians(), end: FRAC_PI_2 },
]),
GdtSymbol::Projected => circled(vec![
line(&[(0.5, 0.5), (0.38, 0.5), (0.38, 0.75), (0.5, 0.75)]),
GdtPrim::Arc { center: v(0.5, 0.625), radius: 0.125, start: -FRAC_PI_2, end: FRAC_PI_2 },
line(&[(0.38, 0.5), (0.38, 0.25)]),
]),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_symbols_compartments_and_lines() {
let rows = parse_frame("{\\Fgdt;j}%%v{\\Fgdt;n}0.1{\\Fgdt;m}%%vA%%vB^J2.5{\\Fgdt;p}");
assert_eq!(rows.len(), 2);
let r0 = &rows[0];
assert_eq!(r0.len(), 4);
assert_eq!(r0[0], vec![GdtRun::Symbol(GdtSymbol::Position)]);
assert_eq!(r0[1], vec![GdtRun::Symbol(GdtSymbol::Diameter), GdtRun::Text("0.1".into()), GdtRun::Symbol(GdtSymbol::Mmc)]);
assert_eq!(r0[3], vec![GdtRun::Text("B".into())]);
assert_eq!(rows[1][0], vec![GdtRun::Text("2.5".into()), GdtRun::Symbol(GdtSymbol::Projected)]);
}
#[test]
fn compose_then_parse() {
let f = GdtFrame {
lines: vec![GdtLine {
symbol: Some(GdtSymbol::Flatness),
tol1: Some(GdtTol { diameter: false, value: "0.05".into(), material: None }),
tol2: None,
datums: vec![GdtDatum { letter: "A".into(), material: Some("L".into()) }],
}],
height: String::new(),
projected: false,
datum_id: "B".into(),
};
let s = compose_frame(&f);
assert_eq!(s, "{\\Fgdt;c}%%v0.05%%v%%vA{\\Fgdt;l}^JB");
let rows = parse_frame(&s);
assert_eq!(rows[0][3], vec![GdtRun::Text("A".into()), GdtRun::Symbol(GdtSymbol::Lmc)]);
assert_eq!(rows[1][0], vec![GdtRun::Text("B".into())]);
}
#[test]
fn hostile_strings_do_not_panic() {
let huge = "%%v{\\Fgdt;j}".repeat(100_000);
for s in ["{\\Fgdt;", "{\\Fgdt", "\\", "%%", "%", "{{{{", "}}}}", "^", "\\P\\P\\P", "{\\H", &huge, "\u{0}%%v\u{ffff}"] {
let rows = parse_frame(s);
assert!(rows.len() <= MAX_FRAME_ROWS && rows.iter().all(|r| r.len() <= MAX_FRAME_CELLS));
let l = layout_frame(s, Vec2::new(f64::NAN, 1.0), f64::INFINITY, f64::NAN, -1.0, &|t, h| t.len() as f64 * h);
assert!(l.frame.iter().all(|p| matches!(p, GdtPrim::Line(v) if v.iter().all(|q| q.is_finite()))));
}
}
#[test]
fn layout_boxes_each_compartment() {
let l = layout_frame("{\\Fgdt;j}%%v0.1%%vA", Vec2::ZERO, 0.0, 1.0, 0.5, &|t, h| t.chars().count() as f64 * h);
// Three cells: four separators, top and bottom.
assert_eq!(l.frame.len(), 6);
assert_eq!(l.texts.len(), 2);
assert!((l.bounds.min.y + 1.0).abs() < 1e-9 && (l.bounds.max.y - 1.0).abs() < 1e-9);
assert!(l.bounds.min.x.abs() < 1e-9 && l.bounds.max.x > 6.0);
}
}
+20 -1
View File
@@ -2,7 +2,7 @@
use std::collections::BTreeMap;
use cadcraft_geom::Vec3;
use cadcraft_geom::{Vec2, Vec3};
use serde::{Deserialize, Serialize};
/// A header variable value.
@@ -76,6 +76,20 @@ impl Header {
_ => None,
}
}
/// Drawing snap spacing; malformed or missing values use the drafting default.
pub fn snap_unit(&self) -> Vec2 {
self.spacing("SNAPUNIT", false)
}
/// Drawing grid spacing. A zero component follows the corresponding snap spacing.
pub fn grid_unit(&self) -> Vec2 {
self.spacing("GRIDUNIT", true)
}
fn spacing(&self, name: &str, allow_zero: bool) -> Vec2 {
self.point(name)
.map(|p| p.xy())
.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))
}
pub fn set_f64(&mut self, name: &str, v: f64) {
self.set(name, HVal::Real(v));
}
@@ -118,6 +132,11 @@ impl Header {
// Snap grid origin and rotation (SNAPANG in degrees).
h.set("SNAPBASE", HVal::Point(Vec3::ZERO));
h.set_f64("SNAPANG", 0.0);
h.set("SNAPUNIT", HVal::Point(Vec3::new(0.5, 0.5, 0.0)));
h.set("GRIDUNIT", HVal::Point(Vec3::new(0.5, 0.5, 0.0)));
// Annotation scale of model space; annotative objects of other scales show (1) or not.
h.set_str("CANNOSCALE", "1:1");
h.set_i64("ANNOALLVISIBLE", 1);
h
}
+93 -5
View File
@@ -6,25 +6,39 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod array;
mod constraint;
mod entity;
mod extents;
mod gdt;
mod header;
pub mod library;
mod plotstyle;
mod plotter;
mod refedit;
mod store;
mod tables;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
pub use array::*;
pub use cadcraft_color as color;
pub use cadcraft_geom as geom;
pub use constraint::*;
pub use entity::*;
pub use extents::{MAX_BLOCK_DEPTH, entity_bounds};
pub use gdt::*;
pub use header::{HVal, Header};
pub use plotstyle::*;
pub use plotter::*;
pub use refedit::{RefEdit, WorkItem};
pub use store::EntityStore;
pub use tables::*;
/// File data CADCraft doesn't model, kept for saving (#528).
pub mod dynblock;
pub mod foreign;
#[derive(Debug, thiserror::Error)]
pub enum DocError {
#[error("no such layer `{0}`")]
@@ -48,28 +62,71 @@ pub enum Space {
Paper(String),
}
impl Space {
/// Whether this is a layout's paper space.
pub fn is_paper(&self) -> bool {
matches!(self, Space::Paper(_))
}
/// The layout whose paper space this is; `None` for model space.
pub fn layout(&self) -> Option<&str> {
match self {
Space::Paper(n) => Some(n),
Space::Model => None,
}
}
/// The tab name (CTAB): `Model`, or the layout's name.
pub fn tab_name(&self) -> &str {
self.layout().unwrap_or("Model")
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Drawing {
pub header: Header,
/// File data CADCraft does not model, written back on save.
pub foreign: std::sync::Arc<foreign::Foreign>,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
pub layouts: Vec<Layout>,
pub views: Vec<NamedView>,
/// Model space viewport configurations (VPORTS): the tiles shown and named ones.
pub vports: Vec<VportConfig>,
pub ucss: Vec<Ucs>,
pub layer_states: Vec<LayerState>,
pub groups: Vec<Group>,
/// Plot style tables kept with the drawing (STYLESMANAGER); they shadow built-in tables of
/// the same name.
pub plot_style_tables: Vec<PlotStyleTable>,
/// Parametric constraints (GEOMCONSTRAINT / DIMCONSTRAINT).
pub constraints: Vec<Constraint>,
/// User parameters and parametric settings.
pub parametric: Parametric,
/// The annotation scale list (SCALELISTEDIT).
pub scales: Vec<AnnoScale>,
/// Next free handle.
pub handseed: u64,
/// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file:
/// a drawing opens with everything shown again.
pub hidden_objects: BTreeSet<Handle>,
/// What reading the file left out (a DWG's object records the reader couldn't decode), told
/// to the user when the drawing opens. Never written to a file.
pub read_notes: Vec<String>,
/// The in-place block reference edit in progress (REFEDIT). Never written to a file; files are
/// written from [`Drawing::committed`].
pub refedit: Option<RefEdit>,
/// Records of the file this drawing was read from that the reader could not place (a damaged
/// file), counted by the section they came from. Never written to a file.
pub skipped_records: BTreeMap<String, usize>,
}
impl Default for Drawing {
@@ -85,17 +142,21 @@ impl Drawing {
d.header = Header::imperial();
d
}
/// An empty metric drawing (millimetres, ISO-25 dimensions).
/// An empty metric drawing (millimetres, ISO-25 dimensions, multileaders and tables to match).
pub fn new_metric() -> Self {
let mut d = Drawing::bare();
d.header = Header::metric();
d.scales = metric_scales();
d.dim_styles.push(DimStyle::iso25());
d.mleader_styles = vec![MLeaderStyle::metric()];
d.table_styles = vec![TableStyle::metric()];
d.header.set_str("DIMSTYLE", "ISO-25");
d
}
fn bare() -> Self {
Drawing {
header: Header::default(),
foreign: std::sync::Arc::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
linetypes: vec![
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
@@ -106,16 +167,24 @@ impl Drawing {
dim_styles: vec![DimStyle::default()],
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: BTreeMap::new(),
model: EntityStore::new(),
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
views: Vec::new(),
vports: Vec::new(),
ucss: Vec::new(),
layer_states: Vec::new(),
groups: Vec::new(),
plot_style_tables: Vec::new(),
constraints: Vec::new(),
parametric: Parametric::default(),
scales: imperial_scales(),
handseed: 0x100,
hidden_objects: BTreeSet::new(),
read_notes: Vec::new(),
refedit: None,
skipped_records: BTreeMap::new(),
}
}
@@ -165,7 +234,17 @@ impl Drawing {
let same = match (base.get(*field), &cv) {
// Text style and arrow block names compare without case.
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(*field, "textStyle" | "arrowBlock" | "arrowBlock1" | "arrowBlock2") =>
if matches!(
*field,
"textStyle"
| "arrowBlock"
| "arrowBlock1"
| "arrowBlock2"
| "leaderArrowBlock"
| "dimLinetype"
| "extLinetype1"
| "extLinetype2"
) =>
{
a.eq_ignore_ascii_case(b)
}
@@ -261,9 +340,15 @@ impl Drawing {
Ok(h)
}
/// Effective visibility of an entity (its own flag, its layer on/thawed).
/// Effective visibility of an entity (its own flag, its layer on/thawed, not hidden by object
/// isolation).
pub fn is_visible(&self, e: &Entity) -> bool {
e.common.visible && self.layer(&e.common.layer).is_none_or(Layer::visible)
e.common.visible && self.layer(&e.common.layer).is_none_or(Layer::visible) && !self.is_hidden_object(e.handle)
}
/// Whether ISOLATEOBJECTS / HIDEOBJECTS hid `h` for this session.
pub fn is_hidden_object(&self, h: Handle) -> bool {
!self.hidden_objects.is_empty() && self.hidden_objects.contains(&h)
}
/// Bounds of all visible entities in a space.
@@ -297,5 +382,8 @@ impl Drawing {
}
}
mod anno;
pub use anno::*;
#[cfg(test)]
mod tests;
+70 -21
View File
@@ -6,6 +6,8 @@
use crate::{DashElement, Drawing, Linetype};
pub mod files;
/// The standard linetype library, defined in inches. Load it into a drawing with
/// [`standard_linetypes_for`], which scales it for metric drawings.
pub fn standard_linetypes() -> Vec<Linetype> {
@@ -151,9 +153,11 @@ pub fn standard_patterns() -> Vec<HatchPattern> {
name: "BRICK",
description: "Brick or masonry-type surface",
lines: vec![
// Running bond: courses 0.25 high, bricks 0.5 long. Each vertical family draws the
// joints of every other course, 0.5 apart; the second is offset half a brick.
pl(0.0, (0.0, 0.0), (0.0, 0.25), &[]),
pl(90.0, (0.0, 0.0), (0.25, 0.25), &[0.25, -0.25]),
pl(90.0, (0.25, 0.0), (0.25, 0.25), &[-0.25, 0.25]),
pl(90.0, (0.0, 0.0), (0.0, 0.5), &[0.25, -0.25]),
pl(90.0, (0.25, 0.0), (0.0, 0.5), &[-0.25, 0.25]),
],
},
HatchPattern {
@@ -201,28 +205,73 @@ pub fn standard_patterns() -> Vec<HatchPattern> {
description: "Staircase effect",
lines: vec![pl(0.0, (0.0, 0.0), (0.125, 0.125), &[0.125, -0.125]), pl(90.0, (0.125, 0.0), (0.125, 0.125), &[0.125, -0.125])],
},
HatchPattern {
name: "AR-CONC",
description: "Random dot and stone pattern",
lines: vec![
pl(50.0, (0.0, 0.0), (0.4, 0.25), &[0.15, -0.6]),
pl(355.0, (0.0, 0.0), (0.27, 0.3), &[0.12, -0.5]),
pl(100.0, (0.12, 0.05), (0.35, 0.33), &[0.1, -0.55]),
pl(0.0, (0.07, 0.02), (0.21, 0.17), &[0.0, -0.4]),
],
},
HatchPattern {
name: "AR-SAND",
description: "Random dot pattern",
lines: vec![
pl(37.5, (0.0, 0.0), (0.112, 0.0912), &[0.0, -0.22, 0.0, -0.14]),
pl(7.5, (0.0, 0.0), (0.157, 0.0724), &[0.0, -0.19, 0.0, -0.31]),
pl(-32.5, (0.0, 0.0), (0.091, 0.1312), &[0.0, -0.27, 0.0, -0.11]),
],
},
// Drawn at the scale of the pattern CAD programs ship under this name (about 16x
// coarser than first drawn here: AR-CONC hatches came out hundreds of times too dense).
scaled_pattern(
HatchPattern {
name: "AR-CONC",
description: "Random dot and stone pattern",
lines: vec![
pl(50.0, (0.0, 0.0), (0.4, 0.25), &[0.15, -0.6]),
pl(355.0, (0.0, 0.0), (0.27, 0.3), &[0.12, -0.5]),
pl(100.0, (0.12, 0.05), (0.35, 0.33), &[0.1, -0.55]),
pl(0.0, (0.07, 0.02), (0.21, 0.17), &[0.0, -0.4]),
],
},
16.0,
),
// Drawn at the scale of the pattern CAD programs ship under this name (about 16x
// coarser than first drawn here: AR-CONC hatches came out hundreds of times too dense).
scaled_pattern(
HatchPattern {
name: "AR-SAND",
description: "Random dot pattern",
lines: vec![
pl(37.5, (0.0, 0.0), (0.112, 0.0912), &[0.0, -0.22, 0.0, -0.14]),
pl(7.5, (0.0, 0.0), (0.157, 0.0724), &[0.0, -0.19, 0.0, -0.31]),
pl(-32.5, (0.0, 0.0), (0.091, 0.1312), &[0.0, -0.27, 0.0, -0.11]),
],
},
16.0,
),
]
}
pub fn pattern(name: &str) -> Option<HatchPattern> {
standard_patterns().into_iter().find(|p| p.name.eq_ignore_ascii_case(name))
}
/// The library pattern `name` as drawn in `d`. In a metric drawing (`MEASUREMENT` 1) every
/// length is multiplied by 25.4, as CAD programs use ISO-scaled pattern definitions there (as
/// for linetypes, see [`standard_linetypes_for`]): a hatch at scale 1 measures in millimetres
/// what it measures in inches in an imperial drawing.
pub fn pattern_for(d: &Drawing, name: &str) -> Option<HatchPattern> {
let p = pattern(name)?;
Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p })
}
/// `p` with every length (origins, offsets, dashes) multiplied by `k`.
fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern {
for l in &mut p.lines {
l.origin = (l.origin.0 * k, l.origin.1 * k);
l.delta = (l.delta.0 * k, l.delta.1 * k);
for d in &mut l.dashes {
*d *= k;
}
}
p
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn metric_drawings_draw_iso_scaled_patterns() {
let imp = pattern_for(&Drawing::new_imperial(), "ANSI31").map(|p| p.lines[0].delta.1);
let met = pattern_for(&Drawing::new_metric(), "ansi31").map(|p| p.lines[0].delta.1);
assert_eq!(imp, Some(0.125));
assert!(met.is_some_and(|m| (m - 0.125 * 25.4).abs() < 1e-12), "{met:?}");
assert!(pattern_for(&Drawing::new_metric(), "NOPE").is_none());
}
}
+341
View File
@@ -0,0 +1,341 @@
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
//!
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
//! a pattern), with `;` starting a comment line. CADCraft ships no such file; these read the
//! files users bring. Everything here treats the text as hostile: lines, definitions, dashes,
//! families and warnings are capped, numbers must be finite and reasonable, and nothing panics.
//! Problems become warnings and the definitions that can be read are kept.
use super::PatternLine;
use crate::{DashElement, Linetype};
/// Longest line read; longer lines are skipped with a warning.
pub const MAX_LINE_CHARS: usize = 4096;
/// Most definitions (linetypes or patterns) read from one file.
pub const MAX_DEFINITIONS: usize = 4096;
/// Most elements in one linetype.
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
/// Most line families in one hatch pattern (what the renderer draws, too).
pub const MAX_PATTERN_FAMILIES: usize = 1024;
/// Most dashes in one pattern line family (as for a pattern definition read from DXF).
pub const MAX_PATTERN_DASHES: usize = 256;
/// Largest magnitude accepted for a length, offset or scale.
pub const MAX_VALUE: f64 = 1.0e6;
/// Longest name or description kept.
const MAX_NAME_CHARS: usize = 255;
/// Most warnings collected; the rest are counted in a last line.
const MAX_WARNINGS: usize = 100;
/// A hatch pattern read from a user's `.pat` file.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UserPattern {
pub name: String,
pub description: String,
pub lines: Vec<PatternLine>,
}
/// What a file held: the definitions that could be read, and why anything else was skipped.
#[derive(Clone, Debug, PartialEq)]
pub struct Parsed<T> {
pub items: Vec<T>,
pub warnings: Vec<String>,
}
impl<T> Default for Parsed<T> {
fn default() -> Self {
Parsed { items: Vec::new(), warnings: Vec::new() }
}
}
impl<T> Parsed<T> {
fn warn(&mut self, line: usize, msg: impl Into<String>) {
match self.warnings.len() {
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
_ => {}
}
}
}
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
fn header(rest: &str) -> std::result::Result<(String, String), String> {
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
let name = name.trim();
if name.is_empty() {
return Err("a definition without a name".into());
}
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
return Err("a definition name that is too long or has control characters".into());
}
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
Ok((name.to_string(), desc))
}
/// A finite number within ±[`MAX_VALUE`].
fn number(t: &str) -> Option<f64> {
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
}
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
}
// ---------- LIN ----------
/// Read the linetypes of a `.lin` file. Simple linetypes and complex ones with embedded text
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
/// Lengths are in drawing units as written: a user's file is never rescaled.
pub fn parse_lin(text: &str) -> Parsed<Linetype> {
let mut out = Parsed::default();
// The definition being read: name, description, header line.
let mut pending: Option<(String, String, usize)> = None;
for (no, line) in lines(text) {
if line.is_empty() || line.starts_with(';') {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
if let Some((name, _, at)) = pending.take() {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
match header(rest) {
Ok((name, desc)) => pending = Some((name, desc, no)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((name, description, _)) = pending.take() else {
out.warn(no, "pattern line without a *NAME line before it; skipped");
continue;
};
if out.items.len() >= MAX_DEFINITIONS {
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
break;
}
if out.items.iter().any(|l: &Linetype| l.name.eq_ignore_ascii_case(&name)) {
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
continue;
}
match lin_pattern(line, no, &name, &mut out) {
Ok(pattern) => out.items.push(Linetype { name, description, pattern }),
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
}
}
if let Some((name, _, at)) = pending {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
out
}
/// Split a pattern line at commas outside `[…]` and `"…"`.
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
let mut out = Vec::new();
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
for (i, c) in line.char_indices() {
match c {
'"' => quoted = !quoted,
'[' if !quoted => depth = depth.saturating_add(1),
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
',' if !quoted && depth == 0 => {
out.push(line.get(start..i).unwrap_or("").trim());
start = i.saturating_add(1);
}
_ => {}
}
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
}
if quoted || depth != 0 {
return Err("an unclosed [ or \"".into());
}
out.push(line.get(start..).unwrap_or("").trim());
Ok(out)
}
/// The elements of a pattern line `A,dash,gap,[…],…`.
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<Linetype>) -> std::result::Result<Vec<DashElement>, String> {
let mut fields = lin_fields(line)?;
// The alignment field ("A") comes first; a line of plain numbers is read as well.
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
fields.remove(0);
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
}
let mut pattern: Vec<DashElement> = Vec::new();
for f in fields.into_iter().filter(|f| !f.is_empty()) {
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
let Some(inner) = f.strip_prefix('[') else {
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
pattern.push(DashElement::dash(len));
continue;
};
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
match lin_text(inner)? {
Some(text) => {
// The text sits at the end of the element before it (a zero-length one if none).
if pattern.last().is_none_or(|e| e.text.is_some()) {
pattern.push(DashElement::dash(0.0));
}
if let Some(last) = pattern.last_mut() {
*last = DashElement { length: last.length, ..text };
}
}
None => {
let shape = inner.split(',').next().unwrap_or("").trim();
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which CADCraft can't read; left out"));
}
}
}
if pattern.is_empty() {
return Err("no dashes".into());
}
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
return Err("every element has zero length".into());
}
Ok(pattern)
}
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
fn lin_text(inner: &str) -> std::result::Result<Option<DashElement>, String> {
let inner = inner.trim();
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
return Err("embedded text that is too long or has control characters".into());
}
let mut parts = rest.split(',').map(str::trim);
if !parts.next().unwrap_or("").is_empty() {
return Err("text element: expected a comma after the text".into());
}
let style = parts.next().unwrap_or("").trim();
if style.is_empty() || style.contains('=') {
return Err("text element: the text style is missing".into());
}
let mut e = DashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..DashElement::dash(0.0) };
for kv in parts.filter(|p| !p.is_empty()) {
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
match k.trim().to_ascii_uppercase().as_str() {
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
"X" => e.offset.x = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
"Y" => e.offset.y = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
// Upright text keeps a rotation relative to the line, like R.
k @ ("R" | "A" | "U") => {
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
e.absolute = k == "A";
}
other => return Err(format!("text element: unknown option `{other}`")),
}
}
Ok(Some(e))
}
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
fn angle(t: &str) -> Option<f64> {
let t = t.trim().to_ascii_lowercase();
let (num, unit) = match t.char_indices().last() {
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
_ => (t.as_str(), 'd'),
};
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
Some(match unit {
'r' => v,
'g' => v * std::f64::consts::PI / 200.0,
_ => v.to_radians(),
})
}
// ---------- PAT ----------
/// Read the hatch patterns of a `.pat` file. Values are used as written (an inch file for inch
/// drawings, a millimetre file for metric ones).
pub fn parse_pat(text: &str) -> Parsed<UserPattern> {
let mut out: Parsed<UserPattern> = Parsed::default();
// The pattern being read, its header line, and whether it already failed.
let mut cur: Option<(UserPattern, usize, bool)> = None;
let finish = |cur: Option<(UserPattern, usize, bool)>, out: &mut Parsed<UserPattern>| {
let Some((p, at, failed)) = cur else { return };
if failed {
return;
}
if p.lines.is_empty() {
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
} else if out.items.len() >= MAX_DEFINITIONS {
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
} else {
out.items.push(p);
}
};
for (no, line) in lines(text) {
// A comment runs to the end of the line.
let line = line.split(';').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
finish(cur.take(), &mut out);
match header(rest) {
Ok((name, description)) => cur = Some((UserPattern { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((p, _, failed)) = cur.as_mut() else {
out.warn(no, "line family without a *NAME line before it; skipped");
continue;
};
if *failed {
continue;
}
if p.lines.len() >= MAX_PATTERN_FAMILIES {
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
*failed = true;
continue;
}
match pat_family(line) {
Ok(l) => p.lines.push(l),
Err(e) => {
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
*failed = true;
}
}
}
finish(cur, &mut out);
out
}
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
fn pat_family(line: &str) -> std::result::Result<PatternLine, String> {
let mut v = Vec::new();
for f in line.split(',') {
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
}
let f = f.trim();
if f.is_empty() && v.len() >= 5 {
continue;
}
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
}
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
};
if dy.abs() < 1e-9 {
return Err("a line family with zero spacing (delta-y)".into());
}
Ok(PatternLine { angle, origin: (x, y), delta: (dx, dy), dashes: v.get(5..).unwrap_or(&[]).to_vec() })
}
+503
View File
@@ -0,0 +1,503 @@
//! Plot style tables: how objects print.
//!
//! A colour-dependent table (`.ctb`) has one plot style per index colour 1..=255: an object
//! prints with the style of its colour. A named table (`.stb`) holds styles that layers and
//! objects name directly. Each style can replace the object's colour, fade it (screening), turn
//! it grey, and replace its linetype and lineweight.
//!
//! CADCraft's built-in tables are our own definitions, not copies of any vendor's files:
//! [`DEFAULT_CTB`] keeps the object's properties, [`MONOCHROME_CTB`] prints everything black
//! and [`GRAYSCALE_CTB`] prints every colour as the grey of its luminance; the named
//! [`DEFAULT_STB`] offers `Normal`, `Black`, `Screened 50%` and `Thick`, and
//! [`MONOCHROME_STB`] prints `Normal` black.
//!
//! Tables are saved as files in our own JSON format (see `docs/plot-styles.md`):
//! [`PlotStyleTable::to_file_text`] and [`PlotStyleTable::from_file_text`].
use cadcraft_color::Rgb;
use serde::{Deserialize, Serialize};
/// Built-in colour-dependent table that prints objects with their own properties.
pub const DEFAULT_CTB: &str = "default.ctb";
/// Built-in colour-dependent table that prints everything black.
pub const MONOCHROME_CTB: &str = "monochrome.ctb";
/// Built-in colour-dependent table that prints every colour as a grey of its luminance.
pub const GRAYSCALE_CTB: &str = "grayscale.ctb";
/// Built-in named table: `Normal` (object properties), `Black`, `Screened 50%` and `Thick`.
pub const DEFAULT_STB: &str = "default.stb";
/// Built-in named table whose `Normal` style prints black.
pub const MONOCHROME_STB: &str = "monochrome.stb";
/// The names of the built-in tables.
pub const BUILTIN_PLOT_STYLE_TABLES: &[&str] = &[DEFAULT_CTB, MONOCHROME_CTB, GRAYSCALE_CTB, DEFAULT_STB, MONOCHROME_STB];
/// The style every named table has, which keeps the object's properties unless redefined.
pub const NORMAL_STYLE: &str = "Normal";
/// Most styles a named table may hold.
pub const MAX_NAMED_STYLES: usize = 1024;
/// Largest table file we read, in bytes.
pub const MAX_TABLE_FILE: usize = 4 << 20;
/// Format marker and version of our table files.
const FILE_MARKER: &str = "cadcraftPlotStyleTable";
const FILE_VERSION: u64 = 1;
/// Number of styles in a colour-dependent table (one per index colour 1..=255).
pub const CTB_STYLES: usize = 255;
/// Line end style of a plot style.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EndStyle {
#[default]
Object,
Butt,
Square,
Round,
Diamond,
}
/// Line join style of a plot style.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum JoinStyle {
#[default]
Object,
Miter,
Bevel,
Round,
Diamond,
}
/// Fill style of a plot style (for filled areas).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FillStyle {
#[default]
Object,
Solid,
Checkerboard,
Crosshatch,
Diamonds,
HorizontalBars,
SlantLeft,
SlantRight,
SquareDots,
VerticalBars,
}
/// One plot style. Serialized fields left at "use the object's" are omitted.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PlotStyle {
pub name: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub description: String,
/// Output colour (`"#rrggbb"` in JSON); `None` uses the object's colour.
#[serde(with = "rgb_hex", skip_serializing_if = "Option::is_none")]
pub color: Option<Rgb>,
/// Print the colour as the grey of its luminance.
#[serde(skip_serializing_if = "is_false")]
pub grayscale: bool,
/// Ink intensity in percent, 0 (white) to 100 (full colour).
#[serde(skip_serializing_if = "is_full")]
pub screening: u8,
/// Linetype name; `None` uses the object's linetype.
#[serde(skip_serializing_if = "Option::is_none")]
pub linetype: Option<String>,
/// Lineweight in hundredths of a millimetre (0..=211); `None` uses the object's lineweight.
#[serde(skip_serializing_if = "Option::is_none")]
pub lineweight: Option<u16>,
#[serde(skip_serializing_if = "is_default")]
pub end: EndStyle,
#[serde(skip_serializing_if = "is_default")]
pub join: JoinStyle,
#[serde(skip_serializing_if = "is_default")]
pub fill: FillStyle,
}
fn is_false(b: &bool) -> bool {
!*b
}
fn is_full(s: &u8) -> bool {
*s >= 100
}
fn is_default<T: Default + PartialEq>(v: &T) -> bool {
*v == T::default()
}
/// `Option<Rgb>` as `"#rrggbb"` (also read from `[r, g, b]`).
mod rgb_hex {
use cadcraft_color::Rgb;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(c: &Option<Rgb>, s: S) -> Result<S::Ok, S::Error> {
match c {
Some(c) => s.serialize_str(&c.hex()),
None => s.serialize_none(),
}
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Any {
Hex(String),
Triple(u8, u8, u8),
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Rgb>, D::Error> {
Ok(match Option::<Any>::deserialize(d)? {
None => None,
Some(Any::Triple(r, g, b)) => Some(Rgb(r, g, b)),
Some(Any::Hex(h)) => {
Some(Rgb::parse_hex(h.trim().trim_start_matches('#')).ok_or_else(|| serde::de::Error::custom("colour must be \"#rrggbb\""))?)
}
})
}
}
impl Default for PlotStyle {
fn default() -> Self {
PlotStyle::object("")
}
}
impl PlotStyle {
/// A style that keeps every object property.
pub fn object(name: &str) -> PlotStyle {
PlotStyle {
name: name.into(),
description: String::new(),
color: None,
grayscale: false,
screening: 100,
linetype: None,
lineweight: None,
end: EndStyle::Object,
join: JoinStyle::Object,
fill: FillStyle::Object,
}
}
/// Whether the style leaves the colour alone.
pub fn keeps_color(&self) -> bool {
self.color.is_none() && !self.grayscale && self.screening >= 100
}
/// The printed colour of an object drawn in `rgb`: the style's colour (else `rgb`), turned
/// grey when asked, then screened toward white.
pub fn apply_color(&self, rgb: Rgb) -> Rgb {
let c = self.color.unwrap_or(rgb);
let c = if self.grayscale {
let g = (c.luma().clamp(0.0, 1.0) * 255.0).round() as u8;
Rgb(g, g, g)
} else {
c
};
let s = u16::from(self.screening.min(100));
// Screening mixes the ink with the white paper: 100 % = full ink, 0 % = white.
let screen = |v: u8| (255 - (255 - u16::from(v)) * s / 100) as u8;
Rgb(screen(c.0), screen(c.1), screen(c.2))
}
}
/// Whether a table maps colours or names to styles.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PlotStyleKind {
/// Colour-dependent (`.ctb`): style `i - 1` applies to index colour `i`.
#[default]
ColorDependent,
/// Named (`.stb`): styles are picked by name.
Named,
}
/// A plot style table.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PlotStyleTable {
/// File name, such as `monochrome.ctb`.
pub name: String,
pub description: String,
pub kind: PlotStyleKind,
pub styles: Vec<PlotStyle>,
}
impl PlotStyleTable {
/// A colour-dependent table whose style for index colour `i` is `f(i)` (else object
/// properties), named `Color_i`.
pub fn color_dependent(name: &str, description: &str, f: impl Fn(u8) -> Option<PlotStyle>) -> PlotStyleTable {
let styles = (1..=255u8)
.map(|i| {
let label = format!("Color_{i}");
let mut s = f(i).unwrap_or_else(|| PlotStyle::object(&label));
s.name = label;
s
})
.collect();
PlotStyleTable { name: name.into(), description: description.into(), kind: PlotStyleKind::ColorDependent, styles }
}
/// A named table holding `Normal` (object properties) followed by `styles`.
pub fn named(name: &str, description: &str, styles: Vec<PlotStyle>) -> PlotStyleTable {
let mut all = vec![PlotStyle::object(NORMAL_STYLE)];
all.extend(styles);
PlotStyleTable { name: name.into(), description: description.into(), kind: PlotStyleKind::Named, styles: all }.sanitized()
}
/// A built-in table by name (case-insensitive; a `.ctb` extension may be left out).
pub fn builtin(name: &str) -> Option<PlotStyleTable> {
let n = name.trim().to_ascii_lowercase();
let n = if n.ends_with(".ctb") || n.ends_with(".stb") { n } else { format!("{n}.ctb") };
let black = Some(Rgb(0, 0, 0));
match n.as_str() {
DEFAULT_STB => Some(PlotStyleTable::named(
DEFAULT_STB,
"Normal keeps object properties; Black, Screened 50% and Thick",
vec![
PlotStyle { name: "Black".into(), color: black, ..PlotStyle::default() },
PlotStyle { name: "Screened 50%".into(), screening: 50, ..PlotStyle::default() },
PlotStyle { name: "Thick".into(), lineweight: Some(50), ..PlotStyle::default() },
],
)),
MONOCHROME_STB => {
let mut t = PlotStyleTable::named(
MONOCHROME_STB,
"Normal prints black; Screened 50% prints grey",
vec![PlotStyle { name: "Screened 50%".into(), color: black, screening: 50, ..PlotStyle::default() }],
);
if let Some(n) = t.styles.first_mut() {
n.color = black;
}
Some(t)
}
DEFAULT_CTB => Some(PlotStyleTable::color_dependent(DEFAULT_CTB, "Object colours, linetypes and lineweights", |_| None)),
MONOCHROME_CTB => Some(PlotStyleTable::color_dependent(MONOCHROME_CTB, "Every colour prints black", |_| {
Some(PlotStyle { color: Some(Rgb(0, 0, 0)), ..PlotStyle::default() })
})),
GRAYSCALE_CTB => Some(PlotStyleTable::color_dependent(GRAYSCALE_CTB, "Every colour prints as the grey of its luminance", |_| {
Some(PlotStyle { grayscale: true, ..PlotStyle::default() })
})),
_ => None,
}
}
/// Whether this table is colour-dependent.
pub fn is_color_dependent(&self) -> bool {
self.kind == PlotStyleKind::ColorDependent
}
/// The style for index colour `aci` (1..=255) of a colour-dependent table.
pub fn by_color(&self, aci: u8) -> Option<&PlotStyle> {
if !self.is_color_dependent() || aci == 0 {
return None;
}
self.styles.get(usize::from(aci) - 1)
}
/// The style called `name` (case-insensitive).
pub fn by_name(&self, name: &str) -> Option<&PlotStyle> {
self.styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))
}
/// The table with hostile or inconsistent values fixed: screening at most 100 %,
/// lineweights at most 2.11 mm, names at most 255 characters; a colour-dependent table has
/// exactly 255 styles named `Color_1`..`Color_255`; a named table has unique, non-empty
/// style names (at most [`MAX_NAMED_STYLES`]) starting with `Normal`.
pub fn sanitized(mut self) -> PlotStyleTable {
let cut = |s: &str| s.chars().take(255).collect::<String>();
self.name = cut(self.name.trim());
self.description = cut(&self.description);
for s in &mut self.styles {
s.name = cut(s.name.trim());
s.description = cut(&s.description);
s.screening = s.screening.min(100);
s.lineweight = s.lineweight.map(|w| w.min(211));
s.linetype = s.linetype.take().map(|l| cut(l.trim())).filter(|l| !l.is_empty());
}
match self.kind {
PlotStyleKind::ColorDependent => {
self.styles.truncate(CTB_STYLES);
while self.styles.len() < CTB_STYLES {
self.styles.push(PlotStyle::object(""));
}
for (i, s) in self.styles.iter_mut().enumerate() {
s.name = format!("Color_{}", i + 1);
}
}
PlotStyleKind::Named => {
let mut seen = std::collections::HashSet::new();
self.styles.retain(|s| !s.name.is_empty() && seen.insert(s.name.to_lowercase()));
self.styles.truncate(MAX_NAMED_STYLES);
match self.styles.iter().position(|s| s.name.eq_ignore_ascii_case(NORMAL_STYLE)) {
Some(0) => {}
Some(i) => {
let n = self.styles.remove(i);
self.styles.insert(0, n);
}
None => {
self.styles.insert(0, PlotStyle::object(NORMAL_STYLE));
self.styles.truncate(MAX_NAMED_STYLES);
}
}
if let Some(n) = self.styles.first_mut() {
n.name = NORMAL_STYLE.into();
}
}
}
self
}
/// The table as a file in our own format: pretty-printed JSON with a format marker.
pub fn to_file_text(&self) -> String {
let mut v = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
if let Some(o) = v.as_object_mut() {
o.insert(FILE_MARKER.into(), FILE_VERSION.into());
}
serde_json::to_string_pretty(&v).unwrap_or_default()
}
/// Read a table file written by [`PlotStyleTable::to_file_text`] (sanitized).
pub fn from_file_text(text: &str) -> std::result::Result<PlotStyleTable, String> {
if text.len() > MAX_TABLE_FILE {
return Err("the plot style table file is too large".into());
}
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("not a CADCraft plot style table: {e}"))?;
match v.get(FILE_MARKER).and_then(serde_json::Value::as_u64) {
Some(FILE_VERSION) => {}
Some(n) => return Err(format!("plot style table format version {n} is newer than this CADCraft reads")),
None => return Err(format!("not a CADCraft plot style table (no `{FILE_MARKER}`)")),
}
let t: PlotStyleTable = serde_json::from_value(v).map_err(|e| format!("bad plot style table: {e}"))?;
Ok(t.sanitized())
}
}
/// Whether a page setup's table name means "no plot style table".
pub fn no_plot_style_table(name: &str) -> bool {
let n = name.trim();
n.is_empty() || n.eq_ignore_ascii_case("none")
}
/// The plot style table a page setup names, if it is one we know: the drawing's own tables
/// first, then the built-in ones. `None` for no table (empty or "None") and for tables we don't
/// have.
pub fn plot_style_table(d: &crate::Drawing, name: &str) -> Option<PlotStyleTable> {
if no_plot_style_table(name) {
return None;
}
let n = name.trim();
d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned().or_else(|| PlotStyleTable::builtin(n))
}
/// The names of every table a drawing can use: its own, then the built-in ones it doesn't
/// shadow.
pub fn plot_style_table_names(d: &crate::Drawing) -> Vec<String> {
let mut v: Vec<String> = d.plot_style_tables.iter().map(|t| t.name.clone()).collect();
for b in BUILTIN_PLOT_STYLE_TABLES {
if !v.iter().any(|n| n.eq_ignore_ascii_case(b)) {
v.push((*b).to_string());
}
}
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtins_are_complete_color_dependent_tables() {
for n in [DEFAULT_CTB, MONOCHROME_CTB, GRAYSCALE_CTB] {
let t = PlotStyleTable::builtin(n).unwrap();
assert_eq!(t.name, n);
assert!(t.is_color_dependent());
assert_eq!(t.styles.len(), CTB_STYLES);
assert_eq!(t.by_color(1).unwrap().name, "Color_1");
assert_eq!(t.by_color(255).unwrap().name, "Color_255");
assert!(t.by_color(0).is_none());
}
assert!(PlotStyleTable::builtin("Monochrome").is_some());
assert!(PlotStyleTable::builtin("nope.ctb").is_none());
assert!(no_plot_style_table("") && no_plot_style_table(" None ") && !no_plot_style_table("monochrome.ctb"));
}
#[test]
fn colour_transforms() {
let mono = PlotStyleTable::builtin(MONOCHROME_CTB).unwrap();
assert_eq!(mono.by_color(1).unwrap().apply_color(Rgb(255, 0, 0)), Rgb(0, 0, 0));
let gray = PlotStyleTable::builtin(GRAYSCALE_CTB).unwrap();
let g = gray.by_color(3).unwrap().apply_color(Rgb(0, 255, 0));
assert!(g.0 == g.1 && g.1 == g.2 && g.0 > 128, "{g:?}");
let half = PlotStyle { color: Some(Rgb(0, 0, 0)), screening: 50, ..PlotStyle::default() };
assert_eq!(half.apply_color(Rgb(9, 9, 9)), Rgb(128, 128, 128));
let none = PlotStyle { screening: 0, ..PlotStyle::default() };
assert_eq!(none.apply_color(Rgb(10, 20, 30)), Rgb(255, 255, 255));
assert!(PlotStyle::default().keeps_color() && !half.keeps_color());
}
#[test]
fn named_builtins_and_sanitizing() {
let t = PlotStyleTable::builtin("default.stb").unwrap();
assert!(!t.is_color_dependent());
assert_eq!(t.styles.first().unwrap().name, NORMAL_STYLE);
assert!(t.by_name("black").is_some() && t.by_color(1).is_none());
assert_eq!(PlotStyleTable::builtin(MONOCHROME_STB).unwrap().by_name("Normal").unwrap().color, Some(Rgb(0, 0, 0)));
// Hostile values are clamped; names fixed.
let bad = PlotStyleTable {
name: " x.stb ".into(),
kind: PlotStyleKind::Named,
styles: vec![
PlotStyle { name: "A".into(), screening: 250, lineweight: Some(9999), ..PlotStyle::default() },
PlotStyle { name: "a".into(), ..PlotStyle::default() },
PlotStyle { name: " ".into(), ..PlotStyle::default() },
],
..PlotStyleTable::default()
}
.sanitized();
assert_eq!(bad.name, "x.stb");
assert_eq!(bad.styles.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Normal", "A"]);
assert_eq!((bad.styles[1].screening, bad.styles[1].lineweight), (100, Some(211)));
let short = PlotStyleTable { styles: vec![PlotStyle::object("zz")], ..PlotStyleTable::default() }.sanitized();
assert_eq!(short.styles.len(), CTB_STYLES);
assert_eq!(short.styles[0].name, "Color_1");
}
#[test]
fn file_format_round_trip() {
for name in BUILTIN_PLOT_STYLE_TABLES {
let t = PlotStyleTable::builtin(name).unwrap();
let text = t.to_file_text();
assert!(text.contains("\"cadcraftPlotStyleTable\": 1"));
assert_eq!(PlotStyleTable::from_file_text(&text).unwrap(), t, "{name}");
}
let mono = PlotStyleTable::builtin(MONOCHROME_CTB).unwrap().to_file_text();
assert!(mono.contains("\"color\": \"#000000\""), "colours as hex");
assert!(!mono.contains("screening"), "defaults are left out");
assert!(PlotStyleTable::from_file_text("{}").is_err());
assert!(PlotStyleTable::from_file_text("{\"cadcraftPlotStyleTable\": 9}").is_err());
assert!(PlotStyleTable::from_file_text("not json").is_err());
let rgb: PlotStyle = serde_json::from_value(serde_json::json!({"name": "x", "color": [1, 2, 3]})).unwrap();
assert_eq!(rgb.color, Some(Rgb(1, 2, 3)));
assert!(serde_json::from_value::<PlotStyle>(serde_json::json!({"color": "#zz0000"})).is_err());
}
#[test]
fn drawing_tables_shadow_builtins() {
let mut d = crate::Drawing::new_metric();
assert!(plot_style_table(&d, "monochrome.ctb").unwrap().by_color(1).unwrap().color.is_some());
d.plot_style_tables.push(PlotStyleTable::color_dependent("Monochrome.ctb", "", |_| None));
assert!(plot_style_table(&d, "monochrome.ctb").unwrap().by_color(1).unwrap().color.is_none());
let names = plot_style_table_names(&d);
assert_eq!(names.iter().filter(|n| n.eq_ignore_ascii_case("monochrome.ctb")).count(), 1);
assert!(names.contains(&"default.stb".to_string()));
}
#[test]
fn json_round_trip_with_defaults() {
let t = PlotStyleTable::builtin(GRAYSCALE_CTB).unwrap();
let back: PlotStyleTable = serde_json::from_value(serde_json::to_value(&t).unwrap()).unwrap();
assert_eq!(back, t);
let s: PlotStyle = serde_json::from_value(serde_json::json!({"name": "Thick", "lineweight": 50})).unwrap();
assert_eq!((s.screening, s.lineweight, s.color), (100, Some(50), None));
}
}
+253
View File
@@ -0,0 +1,253 @@
//! Plotter configurations: output devices with their paper sizes and printable areas.
//!
//! A configuration is a file in our own format (`*.plotter.json`, UTF-8 JSON with a format
//! marker, see `docs/plotters.md`). It names the output (PDF, PNG or SVG), the paper sizes the
//! device offers (each with the margins that bound its printable area), the raster resolution
//! and the default orientation. Binary `.pc3` files are not read.
use serde::{Deserialize, Serialize};
/// File-name suffix of plotter configuration files.
pub const PLOTTER_FILE_EXT: &str = ".plotter.json";
/// Largest plotter configuration file read (bytes).
pub const MAX_PLOTTER_FILE: usize = 1 << 20;
/// Most paper sizes one device keeps.
pub const MAX_DEVICE_PAPERS: usize = 512;
/// Longest device or paper name (characters).
pub const MAX_PLOTTER_NAME: usize = 100;
/// Largest paper side (mm), as for page setups.
pub const MAX_PAPER_MM: f64 = 5080.0;
const FILE_MARKER: &str = "cadcraftPlotter";
const FILE_VERSION: u64 = 1;
/// What a device writes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PlotOutput {
#[default]
Pdf,
Png,
Svg,
}
impl PlotOutput {
pub fn as_str(self) -> &'static str {
match self {
PlotOutput::Pdf => "pdf",
PlotOutput::Png => "png",
PlotOutput::Svg => "svg",
}
}
/// Parse `pdf`, `png` or `svg` (any case).
pub fn parse(s: &str) -> Option<PlotOutput> {
match s.trim().to_ascii_lowercase().as_str() {
"pdf" => Some(PlotOutput::Pdf),
"png" => Some(PlotOutput::Png),
"svg" => Some(PlotOutput::Svg),
_ => None,
}
}
}
/// Default sheet orientation of a device.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Orientation {
Portrait,
#[default]
Landscape,
}
/// A paper size a device offers: size in millimetres (portrait: width <= height after
/// sanitizing) and margins (left, bottom, right, top; mm) bounding the printable area.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DevicePaper {
pub name: String,
pub width: f64,
pub height: f64,
pub margins: [f64; 4],
}
impl Default for DevicePaper {
fn default() -> Self {
DevicePaper { name: String::new(), width: 210.0, height: 297.0, margins: [0.0; 4] }
}
}
impl DevicePaper {
/// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm
/// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at
/// most [`MAX_PLOTTER_NAME`] characters.
pub fn sanitized(mut self) -> DevicePaper {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 };
let (w, h) = (side(self.width), side(self.height));
self.width = w.min(h);
self.height = w.max(h);
for m in &mut self.margins {
*m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 };
}
let [l, b, r, t] = self.margins;
if l + r >= self.width || b + t >= self.height {
self.margins = [0.0; 4];
}
self.name = clean_name(&self.name);
if self.name.is_empty() {
self.name = format!("User ({:.2} x {:.2} MM)", self.width, self.height);
}
self
}
}
/// A plotter configuration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PlotterConfig {
pub name: String,
pub description: String,
pub output: PlotOutput,
/// Raster resolution (dots per inch) for PNG output.
pub resolution: u32,
pub orientation: Orientation,
/// Name of the paper chosen when a page setup switches to this device.
pub default_paper: String,
pub papers: Vec<DevicePaper>,
}
impl Default for PlotterConfig {
fn default() -> Self {
PlotterConfig {
name: String::new(),
description: String::new(),
output: PlotOutput::Pdf,
resolution: 300,
orientation: Orientation::Landscape,
default_paper: String::new(),
papers: Vec::new(),
}
}
}
/// A name trimmed, without control characters, at most [`MAX_PLOTTER_NAME`] characters.
fn clean_name(s: &str) -> String {
s.trim().chars().filter(|c| !c.is_control()).take(MAX_PLOTTER_NAME).collect::<String>().trim().to_string()
}
/// Names compare ignoring case, spaces, `_` and `-`.
fn key(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::<String>().to_ascii_lowercase()
}
impl PlotterConfig {
/// The configuration with hostile values fixed: a clean name and description, resolution
/// 50..=2400 dpi, at most [`MAX_DEVICE_PAPERS`] sanitized papers with unique names, and a
/// default paper the device has (the first one when it names none of them).
pub fn sanitized(mut self) -> PlotterConfig {
self.name = clean_name(&self.name);
self.description = self.description.chars().filter(|c| !c.is_control() || *c == '\n').take(1000).collect();
self.resolution = self.resolution.clamp(50, 2400);
let mut papers: Vec<DevicePaper> = Vec::new();
for p in std::mem::take(&mut self.papers).into_iter().take(MAX_DEVICE_PAPERS) {
let p = p.sanitized();
if !papers.iter().any(|q| key(&q.name) == key(&p.name)) {
papers.push(p);
}
}
self.papers = papers;
self.default_paper = match self.paper(&self.default_paper) {
Some(p) => p.name.clone(),
None => self.papers.first().map(|p| p.name.clone()).unwrap_or_default(),
};
self
}
/// The paper called `name` (ignoring case, spaces, `_` and `-`).
pub fn paper(&self, name: &str) -> Option<&DevicePaper> {
let k = key(name);
if k.is_empty() {
return None;
}
self.papers.iter().find(|p| key(&p.name) == k)
}
/// The paper a page setup gets when it switches to this device.
pub fn default_paper(&self) -> Option<&DevicePaper> {
self.paper(&self.default_paper).or_else(|| self.papers.first())
}
/// The configuration (sanitized) as a file in our own format: pretty-printed JSON with a
/// format marker.
pub fn to_file_text(&self) -> String {
let mut v = serde_json::to_value(self.clone().sanitized()).unwrap_or(serde_json::Value::Null);
if let Some(o) = v.as_object_mut() {
o.insert(FILE_MARKER.into(), FILE_VERSION.into());
}
serde_json::to_string_pretty(&v).unwrap_or_default()
}
/// Read a file written by [`PlotterConfig::to_file_text`] (sanitized; a name is required).
pub fn from_file_text(text: &str) -> std::result::Result<PlotterConfig, String> {
if text.len() > MAX_PLOTTER_FILE {
return Err("the plotter configuration file is too large".into());
}
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("not a CADCraft plotter configuration: {e}"))?;
match v.get(FILE_MARKER).and_then(serde_json::Value::as_u64) {
Some(FILE_VERSION) => {}
Some(n) => return Err(format!("plotter configuration format version {n} is newer than this CADCraft reads")),
None => return Err(format!("not a CADCraft plotter configuration (no `{FILE_MARKER}`)")),
}
let c: PlotterConfig = serde_json::from_value(v).map_err(|e| format!("bad plotter configuration: {e}"))?;
let c = c.sanitized();
if c.name.is_empty() {
return Err("the plotter configuration has no name".into());
}
Ok(c)
}
}
/// The file name a device is kept under: its name with characters that can't appear in file
/// names replaced by `_`, plus [`PLOTTER_FILE_EXT`]. `None` for an empty name.
pub fn plotter_file_name(name: &str) -> Option<String> {
let base: String =
clean_name(name).chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '(' | ')' | '+' | ',') { c } else { '_' }).collect();
let base = base.trim().trim_start_matches('.');
(!base.is_empty()).then(|| format!("{base}{PLOTTER_FILE_EXT}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip_and_hostile_values() {
let c = PlotterConfig {
name: "Office A3".into(),
output: PlotOutput::Png,
resolution: 1_000_000,
default_paper: "nope".into(),
papers: vec![
DevicePaper { name: "A3 borderless".into(), width: 420.0, height: 297.0, margins: [0.0; 4] },
DevicePaper { name: "a3-BORDERLESS".into(), ..DevicePaper::default() },
DevicePaper { name: String::new(), width: f64::NAN, height: 1e12, margins: [f64::INFINITY, 9e9, -1.0, 5.0] },
],
..PlotterConfig::default()
};
let back = PlotterConfig::from_file_text(&c.to_file_text()).unwrap();
assert_eq!(back.resolution, 2400);
assert_eq!(back.papers.len(), 2, "duplicate names dropped");
assert_eq!((back.papers[0].width, back.papers[0].height), (297.0, 420.0), "portrait");
assert_eq!(back.default_paper, "A3 borderless");
assert_eq!(back.papers[1].width, 1.0);
assert_eq!(back.papers[1].height, MAX_PAPER_MM);
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
assert!(back.paper("a3 BORDERLESS").is_some());
assert!(PlotterConfig::from_file_text("{}").is_err());
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name");
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 9, "name": "x"}"#).is_err());
assert_eq!(plotter_file_name("../a/b:c").as_deref(), Some("___a_b_c.plotter.json"));
assert_eq!(plotter_file_name(" "), None);
}
}
+83
View File
@@ -0,0 +1,83 @@
//! In-place editing of a block reference (REFEDIT / REFSET / REFCLOSE): the state kept with the
//! drawing while it lasts.
//!
//! The reference being edited is hidden and the block's objects stand in the drawing as ordinary
//! objects (the *working set*, transformed to where the reference shows them), the rest of the
//! block as faded copies (*ghosts*) that cannot be edited. REFCLOSE writes the working set back
//! into the block definition. The state lives in the [`Drawing`] itself, so undo and redo move
//! the working copies and the state together and can never leave one without the other.
use std::borrow::Cow;
use cadcraft_geom::Mat3;
use crate::{Drawing, Entity, Handle, Space};
/// One object of the working set.
#[derive(Clone, Debug, PartialEq)]
pub struct WorkItem {
/// The object in the drawing (a copy of the block object, or a drawing object added to the set).
pub copy: Handle,
/// The block object it was copied from; `None` for an object added from the drawing.
pub source: Option<Handle>,
}
/// An active in-place edit of a block reference. Never written to a file.
#[derive(Clone, Debug, PartialEq)]
pub struct RefEdit {
/// The block being edited.
pub block: String,
/// The reference that was picked (hidden while editing).
pub insert: Handle,
/// Whether the reference was visible before it was hidden.
pub insert_was_visible: bool,
/// The space the reference is in.
pub space: Space,
/// Block coordinates to drawing coordinates, through the picked reference.
pub to_world: Mat3,
/// The working set.
pub items: Vec<WorkItem>,
/// The rest of the block as faded copies: (copy, block object).
pub ghosts: Vec<(Handle, Handle)>,
/// Block objects taken out of the working set with their edits (block coordinates, the block
/// object's handle).
pub released: Vec<Entity>,
}
impl RefEdit {
/// Whether `h` is a working set object.
pub fn is_working(&self, h: Handle) -> bool {
self.items.iter().any(|i| i.copy == h)
}
/// Whether `h` is something the edit manages (working set, ghost, the hidden reference).
pub fn owns(&self, h: Handle) -> bool {
h == self.insert || self.is_working(h) || self.ghosts.iter().any(|(g, _)| *g == h)
}
}
impl Drawing {
/// The drawing as REFCLOSE Discard would leave it: the working copies and ghosts gone, the
/// reference shown, the block untouched. Borrowed when no edit is active. Files are written
/// from this, so a saved or autosaved drawing never holds half an edit.
pub fn committed(&self) -> Cow<'_, Drawing> {
let Some(r) = &self.refedit else { return Cow::Borrowed(self) };
let mut d = self.clone();
d.end_refedit_discard(r);
Cow::Owned(d)
}
/// Remove the edit's working copies and ghosts, show the reference again and clear the state.
pub fn end_refedit_discard(&mut self, r: &RefEdit) {
for i in &r.items {
if i.source.is_some() {
self.remove_entity(i.copy);
}
}
for (g, _) in &r.ghosts {
self.remove_entity(*g);
}
let vis = r.insert_was_visible;
let _ = self.modify_entity(r.insert, |e| e.common.visible = vis);
self.refedit = None;
}
}
+108
View File
@@ -189,6 +189,70 @@ impl EntityStore {
None => false,
}
}
/// Move `h` directly above (`above`) or under `anchor` in the draw order. False (and nothing
/// moves) when either is absent or they are the same object.
pub fn move_next_to(&mut self, h: Handle, anchor: Handle, above: bool) -> bool {
if h == anchor || !self.contains(anchor) {
return false;
}
let Some(e) = self.remove(h) else { return false };
let at = self.chunk_id(anchor).and_then(|id| Some((id, self.chunk_pos(id)?)));
let Some((id, pos)) = at else {
// Unreachable in practice (the anchor was present); keep the object on top.
self.push(Arc::unwrap_or_clone(e));
return false;
};
let Some(c) = self.chunks.get_mut(pos) else {
// Unreachable in practice too; never lose the object.
self.push(Arc::unwrap_or_clone(e));
return false;
};
let chunk = Arc::make_mut(c);
let i = chunk.items.iter().position(|x| x.handle == anchor).unwrap_or(chunk.items.len());
let i = if above { (i + 1).min(chunk.items.len()) } else { i };
chunk.items.insert(i, e);
let split = chunk.items.len() > 2 * CHUNK_MAX;
self.set_index(h, Some(id));
self.len += 1;
if split {
self.split_chunk(pos);
}
true
}
/// Split an oversized chunk in two, keeping the order.
fn split_chunk(&mut self, pos: usize) {
let mut fresh = self.new_chunk();
let Some(c) = self.chunks.get_mut(pos) else { return };
let chunk = Arc::make_mut(c);
let tail = chunk.items.split_off(chunk.items.len() / 2);
let new = Arc::make_mut(&mut fresh);
new.items = tail;
let (id, moved): (u32, Vec<Handle>) = (new.id, new.items.iter().map(|e| e.handle).collect());
self.chunks.insert(pos + 1, fresh);
for h in moved {
self.set_index(h, Some(id));
}
}
/// Reorder the whole store by a key (stable: equal keys keep their order).
pub fn sort_by_key<K: Ord>(&mut self, mut key: impl FnMut(&Entity) -> K) {
let mut items: Vec<Arc<Entity>> = self.iter().cloned().collect();
items.sort_by_cached_key(|e| key(e));
*self = EntityStore::default();
for e in items {
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
self.chunks.push(c);
}
let h = e.handle;
let Some(last) = self.chunks.last_mut() else { return };
let chunk = Arc::make_mut(last);
chunk.items.push(e);
let id = chunk.id;
self.set_index(h, Some(id));
self.len += 1;
}
}
/// True when `other` shares every chunk with `self` (same draw order, same entities). Holding
/// a clone of a store makes this exact: any edit to the original copies the touched chunk.
pub fn same_as(&self, other: &EntityStore) -> bool {
@@ -256,4 +320,48 @@ mod tests {
assert_eq!(s.iter().next().map(|e| e.handle), Some(Handle(5)));
assert_eq!(s.len(), 5);
}
fn order(s: &EntityStore) -> Vec<u64> {
s.iter().map(|e| e.handle.0).collect()
}
#[test]
fn move_next_to_and_sort() {
let mut s = EntityStore::new();
for h in 1..=5 {
s.push(ent(h));
}
assert!(s.move_next_to(Handle(1), Handle(3), true));
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
assert!(s.move_next_to(Handle(5), Handle(2), false));
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
assert!(!s.move_next_to(Handle(5), Handle(5), true));
assert!(!s.move_next_to(Handle(5), Handle(99), true));
assert!(!s.move_next_to(Handle(99), Handle(5), true));
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
assert_eq!(s.len(), 5);
s.sort_by_key(|e| e.handle.0 % 2);
assert_eq!(order(&s), [2, 4, 5, 3, 1]);
assert!(s.get(Handle(3)).is_some());
}
#[test]
fn move_next_to_splits_big_chunks() {
let mut s = EntityStore::new();
for h in 1..=3000 {
s.push(ent(h));
}
// Pile everything into the first chunk, under handle 1.
for h in 1500..=3000 {
assert!(s.move_next_to(Handle(h), Handle(1), true));
}
assert_eq!(s.len(), 3000);
assert!(s.chunks.iter().all(|c| c.items.len() <= 2 * CHUNK_MAX));
let o = order(&s);
assert_eq!(o.first(), Some(&1));
assert_eq!(o.get(1), Some(&3000));
for h in 1..=3000 {
assert_eq!(s.get(Handle(h)).map(|e| e.handle.0), Some(h));
}
}
}
+278 -4
View File
@@ -230,6 +230,49 @@ pub struct DimStyle {
/// DIMSE1 / DIMSE2 suppress extension lines.
pub suppress_ext1: bool,
pub suppress_ext2: bool,
/// DIMSD1 / DIMSD2 suppress the first / second half of the dimension line and its arrow.
pub suppress_dim1: bool,
pub suppress_dim2: bool,
/// DIMATFIT, what moves outside the extension lines when text and arrows don't both fit:
/// 0 both, 1 arrows first, 2 text first, 3 whichever fits best.
pub fit: u8,
/// DIMTIX: text always between the extension lines.
pub text_inside: bool,
/// DIMSOXD: suppress arrowheads that don't fit between the extension lines.
pub suppress_outside_arrows: bool,
/// DIMTOFL: a dimension line between the extension lines even when the arrows are outside
/// (through the circle for radius and diameter dimensions with the text outside).
pub force_line_inside: bool,
/// DIMTMOVE, when the text is moved away from its default place: 0 the dimension line
/// moves with it, 1 a leader joins them, 2 neither.
pub text_move: u8,
/// DIMTVP: text above (+) or below (-) the dimension line by this many text heights when
/// DIMTAD is 0.
pub text_vertical_pos: f64,
/// DIMTOLJ, vertical place of tolerance values next to the measurement: 0 bottom,
/// 1 middle, 2 top.
pub tol_just: u8,
/// DIMAZIN zero suppression of angular dimensions: 1 leading, 2 trailing.
pub angular_zero_suppression: u8,
/// DIMARCSYM, arc length symbol: 0 before the text, 1 above it, 2 none.
pub arc_symbol: u8,
/// DIMLDRBLK leader arrowhead ("" = closed filled).
pub leader_arrow_block: String,
/// DIMLTYPE / DIMLTEX1 / DIMLTEX2: linetypes of the dimension line and the extension
/// lines ("" = ByBlock).
pub dim_linetype: String,
pub ext_linetype1: String,
pub ext_linetype2: String,
/// DIMLWD / DIMLWE: lineweights of the dimension line and the extension lines in 1/100 mm
/// (-1 ByLayer, -2 ByBlock, -3 default).
pub dim_lineweight: i16,
pub ext_lineweight: i16,
/// DIMFXLON / DIMFXL: extension lines of a fixed length, measured from the dimension line
/// toward the origin.
pub fixed_ext: bool,
pub fixed_ext_length: f64,
/// DIMJOGANG: angle (degrees) of the jog's middle segment in jogged radius dimensions.
pub jog_angle: f64,
}
/// DIMSTYLE system variable names and the [`DimStyle`] fields they set.
@@ -281,6 +324,26 @@ pub const DIMVARS: &[(&str, &str)] = &[
("DIMAUNIT", "angularUnit"),
("DIMSE1", "suppressExt1"),
("DIMSE2", "suppressExt2"),
("DIMSD1", "suppressDim1"),
("DIMSD2", "suppressDim2"),
("DIMATFIT", "fit"),
("DIMTIX", "textInside"),
("DIMSOXD", "suppressOutsideArrows"),
("DIMTOFL", "forceLineInside"),
("DIMTMOVE", "textMove"),
("DIMTVP", "textVerticalPos"),
("DIMTOLJ", "tolJust"),
("DIMAZIN", "angularZeroSuppression"),
("DIMARCSYM", "arcSymbol"),
("DIMLDRBLK", "leaderArrowBlock"),
("DIMLTYPE", "dimLinetype"),
("DIMLTEX1", "extLinetype1"),
("DIMLTEX2", "extLinetype2"),
("DIMLWD", "dimLineweight"),
("DIMLWE", "extLineweight"),
("DIMFXLON", "fixedExt"),
("DIMFXL", "fixedExtLength"),
("DIMJOGANG", "jogAngle"),
];
impl Default for DimStyle {
@@ -335,6 +398,26 @@ impl Default for DimStyle {
angular_unit: 0,
suppress_ext1: false,
suppress_ext2: false,
suppress_dim1: false,
suppress_dim2: false,
fit: 3,
text_inside: false,
suppress_outside_arrows: false,
force_line_inside: false,
text_move: 0,
text_vertical_pos: 0.0,
tol_just: 1,
angular_zero_suppression: 0,
arc_symbol: 0,
leader_arrow_block: String::new(),
dim_linetype: String::new(),
ext_linetype1: String::new(),
ext_linetype2: String::new(),
dim_lineweight: -2,
ext_lineweight: -2,
fixed_ext: false,
fixed_ext_length: 1.0,
jog_angle: 45.0,
}
}
}
@@ -371,6 +454,13 @@ impl DimStyle {
(Value::Bool(_), Value::String(t)) => Value::Bool(matches!(t.to_ascii_lowercase().as_str(), "1" | "on" | "true" | "yes")),
(Value::Number(_), Value::String(t)) => match t.trim().parse::<f64>() {
Ok(x) => serde_json::json!(x),
// Lineweight names.
Err(_) if matches!(field, "dimLineweight" | "extLineweight") => match t.trim().to_ascii_lowercase().as_str() {
"bylayer" => serde_json::json!(-1),
"byblock" => serde_json::json!(-2),
"default" => serde_json::json!(-3),
_ => v.clone(),
},
Err(_) => v.clone(),
},
(Value::Number(_), Value::Bool(b)) => serde_json::json!(u8::from(*b)),
@@ -384,6 +474,10 @@ impl DimStyle {
};
// Integers stored in u8 fields: round floats.
let coerced = match (&old, &coerced) {
// Lineweights (i16): whole hundredths of a mm or -1/-2/-3.
(Value::Number(_), Value::Number(n)) if matches!(field, "dimLineweight" | "extLineweight") && !n.is_i64() => {
serde_json::json!(n.as_f64().filter(|x| x.is_finite()).unwrap_or(0.0).round().clamp(-3.0, 211.0) as i64)
}
(Value::Number(o), Value::Number(n)) if o.is_u64() && !n.is_u64() => {
serde_json::json!(n.as_f64().filter(|x| x.is_finite()).unwrap_or(0.0).round().clamp(0.0, 255.0) as u64)
}
@@ -393,7 +487,11 @@ impl DimStyle {
let x = coerced.as_f64();
let out_of_range = match field {
"textHeight" | "tolScale" => x.is_some_and(|x| x <= 0.0),
"scale" | "arrowSize" | "tickSize" => x.is_some_and(|x| x < 0.0),
"scale" | "arrowSize" | "tickSize" | "fixedExtLength" => x.is_some_and(|x| x < 0.0),
"fit" | "angularZeroSuppression" => x.is_some_and(|x| x > 3.0),
"textMove" | "tolJust" | "arcSymbol" => x.is_some_and(|x| x > 2.0),
"dimLineweight" | "extLineweight" => x.is_some_and(|x| !(-3.0..=211.0).contains(&x)),
"jogAngle" => x.is_some_and(|x| !(5.0..=90.0).contains(&x)),
_ => false,
};
if out_of_range {
@@ -429,6 +527,45 @@ impl DimStyle {
st
}
/// DIMTMOVE 0: the dimension line of a linear or aligned dimension follows text the user
/// placed (`text_mid`), keeping the DIMTAD / DIMTVP offset. Other kinds, text in its
/// default place and other DIMTMOVE values are left alone.
pub fn follow_text(&self, d: &mut crate::Dimension, dimscale: f64) {
if self.text_move != 0 || !d.user_text_pos {
return;
}
let dir = match d.kind {
crate::DimKind::Linear { rotation } => Vec2::from_angle(rotation),
crate::DimKind::Aligned => (d.p14.xy() - d.p13.xy()).normalized(),
_ => return,
};
if dir == Vec2::ZERO || !dir.is_finite() {
return;
}
let n = dir.perp();
let k = self.effective_scale(dimscale);
let (th, gap) = (self.text_height * k, self.text_gap.abs() * k);
let above = if n.y.abs() > 1e-9 {
if n.y > 0.0 { n } else { -n }
} else if n.x < 0.0 {
n
} else {
-n
};
let away = if (d.defpt.xy() - d.p13.xy()).dot(n) >= 0.0 { n } else { -n };
let off = match self.text_above {
0 => above * (self.text_vertical_pos * th),
2 => away * (gap + th / 2.0),
4 => -above * (gap + th / 2.0),
_ => above * (gap + th / 2.0),
};
let shift = n * (d.text_mid.xy() - off - d.defpt.xy()).dot(n);
if shift.is_finite() {
d.defpt.x += shift.x;
d.defpt.y += shift.y;
}
}
/// The ISO-25 style for metric drawings.
pub fn iso25() -> Self {
DimStyle {
@@ -445,6 +582,8 @@ impl DimStyle {
center_mark: 2.5,
zero_suppression: 8,
baseline_spacing: 3.75,
force_line_inside: true,
tol_just: 0,
..Default::default()
}
}
@@ -459,11 +598,28 @@ pub struct MLeaderStyle {
pub landing_gap: f64,
pub dogleg: f64,
pub text_style: String,
/// New multileaders of this style are annotative.
pub annotative: bool,
}
impl Default for MLeaderStyle {
fn default() -> Self {
MLeaderStyle { name: "Standard".into(), arrow_size: 0.18, text_height: 0.18, landing_gap: 0.09, dogleg: 0.36, text_style: "Standard".into() }
MLeaderStyle {
name: "Standard".into(),
arrow_size: 0.18,
text_height: 0.18,
landing_gap: 0.09,
dogleg: 0.36,
text_style: "Standard".into(),
annotative: false,
}
}
}
impl MLeaderStyle {
/// The Standard style for metric drawings: text and arrows as high as ISO-25's.
pub fn metric() -> Self {
MLeaderStyle { arrow_size: 2.5, text_height: 2.5, landing_gap: 0.625, dogleg: 5.0, ..Default::default() }
}
}
@@ -475,24 +631,52 @@ pub struct TableStyle {
pub margin: f64,
pub title: bool,
pub header: bool,
/// Cell styles: custom ones, and Title/Header/Data where they differ from what the text
/// height and margin imply ([`TableStyle::cell_style`]).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub cell_styles: Vec<crate::CellStyle>,
}
impl Default for TableStyle {
fn default() -> Self {
TableStyle { name: "Standard".into(), text_height: 0.18, margin: 0.06, title: true, header: true }
TableStyle { name: "Standard".into(), text_height: 0.18, margin: 0.06, title: true, header: true, cell_styles: Vec::new() }
}
}
impl TableStyle {
/// The Standard style for metric drawings: text as high as ISO-25's.
pub fn metric() -> Self {
TableStyle { text_height: 2.5, margin: 1.0, ..Default::default() }
}
}
mod cellstyle;
mod tablebreak;
pub use cellstyle::*;
pub use tablebreak::*;
/// A block definition.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Block {
pub name: String,
/// References to this block are annotative.
#[serde(default)]
pub annotative: bool,
pub base: Vec3,
#[serde(skip)]
pub entities: EntityStore,
#[serde(default)]
pub description: String,
/// An xref (`xref_path`: the referenced drawing's path as the user gave it, absolute,
/// relative to the host drawing's folder or a bare file name) attached as an overlay (DXF
/// BLOCK flag 8): not loaded when the host drawing is itself referenced by another drawing.
/// An xref's objects come from that file and are never saved with the host.
#[serde(default)]
pub xref_overlay: bool,
/// Whether an xref's objects are loaded, and why not (session state; not saved).
#[serde(default)]
pub xref_status: XrefStatus,
/// Anonymous (`*D12`, `*U3`…) blocks are generated geometry.
#[serde(default)]
pub anonymous: bool,
@@ -502,19 +686,55 @@ pub struct Block {
pub explodable: bool,
#[serde(default)]
pub units: u8,
/// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>,
}
/// The load state of an external reference.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum XrefStatus {
/// Not loaded yet (read from a file, not resolved).
#[default]
NotLoaded,
Loaded,
/// Unloaded by the user (XREF Unload): kept, not drawn.
Unloaded,
/// The referenced file was not found.
NotFound,
/// The file was found but could not be loaded (unreadable, too large, a circular reference).
Unresolved,
}
impl XrefStatus {
/// The status as the External References palette shows it.
pub fn label(self) -> &'static str {
match self {
XrefStatus::NotLoaded => "Not loaded",
XrefStatus::Loaded => "Loaded",
XrefStatus::Unloaded => "Unloaded",
XrefStatus::NotFound => "Not Found",
XrefStatus::Unresolved => "Unresolved",
}
}
}
impl Block {
pub fn new(name: &str) -> Self {
Block {
name: name.into(),
annotative: false,
base: Vec3::ZERO,
entities: EntityStore::new(),
xref_overlay: false,
xref_status: XrefStatus::NotLoaded,
description: String::new(),
anonymous: name.starts_with('*'),
xref_path: None,
explodable: true,
units: 0,
array: None,
}
}
}
@@ -532,12 +752,23 @@ pub struct PageSetup {
pub landscape: bool,
/// "layout" | "extents" | "display" | "window" | "limits".
pub plot_area: String,
/// Plot window corners `[x1, y1, x2, y2]` (DXF plot layout groups 48, 49, 140, 141); used when `plot_area` is "window".
pub plot_window: [f64; 4],
pub scale_to_fit: bool,
/// Paper units per drawing unit.
pub scale: f64,
pub plot_style_table: String,
pub center: bool,
pub lineweights: bool,
/// Draw the layout on screen (and in its PNG/SVG exports) with its plot style table
/// applied ("Display plot styles"; DXF plot layout flag 2).
pub show_plot_styles: bool,
/// Plot objects with their transparency ("Plot transparency"; PLOTTRANSPARENCYOVERRIDE can
/// override it). The DXF plot layout flags have no bit for it, so it is not saved in DXF.
pub plot_transparency: bool,
/// 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,
}
impl Default for PageSetup {
@@ -550,11 +781,15 @@ impl Default for PageSetup {
margins_mm: [6.35, 6.35, 6.35, 6.35],
landscape: true,
plot_area: "layout".into(),
plot_window: [0.0; 4],
scale_to_fit: false,
scale: 1.0,
plot_style_table: String::new(),
center: false,
lineweights: true,
show_plot_styles: false,
plot_transparency: false,
paper_mm: false,
}
}
}
@@ -578,15 +813,54 @@ impl Layout {
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
/// A named view (VIEW table): the centre and size of the area shown, in model space or a layout.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NamedView {
pub name: String,
pub center: Vec2,
pub height: f64,
pub width: f64,
/// The layer state restored with the view (its layer snapshot).
#[serde(default)]
pub layer_state: Option<String>,
/// View twist (radians, counterclockwise); kept for files, not applied to the 2D display.
#[serde(default)]
pub twist: f64,
/// The layout a paper space view belongs to (`None`: a model space view; an empty name: a
/// paper space view whose layout is not known).
#[serde(default)]
pub layout: Option<String>,
}
/// One tiled model space viewport of a [`VportConfig`] (a VPORT table record): its corners as
/// fractions of the drawing area (0,0 lower left to 1,1 upper right) and its view.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VportTile {
pub min: Vec2,
pub max: Vec2,
pub center: Vec2,
pub height: f64,
/// Width / height of the tile on screen when it was saved (0: unknown).
#[serde(default)]
pub aspect: f64,
}
/// A model space viewport configuration (VPORTS): `*Active` is the one shown, other names are
/// saved configurations. The first tile is the current one.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct VportConfig {
pub name: String,
pub tiles: Vec<VportTile>,
}
impl VportConfig {
/// The name of the configuration shown.
pub const ACTIVE: &'static str = "*Active";
pub fn is_active(&self) -> bool {
self.name.eq_ignore_ascii_case(Self::ACTIVE)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+301
View File
@@ -0,0 +1,301 @@
//! Table cell styles: the Title, Header and Data styles every table style has, plus named custom
//! ones. A cell style sets the text (style, height, colour, alignment), the cell (fill, margins,
//! borders) and how numbers are shown.
use cadcraft_color::Color;
use serde::{Deserialize, Serialize};
use crate::{Lineweight, Table, TableStyle};
/// The most cell styles a table style keeps (hostile input).
pub const MAX_CELL_STYLES: usize = 64;
/// One border of a cell style.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CellBorder {
pub visible: bool,
pub color: Color,
pub lineweight: Lineweight,
}
impl Default for CellBorder {
fn default() -> Self {
CellBorder { visible: true, color: Color::ByBlock, lineweight: Lineweight::ByBlock }
}
}
/// The borders of a cell style, in the order of the DXF Reference's TABLESTYLE groups: top,
/// inside horizontal, bottom, left, inside vertical, right. "Inside" borders separate cells that
/// share the style.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CellBorders {
pub top: CellBorder,
pub inside_h: CellBorder,
pub bottom: CellBorder,
pub left: CellBorder,
pub inside_v: CellBorder,
pub right: CellBorder,
}
impl CellBorders {
/// The borders in DXF order (top, inside horizontal, bottom, left, inside vertical, right).
pub fn as_array(&self) -> [CellBorder; 6] {
[self.top, self.inside_h, self.bottom, self.left, self.inside_v, self.right]
}
/// Mutable borders in DXF order.
pub fn as_array_mut(&mut self) -> [&mut CellBorder; 6] {
[&mut self.top, &mut self.inside_h, &mut self.bottom, &mut self.left, &mut self.inside_v, &mut self.right]
}
}
/// How a cell shows a number (a formula result).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CellFormat {
/// As short as possible (up to the precision when it has decimals).
#[default]
General,
/// Fixed decimals.
Decimal,
/// × 100 with a percent sign.
Percent,
/// Shown as typed: formulas keep their text.
Text,
}
/// A cell style.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CellStyle {
pub name: String,
/// Text style name.
pub text_style: String,
pub text_height: f64,
pub text_color: Color,
/// Background fill; `None` for no fill.
pub fill: Option<Color>,
/// Text alignment in the cell, as MTEXT attachment: 1 top left … 9 bottom right.
pub align: u8,
/// Horizontal and vertical margin between the cell edge and its text.
pub margin_h: f64,
pub margin_v: f64,
pub borders: CellBorders,
pub format: CellFormat,
/// Decimal places for numbers (0..=8).
pub precision: u8,
/// New rows in this style merge across the table (titles).
pub merge: bool,
}
impl Default for CellStyle {
fn default() -> Self {
CellStyle {
name: CellStyle::DATA.into(),
text_style: "Standard".into(),
text_height: 0.18,
text_color: Color::ByBlock,
fill: None,
align: 4,
margin_h: 0.06,
margin_v: 0.06,
borders: CellBorders::default(),
format: CellFormat::General,
precision: 2,
merge: false,
}
}
}
impl CellStyle {
pub const TITLE: &'static str = "Title";
pub const HEADER: &'static str = "Header";
pub const DATA: &'static str = "Data";
/// Whether `name` is one of the three styles every table style has.
pub fn is_builtin(name: &str) -> bool {
[Self::TITLE, Self::HEADER, Self::DATA].iter().any(|n| n.eq_ignore_ascii_case(name))
}
/// A copy with every value in range (hostile input from files and JSON).
pub fn sanitized(mut self) -> CellStyle {
let pos = |v: f64, d: f64| if v.is_finite() && v > 0.0 { v.min(1e9) } else { d };
let nonneg = |v: f64| if v.is_finite() && v >= 0.0 { v.min(1e9) } else { 0.0 };
self.text_height = pos(self.text_height, 0.18);
self.margin_h = nonneg(self.margin_h);
self.margin_v = nonneg(self.margin_v);
if !(1..=9).contains(&self.align) {
self.align = 4;
}
self.precision = self.precision.min(8);
self.name = self.name.trim().chars().take(255).collect();
if self.text_style.trim().is_empty() {
self.text_style = "Standard".into();
}
self
}
/// `v` as this style shows numbers.
pub fn format_number(&self, v: f64) -> String {
if !v.is_finite() {
return "#NUM".into();
}
let p = usize::from(self.precision.min(8));
match self.format {
CellFormat::Decimal => format!("{:.*}", p, v),
CellFormat::Percent => format!("{:.*}%", p, v * 100.0),
CellFormat::General | CellFormat::Text => {
let s = format!("{:.*}", p, v);
let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s };
if s == "-0" { "0".into() } else { s }
}
}
}
}
impl TableStyle {
/// The Title, Header or Data style this table style implies from its text height and margin
/// (data middle left; header and title middle centre, the title 1.4 × as high and merged).
pub fn base_cell_style(&self, name: &str) -> Option<CellStyle> {
let base = CellStyle { text_height: self.text_height, margin_h: self.margin, margin_v: self.margin, ..CellStyle::default() };
if name.eq_ignore_ascii_case(CellStyle::TITLE) {
Some(CellStyle { name: CellStyle::TITLE.into(), text_height: self.text_height * 1.4, align: 5, merge: true, ..base })
} else if name.eq_ignore_ascii_case(CellStyle::HEADER) {
Some(CellStyle { name: CellStyle::HEADER.into(), align: 5, ..base })
} else if name.eq_ignore_ascii_case(CellStyle::DATA) {
Some(base)
} else {
None
}
}
/// The cell style `name`: the style's own definition, else the implied Title/Header/Data
/// style, else Data.
pub fn cell_style(&self, name: &str) -> CellStyle {
self.cell_styles
.iter()
.find(|c| c.name.eq_ignore_ascii_case(name))
.cloned()
.or_else(|| self.base_cell_style(name))
.or_else(|| self.cell_styles.iter().find(|c| c.name.eq_ignore_ascii_case(CellStyle::DATA)).cloned())
.or_else(|| self.base_cell_style(CellStyle::DATA))
.unwrap_or_default()
}
/// Whether the style has a cell style `name` (built-in or custom).
pub fn has_cell_style(&self, name: &str) -> bool {
CellStyle::is_builtin(name) || self.cell_styles.iter().any(|c| c.name.eq_ignore_ascii_case(name))
}
/// The names of its cell styles: Title, Header, Data, then the custom ones.
pub fn cell_style_names(&self) -> Vec<String> {
let mut out: Vec<String> = [CellStyle::TITLE, CellStyle::HEADER, CellStyle::DATA].iter().map(|s| s.to_string()).collect();
out.extend(self.cell_styles.iter().filter(|c| !CellStyle::is_builtin(&c.name)).map(|c| c.name.clone()));
out
}
/// Store `cs` (replacing a cell style of the same name). A built-in style equal to its implied
/// form is not stored, so plain styles stay plain.
pub fn set_cell_style(&mut self, cs: CellStyle) {
let cs = cs.sanitized();
self.cell_styles.retain(|c| !c.name.eq_ignore_ascii_case(&cs.name));
if self.base_cell_style(&cs.name).is_some_and(|b| b == CellStyle { name: b.name.clone(), ..cs.clone() }) {
return;
}
if self.cell_styles.len() < MAX_CELL_STYLES {
self.cell_styles.push(cs);
}
}
}
/// The cell style of row `row` by its position: Title for the first row of a titled table,
/// Header for the header row, else Data.
pub fn positional_cell_style(row: usize, title: bool, header: bool) -> &'static str {
if title && row == 0 {
CellStyle::TITLE
} else if header && row == usize::from(title) {
CellStyle::HEADER
} else {
CellStyle::DATA
}
}
impl Default for Table {
fn default() -> Self {
Table {
insert: cadcraft_geom::Vec3::new(0.0, 0.0, 0.0),
col_widths: Vec::new(),
row_heights: Vec::new(),
cells: Vec::new(),
style: "Standard".into(),
text_height: 0.18,
title: false,
header: false,
row_styles: Vec::new(),
breaks: None,
data_link: None,
}
}
}
impl Table {
/// The cell style name of row `row`.
pub fn row_style(&self, row: usize) -> &str {
match self.row_styles.get(row).map(|s| s.trim()).filter(|s| !s.is_empty()) {
Some(s) => s,
None => positional_cell_style(row, self.title, self.header),
}
}
/// The cell style name of cell (`row`, `col`): its own, else its row's.
pub fn cell_style_name(&self, row: usize, col: usize) -> &str {
match self.cells.get(row).and_then(|r| r.get(col)).map(|c| c.style.trim()).filter(|s| !s.is_empty()) {
Some(s) => s,
None => self.row_style(row),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn implied_styles_follow_the_table_style() {
let st = TableStyle { text_height: 0.25, margin: 0.1, ..TableStyle::default() };
let t = st.cell_style("title");
assert_eq!((t.name.as_str(), t.align, t.merge), ("Title", 5, true));
assert!((t.text_height - 0.35).abs() < 1e-12);
assert_eq!(st.cell_style("nope").name, "Data");
assert_eq!(st.cell_style_names(), ["Title", "Header", "Data"]);
}
#[test]
fn storing_an_implied_style_keeps_the_style_plain() {
let mut st = TableStyle::default();
st.set_cell_style(st.cell_style("Header"));
assert!(st.cell_styles.is_empty());
st.set_cell_style(CellStyle { name: "Totals".into(), fill: Some(Color::Index(3)), ..CellStyle::default() });
assert!(st.has_cell_style("TOTALS"));
assert_eq!(st.cell_style_names().last().map(String::as_str), Some("Totals"));
}
#[test]
fn numbers_format() {
let c = CellStyle::default();
assert_eq!(c.format_number(2.5), "2.5");
assert_eq!(c.format_number(3.0), "3");
assert_eq!(c.format_number(-0.0001), "0");
let d = CellStyle { format: CellFormat::Decimal, precision: 3, ..c.clone() };
assert_eq!(d.format_number(1.0), "1.000");
let p = CellStyle { format: CellFormat::Percent, precision: 0, ..c };
assert_eq!(p.format_number(0.25), "25%");
assert_eq!(p.format_number(f64::NAN), "#NUM");
}
#[test]
fn hostile_values_are_sanitized() {
let c = CellStyle { text_height: f64::NAN, margin_h: -1.0, align: 42, precision: 200, ..CellStyle::default() }.sanitized();
assert_eq!((c.text_height, c.margin_h, c.align, c.precision), (0.18, 0.0, 4, 8));
}
}
+268
View File
@@ -0,0 +1,268 @@
//! Table breaking: a long table drawn in several parts side by side or one below the other, with
//! the label rows repeated, and data links (the table's cells filled from a CSV file).
use cadcraft_geom::{Bounds2, Vec2};
use serde::{Deserialize, Serialize};
use crate::Table;
/// The most parts a table is broken into.
pub const MAX_TABLE_PARTS: usize = 1000;
/// Where the next part of a broken table goes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BreakDirection {
#[default]
Right,
Left,
Down,
}
/// TABLEBREAK settings.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct TableBreak {
pub enabled: bool,
pub direction: BreakDirection,
/// Repeat the title and header rows at the top of every part.
pub repeat_top: bool,
/// Repeat the last row (bottom labels) at the bottom of every part.
pub repeat_bottom: bool,
/// Largest part height (labels included).
pub height: f64,
/// Manual heights of the first parts; later parts use `height`.
pub heights: Vec<f64>,
/// Space between parts.
pub spacing: f64,
/// Moves of parts 2, 3, … from their automatic place (part grips).
pub offsets: Vec<Vec2>,
}
impl Default for TableBreak {
fn default() -> Self {
TableBreak {
enabled: false,
direction: BreakDirection::Right,
repeat_top: true,
repeat_bottom: false,
height: 0.0,
heights: Vec::new(),
spacing: 0.5,
offsets: Vec::new(),
}
}
}
/// A CSV file the table's cells come from (DATALINK).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DataLink {
pub path: String,
/// The first table row the file's rows fill.
pub start_row: usize,
}
/// One part of a (broken) table: the rows it shows, top to bottom, and its insertion point.
#[derive(Clone, Debug, PartialEq)]
pub struct TablePart {
pub rows: Vec<usize>,
pub origin: Vec2,
}
fn size(v: f64) -> f64 {
if v.is_finite() && v > 0.0 { v } else { 0.0 }
}
impl Table {
/// Number of label rows at the top (title and header).
pub fn top_label_rows(&self) -> usize {
(usize::from(self.title) + usize::from(self.header)).min(self.row_heights.len())
}
/// Whether the table is drawn in several parts.
pub fn is_broken(&self) -> bool {
self.breaks.as_ref().is_some_and(|b| b.enabled && (size(b.height) > 0.0 || b.heights.iter().any(|h| size(*h) > 0.0)))
}
/// The parts the table is drawn in (one part when it isn't broken).
pub fn parts(&self) -> Vec<TablePart> {
let rows = self.row_heights.len().min(10_000);
let o = self.insert.xy();
let all = || TablePart { rows: (0..rows).collect(), origin: o };
let Some(b) = self.breaks.as_ref().filter(|_| self.is_broken()) else { return vec![all()] };
let h = |r: usize| size(self.row_heights.get(r).copied().unwrap_or(0.0));
let top: Vec<usize> = (0..self.top_label_rows()).collect();
let bottom: Option<usize> = (b.repeat_bottom && rows > top.len() + 1).then(|| rows - 1);
let data_end = bottom.unwrap_or(rows);
let bottom_h = bottom.map(h).unwrap_or(0.0);
let mut parts: Vec<Vec<usize>> = Vec::new();
let mut r = top.len();
while r < data_end && parts.len() < MAX_TABLE_PARTS {
let i = parts.len();
let limit = b.heights.get(i).copied().map(size).filter(|v| *v > 0.0).unwrap_or(size(b.height));
let mut rows_here: Vec<usize> = if i == 0 || b.repeat_top { top.clone() } else { Vec::new() };
let mut used: f64 = rows_here.iter().map(|r| h(*r)).sum::<f64>() + if b.repeat_bottom { bottom_h } else { 0.0 };
// At least one data row per part.
while r < data_end {
let next = r;
let fits = limit <= 0.0 || used + h(next) <= limit + 1e-9;
if !fits && rows_here.len() > if i == 0 || b.repeat_top { top.len() } else { 0 } {
break;
}
used += h(next);
rows_here.push(next);
r += 1;
}
parts.push(rows_here);
}
if parts.is_empty() {
return vec![all()];
}
// The rest when the part limit is reached; the bottom labels.
let n = parts.len();
if let Some(last) = parts.last_mut() {
last.extend(r..data_end);
}
for p in &mut parts {
if let Some(br) = bottom {
p.push(br);
}
}
// Place them.
let width: f64 = self.col_widths.iter().map(|w| size(*w)).sum();
let spacing = size(b.spacing);
let mut out = Vec::with_capacity(n);
let mut at = o;
for (i, rows) in parts.into_iter().enumerate() {
if i > 0 {
let prev_h: f64 = out.last().map(|p: &TablePart| p.rows.iter().map(|r| h(*r)).sum()).unwrap_or(0.0);
at = match b.direction {
BreakDirection::Right => at + Vec2::new(width + spacing, 0.0),
BreakDirection::Left => at - Vec2::new(width + spacing, 0.0),
BreakDirection::Down => at - Vec2::new(0.0, prev_h + spacing),
};
}
let off = if i > 0 { b.offsets.get(i - 1).copied().filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO) } else { Vec2::ZERO };
// Automatic places follow the automatic chain; manual moves apply to the part only.
out.push(TablePart { rows, origin: at + off });
}
out
}
/// The area the table covers, all parts included.
pub fn bounds(&self) -> Bounds2 {
let w: f64 = self.col_widths.iter().map(|w| size(*w)).sum();
let mut b = Bounds2::EMPTY;
for p in self.parts() {
let h: f64 = p.rows.iter().map(|r| size(self.row_heights.get(*r).copied().unwrap_or(0.0))).sum();
b.add(p.origin);
b.add(p.origin + Vec2::new(w, -h));
}
b
}
/// The cell (row, col) under `p`, in any part.
pub fn cell_at_point(&self, p: Vec2) -> Option<(usize, usize)> {
for part in self.parts() {
let (x, y) = (p.x - part.origin.x, part.origin.y - p.y);
if !(x.is_finite() && y.is_finite()) || x < 0.0 || y < 0.0 {
continue;
}
let mut acc = 0.0;
let mut row = None;
for r in &part.rows {
acc += size(self.row_heights.get(*r).copied().unwrap_or(0.0));
if y <= acc {
row = Some(*r);
break;
}
}
let Some(row) = row else { continue };
let mut acc = 0.0;
for (c, w) in self.col_widths.iter().enumerate() {
acc += size(*w);
if x <= acc {
return Some((row, c));
}
}
}
None
}
/// Grip points: the insertion point, then the origin of every further part.
pub fn grip_points(&self) -> Vec<Vec2> {
let mut g = vec![self.insert.xy()];
if self.is_broken() {
g.extend(self.parts().into_iter().skip(1).map(|p| p.origin));
}
g
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::TableCell;
fn table(rows: usize) -> Table {
Table {
col_widths: vec![2.0, 3.0],
row_heights: vec![1.0; rows],
cells: vec![vec![TableCell::default(); 2]; rows],
title: true,
header: true,
..Table::default()
}
}
#[test]
fn unbroken_is_one_part() {
let t = table(5);
assert_eq!(t.parts(), vec![TablePart { rows: vec![0, 1, 2, 3, 4], origin: Vec2::ZERO }]);
}
#[test]
fn breaks_repeat_labels_and_go_right() {
let mut t = table(8);
t.breaks = Some(TableBreak { enabled: true, height: 4.0, spacing: 1.0, ..TableBreak::default() });
let p = t.parts();
let rows: Vec<Vec<usize>> = p.iter().map(|x| x.rows.clone()).collect();
assert_eq!(rows, vec![vec![0, 1, 2, 3], vec![0, 1, 4, 5], vec![0, 1, 6, 7]]);
assert_eq!(p[1].origin, Vec2::new(6.0, 0.0));
assert_eq!(t.grip_points().len(), 3);
assert_eq!(t.cell_at_point(Vec2::new(7.0, -2.5)), Some((4, 0)));
let b = t.bounds();
assert_eq!((b.min, b.max), (Vec2::new(0.0, -4.0), Vec2::new(17.0, 0.0)));
}
#[test]
fn down_without_repeats_and_manual_heights() {
let mut t = table(8);
t.breaks = Some(TableBreak {
enabled: true,
direction: BreakDirection::Down,
repeat_top: false,
repeat_bottom: true,
height: 3.0,
heights: vec![5.0],
offsets: vec![Vec2::new(1.0, 0.0)],
..TableBreak::default()
});
let p = t.parts();
let rows: Vec<Vec<usize>> = p.iter().map(|x| x.rows.clone()).collect();
assert_eq!(rows, vec![vec![0, 1, 2, 3, 7], vec![4, 5, 7], vec![6, 7]]);
assert_eq!(p[1].origin, Vec2::new(1.0, -5.5));
}
#[test]
fn hostile_break_settings() {
let mut t = table(3000);
t.breaks = Some(TableBreak { enabled: true, height: 1e-9, spacing: f64::NAN, ..TableBreak::default() });
let p = t.parts();
assert!(p.len() <= MAX_TABLE_PARTS);
assert_eq!(p.iter().map(|x| x.rows.iter().filter(|r| **r >= 2).count()).sum::<usize>(), 2998);
t.breaks = Some(TableBreak { enabled: true, height: f64::INFINITY, ..TableBreak::default() });
assert_eq!(t.parts().len(), 1);
}
}
+118
View File
@@ -16,6 +16,23 @@ fn new_drawing_has_standard_tables() {
assert!(m.dim_style("ISO-25").is_some());
}
#[test]
fn new_metric_drawing_has_metric_multileader_and_table_styles() {
let m = Drawing::new_metric();
let iso = m.dim_style("ISO-25").unwrap();
let ml = m.mleader_styles.iter().find(|s| s.name == "Standard").unwrap();
assert_eq!((ml.text_height, ml.arrow_size), (iso.text_height, iso.arrow_size));
assert_eq!(ml.dogleg, 5.0);
let ts = m.table_styles.iter().find(|s| s.name == "Standard").unwrap();
assert_eq!(ts.text_height, iso.text_height);
assert_eq!(iso.text_height, 2.5);
let i = Drawing::new_imperial();
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
assert_eq!(i.table_styles, vec![TableStyle::default()]);
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
}
#[test]
fn add_and_extents() {
let mut d = Drawing::new_imperial();
@@ -79,6 +96,59 @@ fn inserts_of_missing_or_empty_blocks_do_not_stretch_extents() {
assert_eq!(d.extents(&Space::Model).max, Vec2::new(12.0, 12.0));
}
#[test]
fn visible_attributes_of_a_missing_block_still_count() {
// The renderer draws the attributes of a reference whose definition is missing, so they are
// extents and selection targets, as with an empty definition. The insertion point still isn't.
let attrib = |invisible: bool| Attrib {
tag: "TAG".into(),
text: Text {
insert: Vec3::new(1000.0, 1000.0, 0.0),
align_pt: None,
height: 10.0,
value: "hello".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
},
invisible,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let ins = |block: &str, attribs: Vec<Attrib>| {
Entity::new(
Handle(1),
EntityKind::Insert(Insert {
block: block.into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs,
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
}),
)
};
let mut d = Drawing::new_imperial();
d.blocks.insert("Empty".into(), std::sync::Arc::new(Block::new("Empty")));
let missing = entity_bounds(&d, &ins("Missing", vec![attrib(false)]), 0);
let empty = entity_bounds(&d, &ins("Empty", vec![attrib(false)]), 0);
assert!(!missing.is_empty());
assert_eq!((missing.min, missing.max), (empty.min, empty.max));
assert_eq!(missing.min, Vec2::new(1000.0, 1000.0));
// Without a visible attribute there is nothing to measure.
assert!(entity_bounds(&d, &ins("Missing", vec![]), 0).is_empty());
assert!(entity_bounds(&d, &ins("Missing", vec![attrib(true)]), 0).is_empty());
}
#[test]
fn transform_arc_mirror_keeps_shape() {
let mut k = EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 1.0, start: 0.0, end: std::f64::consts::FRAC_PI_2 });
@@ -269,6 +339,38 @@ fn extents_pair(d: &Drawing) -> (Vec2, Vec2) {
(b.min, b.max)
}
/// #706: block A reaches B once through a chain of 14 blocks (B at depth 15, its line's block E at
/// 16, past the limit) and once directly (B at depth 1). `children` picks which of the two A holds.
fn deep_and_shallow(children: &[&str]) -> Drawing {
let mut d = Drawing::new_imperial();
let mut add = |name: &str, kids: Vec<EntityKind>| {
let mut blk = Block::new(name);
for (i, k) in kids.into_iter().enumerate() {
blk.entities.push(Entity::new(Handle(i as u64 + 1), k));
}
d.blocks.insert(name.into(), std::sync::Arc::new(blk));
};
add("E", vec![line((1000.0, 1000.0), (2000.0, 1000.0))]);
add("B", vec![plain_insert("E")]);
for i in 1..=14 {
let next = if i == 14 { "B".to_string() } else { format!("C{}", i + 1) };
add(&format!("C{i}"), vec![plain_insert(&next)]);
}
add("A", children.iter().map(|c| plain_insert(c)).collect());
d.add(&Space::Model, Common::default(), plain_insert("A")).unwrap();
d
}
#[test]
fn deep_block_visit_does_not_hide_a_shallow_reference() {
let line = (Vec2::new(1000.0, 1000.0), Vec2::new(2000.0, 1000.0));
// Control: past the limit, the deep path alone contributes nothing.
assert!(deep_and_shallow(&["C1"]).extents(&Space::Model).is_empty());
assert_eq!(extents_pair(&deep_and_shallow(&["B"])), line);
assert_eq!(extents_pair(&deep_and_shallow(&["B", "C1"])), line);
assert_eq!(extents_pair(&deep_and_shallow(&["C1", "B"])), line);
}
#[test]
fn block_entity_with_invisible_flag_is_ignored_in_insert_extents() {
let mut far = far_line("0");
@@ -354,6 +456,8 @@ fn attdef_in_block_is_ignored_in_insert_extents() {
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
}),
);
let d = drawing_with_block(attdef);
@@ -385,6 +489,8 @@ fn mtext_kind(contents: &str) -> EntityKind {
style: "Standard".into(),
contents: contents.into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
})
}
@@ -441,6 +547,7 @@ fn invisible_dimblock_entity_is_ignored_in_dimension_extents() {
block: Some("*D1".into()),
overrides: Default::default(),
assoc: vec![],
marks: Default::default(),
}),
)
.unwrap();
@@ -463,3 +570,14 @@ fn invisible_dimblock_entity_is_ignored_in_dimension_extents() {
dim(&mut d, far_line("0"));
assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0));
}
#[test]
fn space_names_its_tab() {
assert!(!Space::Model.is_paper());
assert_eq!(Space::Model.layout(), None);
assert_eq!(Space::Model.tab_name(), "Model");
let p = Space::Paper("Sheet A".into());
assert!(p.is_paper());
assert_eq!(p.layout(), Some("Sheet A"));
assert_eq!(p.tab_name(), "Sheet A");
}
+181
View File
@@ -0,0 +1,181 @@
//! Reading the user's own `.lin` and `.pat` files (#552). Every file here is a tiny synthetic one
//! written for these tests, with our own names.
use cadcraft_doc::library::files::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat};
const LIN: &str = "\
;; my own linetypes
*MYDASH,My dash __ __ __
A,.5,-.25
*MYDOTS
A,0,-.1,0,-.2
*MYTEXT,Text line --MY--MY--
A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2
*MYSHAPE,Shape line
A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1
";
#[test]
fn simple_and_text_linetypes_are_read() {
let r = parse_lin(LIN);
let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]);
let dash = &r.items[0];
assert_eq!(dash.description, "My dash __ __ __");
assert_eq!(dash.pattern.iter().map(|e| e.length).collect::<Vec<_>>(), [0.5, -0.25]);
assert_eq!(r.items[1].description, "");
assert_eq!(r.items[1].pattern.len(), 4);
// The text belongs to the gap before it: drawn at that gap's end.
let text = &r.items[2].pattern;
assert_eq!(text.len(), 3);
assert_eq!(text[1].length, -0.2);
assert_eq!(text[1].text.as_deref(), Some("MY"));
assert_eq!(text[1].style.as_deref(), Some("STANDARD"));
assert!((text[1].scale - 0.1).abs() < 1e-12);
assert!((text[1].offset.x + 0.1).abs() < 1e-12 && (text[1].offset.y + 0.05).abs() < 1e-12);
assert!(!text[1].absolute);
assert!(text[2].text.is_none());
// Shapes need SHX files: left out with a note, the dashes kept.
let shape = &r.items[3].pattern;
assert_eq!(shape.iter().map(|e| e.length).collect::<Vec<_>>(), [0.25, -0.1, -0.1, 1.0]);
assert!(shape.iter().all(|e| e.text.is_none() && e.shape.is_none()));
assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings);
}
#[test]
fn text_rotation_units_and_absolute_angles() {
let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n");
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let rot = |i: usize| r.items[i].pattern[0].rotation;
assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute);
assert!((rot(1) - 1.5).abs() < 1e-12);
assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
// Commas and brackets inside the quoted text are text.
assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]"));
}
#[test]
fn broken_linetypes_are_skipped_with_warnings() {
let text = "\
*NOPATTERN
*BADNUM
A,.5,abc
*BADALIGN
B,.5,-.5
*UNCLOSED
A,.5,[\"x\",S1
*
A,1,-1
A,1,-1
*GOOD
A,1,-1
*GOOD
A,2,-2
*ZERO
A,0,0
*NOSTYLE
A,1,[\"x\"],-1
";
let r = parse_lin(text);
assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["GOOD"]);
assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept");
for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] {
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
}
}
#[test]
fn hostile_linetype_files_never_panic_and_stay_capped() {
let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(","));
let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(","));
let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect();
let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n";
for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"]
{
let r = parse_lin(text);
assert!(r.items.len() <= 4096);
assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite())));
assert!(r.warnings.len() <= 101);
}
assert!(parse_lin(huge).items.is_empty());
assert_eq!(parse_lin(&defs).items.len(), 4096);
}
const PAT: &str = "\
; my own patterns
*MYGRID, My grid
0, 0,0, 0,.5
90, 0,0, 0,.5
*MYBRICK,My brick ; trailing comment
0, 0,0, 0,.25
90, 0,0, .25,.25, .25,-.25
";
#[test]
fn hatch_patterns_are_read() {
let r = parse_pat(PAT);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert_eq!(r.items.len(), 2);
let grid = &r.items[0];
assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid"));
assert_eq!(grid.lines.len(), 2);
assert_eq!(grid.lines[1].angle, 90.0);
assert_eq!(grid.lines[1].delta, (0.0, 0.5));
let brick = &r.items[1];
assert_eq!(brick.description, "My brick");
assert_eq!(brick.lines[1].origin, (0.0, 0.0));
assert_eq!(brick.lines[1].dashes, [0.25, -0.25]);
}
#[test]
fn lowercase_pattern_names_are_upper_cased() {
let r = parse_pat("*mypat\n45,0,0,0,.125\n");
assert_eq!(r.items[0].name, "MYPAT");
}
#[test]
fn broken_patterns_are_skipped_with_warnings() {
let text = "\
0,0,0,0,1
*EMPTY
*SHORT
0,0,0
*ZEROGAP
0,0,0,1,0
*BADNUM
0,0,0,0,x
*OK
0,0,0,0,1
*OK
45,0,0,0,1
";
let r = parse_pat(text);
assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["OK"]);
assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept");
for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] {
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
}
}
#[test]
fn hostile_pattern_files_never_panic_and_stay_capped() {
let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5));
let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(","));
let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(","));
let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect();
let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n";
for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] {
let r = parse_pat(text);
assert!(r.items.len() <= 4096);
assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES)));
assert!(r.warnings.len() <= 101);
}
assert!(parse_pat(&families).items.is_empty());
assert!(parse_pat(&dashes).items.is_empty());
assert_eq!(parse_pat(&ok_dashes).items.len(), 1);
assert!(parse_pat(big).items.is_empty());
assert_eq!(parse_pat(&defs).items.len(), 4096);
}
+2
View File
@@ -0,0 +1,2 @@
mod lin_pat_parse;
mod sub_segment_alias;
+14
View File
@@ -0,0 +1,14 @@
//! `Sub::parse` accepts every spelling its documentation lists (#710).
use cadcraft_doc::Sub;
#[test]
fn short_segment_name_matches_the_documented_forms() {
for spelling in ["seg2", "segment2", "s2"] {
assert_eq!(Sub::parse(spelling), Some(Sub::Segment(2)), "spelling: {spelling}");
}
for spelling in ["s", "start"] {
assert_eq!(Sub::parse(spelling), Some(Sub::Start), "spelling: {spelling}");
}
assert_eq!(Sub::parse("unknown"), None);
}
+1 -1
View File
@@ -10,4 +10,4 @@ workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# MPL-2.0: used as an unmodified dependency only (see plan/adr/0001 and NOTICE).
acadrust = "0.6.3"
acadrust = "0.6.5"
+663 -12
View File
@@ -4,6 +4,25 @@
//! converted to DXF bytes, which CADCraft's own DXF reader maps to its document model; saving
//! goes the other way. Keeping the dependency behind this byte-level API isolates it: nothing
//! else in CADCraft depends on its types. Native targets only (it memory-maps files).
//!
//! # Guardrails around the third-party decoder
//!
//! The decoder allocates tables and section buffers from sizes a (possibly damaged or hostile)
//! file declares, and once it starts it cannot be interrupted (an allocation failure aborts the
//! process, which `catch_unwind` cannot recover). Because the dependency is used unmodified, this
//! crate guards it from the outside:
//!
//! - Both directions reject oversized input *before* the decoder runs ([`Limits::max_dwg_bytes`]
//! for DWG→DXF, [`Limits::max_dxf_bytes`] for DXF→DWG), and the DWG→DXF output is capped while
//! it is written (`CappedWriter`).
//! - The reader and writer run inside `catch_unwind`, so a decode failure is reported instead of
//! crashing.
//!
//! These bound the input- and output-size variants. A small file that declares a huge internal
//! table or section can still make the dependency allocate before any size is known; fully fixing
//! that requires an upstream fix in `acadrust` (validate declared sizes against a decoded-memory
//! budget) or running the decode in a separate worker with an OS memory limit. The limits here
//! keep the blast radius bounded in the meantime.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
@@ -61,12 +80,38 @@ mod native {
/// guard: the input size before the DWG reader runs, the DXF size while it is written, so a
/// runaway conversion stops at the limit instead of filling memory first.
pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result<Vec<u8>, String> {
dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf)
}
/// [`dwg_to_dxf_with`], also returning notes on what the read left out. The reader runs in
/// failsafe mode: an object record it can't decode is skipped instead of failing the whole
/// file, and the notes say how many were skipped and of which types, so a partial read never
/// passes for a complete one.
pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec<u8>, Vec<String>), String> {
if bytes.len() > limits.max_dwg_bytes {
return Err(format!("DWG: the file is {}, larger than the {} CADCraft opens", mb(bytes.len() as u64), mb(limits.max_dwg_bytes as u64)));
}
let doc = std::panic::catch_unwind(|| acadrust::DwgReader::from_stream(Cursor::new(bytes)).read())
.map_err(|_| "the DWG reader failed on this file".to_string())?
.map_err(|e| format!("DWG: {e}"))?;
let outcome = std::panic::catch_unwind(|| {
acadrust::DwgReader::from_stream_with_options(Cursor::new(bytes), acadrust::DwgReadOptions::failsafe()).read_with_stats()
})
.map_err(|_| "the DWG reader failed on this file".to_string())?
.map_err(|e| format!("DWG: {e}"))?;
// Failsafe skips records, not whole files: when the objects stream itself couldn't be
// read (a damaged header or section map, or not a DWG at all), nothing was read.
if !outcome.stats.record_stream_read {
let why = outcome.stats.diagnostics.first().map(|d| d.message.trim_start_matches("Failsafe: ").to_string());
return Err(format!("DWG: {}", why.unwrap_or_else(|| "the file's objects couldn't be read".to_string())));
}
let mut notes = read_notes(&outcome.stats);
let mut doc = outcome.document;
current_style_names(&mut doc);
table_merges(&mut doc);
table_style_rows(&mut doc, false);
let orphans = drop_orphaned_dgn_components(&mut doc);
if orphans > 0 {
let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") };
notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out"));
}
let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false };
let written = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)))
.map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?;
@@ -79,14 +124,283 @@ mod native {
));
}
written.map_err(|e| format!("DWG→DXF: {e}"))?;
Ok(add_header_vars(out.buf, &doc.header))
Ok((add_header_vars(out.buf, &doc.header), notes))
}
/// Most record types named in the skipped-records note.
const NOTE_TYPES: usize = 6;
/// The note on object records a failsafe read skipped: how many, and how many of each type
/// (most first), or nothing when the read was complete.
pub(crate) fn read_notes(stats: &acadrust::ReadStats) -> Vec<String> {
let skipped = stats.skipped_source_records;
if skipped == 0 {
return Vec::new();
}
let label = |t: Option<&str>| match t.map(str::parse::<i16>) {
Some(Ok(code)) => type_name(code).map_or_else(|| format!("type {code}"), str::to_string),
Some(Err(_)) => t.unwrap_or_default().to_string(),
None => "unknown".to_string(),
};
let mut by_type: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
for d in stats.diagnostics.iter().filter(|d| d.record_handle.is_some()) {
*by_type.entry(label(d.record_type.as_deref())).or_default() += 1;
}
let mut types: Vec<(String, usize)> = by_type.into_iter().collect();
types.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let mut list: Vec<String> = types.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t} × {n}")).collect();
if types.len() > NOTE_TYPES {
list.push(format!("{} more types", types.len() - NOTE_TYPES));
}
let of = if stats.source_records > 0 { format!(" of {}", stats.source_records) } else { String::new() };
let records = if skipped == 1 && of.is_empty() { "object record" } else { "object records" };
let (were, them) = if skipped == 1 { ("was", "it") } else { ("were", "them") };
let which = if list.is_empty() { String::new() } else { format!(" ({})", list.join(", ")) };
vec![format!(
"DWG: {skipped}{of} {records} couldn't be read and {were} left out{which}; \
saving over the original file would lose {them}"
)]
}
/// The DXF name of a DWG object type code with a fixed number (classes, 500 and up, are
/// numbered per file).
fn type_name(code: i16) -> Option<&'static str> {
Some(match code {
1 => "TEXT",
2 => "ATTRIB",
3 => "ATTDEF",
4 => "BLOCK",
5 => "ENDBLK",
6 => "SEQEND",
7 => "INSERT",
8 => "MINSERT",
10..=14 => "VERTEX",
15 | 16 | 29 | 30 => "POLYLINE",
17 => "ARC",
18 => "CIRCLE",
19 => "LINE",
20..=26 => "DIMENSION",
27 => "POINT",
28 => "3DFACE",
31 => "SOLID",
32 => "TRACE",
33 => "SHAPE",
34 => "VIEWPORT",
35 => "ELLIPSE",
36 => "SPLINE",
37 => "REGION",
38 => "3DSOLID",
39 => "BODY",
40 => "RAY",
41 => "XLINE",
42 => "DICTIONARY",
43 => "OLEFRAME",
44 => "MTEXT",
45 => "LEADER",
46 => "TOLERANCE",
47 => "MLINE",
48 => "BLOCK_CONTROL",
49 => "BLOCK_RECORD",
50 => "LAYER_CONTROL",
51 => "LAYER",
52 => "STYLE_CONTROL",
53 => "STYLE",
56 => "LTYPE_CONTROL",
57 => "LTYPE",
60 => "VIEW_CONTROL",
61 => "VIEW",
62 => "UCS_CONTROL",
63 => "UCS",
64 => "VPORT_CONTROL",
65 => "VPORT",
66 => "APPID_CONTROL",
67 => "APPID",
68 => "DIMSTYLE_CONTROL",
69 => "DIMSTYLE",
70 => "VX_CONTROL",
71 => "VX_TABLE_RECORD",
72 => "GROUP",
73 => "MLINESTYLE",
74 => "OLE2FRAME",
77 => "LWPOLYLINE",
78 => "HATCH",
79 => "XRECORD",
80 => "ACDBPLACEHOLDER",
82 => "LAYOUT",
_ => return None,
})
}
/// Merged table cells onto the cells. acadrust 0.6.3 reads a 2010+ (AC1024+) DWG table's
/// merged cells into the table's `merged_ranges` only, while its DXF writer writes each cell's
/// own merge groups (173, 175, 176), so without this the merges would be lost. Tables whose
/// cells already carry merges are left alone. Each range's first cell gets the span; the
/// cells it covers are marked merged with no span of their own, as CADCraft's DXF writer does.
fn table_merges(doc: &mut acadrust::CadDocument) {
for e in doc.entities_mut() {
let acadrust::entities::EntityType::Table(t) = e else { continue };
if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) {
continue;
}
let (rows, cols) = (t.rows.len(), t.columns.len());
// A real table has at most one merge per cell; more ranges than that come from a
// damaged file and would only make this rows × cols × ranges.
let max_ranges = rows.saturating_mul(cols).min(1 << 16);
for r in t.merged_ranges.iter().take(max_ranges).cloned().collect::<Vec<_>>() {
// Clamp to the table: the ranges come from the file.
let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1)));
if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) {
continue;
}
let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX);
for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) {
for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) {
cell.merged = 1;
let first = (ri, ci) == (r.top_row, r.left_col);
cell.merge_width = if first { span(right - r.left_col) } else { 0 };
cell.merge_height = if first { span(bottom - r.top_row) } else { 0 };
}
}
}
}
}
/// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps
/// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while
/// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields
/// (groups 280, 281). `to_flags` copies the fields into the flags before a DWG is written;
/// otherwise the flags are copied into the fields after one is read. Older versions store
/// both and are left alone.
fn table_style_rows(doc: &mut acadrust::CadDocument, to_flags: bool) {
use acadrust::objects::{ObjectType, TableStyleFlags};
if doc.version < acadrust::DxfVersion::AC1024 {
return;
}
for o in doc.objects.values_mut() {
let ObjectType::TableStyle(s) = o else { continue };
for (bit, suppressed) in
[(TableStyleFlags::TITLE_SUPPRESSED, &mut s.title_suppressed), (TableStyleFlags::HEADER_SUPPRESSED, &mut s.header_suppressed)]
{
if to_flags {
s.flags.set(bit, *suppressed);
} else {
*suppressed = s.flags.contains(bit);
}
}
}
}
/// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification,
/// common dimension data), which acadrust keeps no copy of from DXF: it is set here as
/// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128,
/// acadrust 0.6.5 reads and writes itself.
fn dimension_flags(doc: &mut acadrust::CadDocument) {
for e in doc.entities_mut() {
let acadrust::entities::EntityType::Dimension(d) = e else { continue };
d.base_mut().dwg_flags_byte |= 0x02;
}
}
/// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses
/// (#1482). A drawing that once came from MicroStation can carry hundreds of thousands of
/// them, orphaned copies piled up by earlier DGN imports and copy-pastes (AutoCAD's PURGE
/// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053
/// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file
/// didn't open at all. No definition that was read refers to them (a definition the reader
/// skipped can't use them either) and CADCraft doesn't draw DGN line styles, so nothing
/// visible is lost.
/// Every component a definition reaches (directly, or through compound and point
/// components) is kept, as are the definitions; dictionary entries that named a dropped
/// component go with it. Returns how many were left out.
fn drop_orphaned_dgn_components(doc: &mut acadrust::CadDocument) -> usize {
use acadrust::objects::{DgnLineStyleData, ObjectType};
use std::collections::{HashMap, HashSet};
// Each component's references, and the definitions' root components to start from.
let mut refs: HashMap<acadrust::Handle, Vec<acadrust::Handle>> = HashMap::new();
let mut stack: Vec<acadrust::Handle> = Vec::new();
for (h, o) in &doc.objects {
let ObjectType::DgnLineStyle(ls) = o else { continue };
match &ls.data {
DgnLineStyleData::Definition { root_component, .. } => stack.push(*root_component),
DgnLineStyleData::Component { component, .. } => {
refs.insert(*h, component.references());
}
DgnLineStyleData::Registered { .. } => {}
}
}
if refs.is_empty() {
return 0;
}
// Each component is visited once, so cycles and shared subtrees end.
let mut used: HashSet<acadrust::Handle> = HashSet::new();
while let Some(h) = stack.pop() {
if let Some(r) = refs.get(&h)
&& used.insert(h)
{
stack.extend(r.iter().copied());
}
}
let orphans: HashSet<acadrust::Handle> = refs.into_keys().filter(|h| !used.contains(h)).collect();
if orphans.is_empty() {
return 0;
}
doc.objects.retain(|h, _| !orphans.contains(h));
doc.dgn_ls_components.retain(|h, _| !orphans.contains(h));
for o in doc.objects.values_mut() {
let ObjectType::Dictionary(d) = o else { continue };
if d.entries.iter().any(|(_, e)| orphans.contains(e)) {
d.entries.retain(|(_, e)| !orphans.contains(e));
let keys: HashSet<&str> = d.entries.iter().map(|(k, _)| k.as_str()).collect();
d.hard_owner_entries.retain(|k| keys.contains(k.as_str()));
}
}
orphans.len()
}
/// Leave out what acadrust can't write as this DWG version: other programs' custom entities
/// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file
/// for one of them (0.6.3 left them out); CADCraft already tells the user which entity types
/// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many.
fn drop_unwritable(doc: &mut acadrust::CadDocument) -> usize {
let version = doc.version;
let unwritable: Vec<acadrust::Handle> = doc
.entities()
.filter_map(|e| match e {
acadrust::entities::EntityType::Unknown(u)
if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 =>
{
Some(u.common.handle)
}
_ => None,
})
.collect();
for h in &unwritable {
doc.remove_entity(*h);
}
let objects: Vec<acadrust::Handle> = doc
.objects
.iter()
.filter_map(|(h, o)| match o {
acadrust::objects::ObjectType::Unknown { raw_dwg_data, raw_dwg_version, .. }
if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 =>
{
Some(*h)
}
_ => None,
})
.collect();
for h in &objects {
doc.objects.remove(h);
}
unwritable.len() + objects.len()
}
/// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of
/// the HEADER section: (name, group code, value).
fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] {
[
("$ANGBASE", 50, h.angle_base.to_string()),
// DWG holds radians; `$ANGBASE` is in degrees.
("$ANGBASE", 50, h.angle_base.to_degrees().to_string()),
("$ANGDIR", 70, h.angle_direction.to_string()),
("$FILLETRAD", 40, h.fillet_radius.to_string()),
("$CHAMFERA", 40, h.chamfer_distance_a.to_string()),
@@ -146,28 +460,138 @@ 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<Vec<u8>, String> {
convert(dxf, None)
}
/// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"),
/// whatever version the DXF declares.
pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result<Vec<u8>, String> {
let v = match version.trim().to_ascii_uppercase().as_str() {
"AC1015" => acadrust::DxfVersion::AC1015,
"AC1018" => acadrust::DxfVersion::AC1018,
"AC1021" => acadrust::DxfVersion::AC1021,
"AC1024" => acadrust::DxfVersion::AC1024,
"AC1027" => acadrust::DxfVersion::AC1027,
"AC1032" => acadrust::DxfVersion::AC1032,
_ => return Err(super::unsupported(version)),
};
convert(dxf, Some(v))
}
/// The current dimension and text styles' names from their handles: a DWG stores the
/// handles, and the reader leaves the names at "Standard", so a drawing reopened from DWG
/// lost its current dimension style (#1051).
fn current_style_names(doc: &mut acadrust::CadDocument) {
let h = doc.header.current_dimstyle_handle;
if let Some(n) = doc.dim_styles.iter().find(|ds| ds.handle == h && !h.is_null()).map(|ds| ds.name.clone()) {
doc.header.current_dimstyle_name = n;
}
let h = doc.header.current_text_style_handle;
if let Some(n) = doc.text_styles.iter().find(|ts| ts.handle == h && !h.is_null()).map(|ts| ts.name.clone()) {
doc.header.current_text_style_name = n;
}
}
/// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the
/// handle read with it needn't be the style's in the document, in which case the DWG writer
/// fell back to Standard and AutoCAD opened the drawing with Standard current (#1051).
fn current_dimstyle(doc: &mut acadrust::CadDocument) {
let name = doc.header.current_dimstyle_name.clone();
if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) {
doc.header.current_dimstyle_handle = h;
}
}
/// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]:
/// the handle read with the DXF needn't be the style's in the document, in which case the DWG
/// writer fell back to Standard and AutoCAD opened the drawing with Standard current (#1650).
fn current_text_style(doc: &mut acadrust::CadDocument) {
let name = doc.header.current_text_style_name.clone();
if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) {
doc.header.current_text_style_handle = h;
}
}
fn convert(dxf: &[u8], version: Option<acadrust::DxfVersion>) -> Result<Vec<u8>, 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
// runs inside `catch_unwind` so a decode failure is reported rather than crashing.
if dxf.len() > Limits::DEFAULT.max_dxf_bytes {
return Err(format!(
"DXF: the input is {}, larger than the {} CADCraft converts to DWG",
mb(dxf.len() as u64),
mb(Limits::DEFAULT.max_dxf_bytes as u64)
));
}
let data = dxf.to_vec();
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}"))?;
// Write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG has no true colours, transparency,
// table styles or gradients, and readers can't tell its layouts apart reliably. The DXF
// stays R2000; only the DWG is newer.
if doc.version < MIN_DWG_VERSION {
doc.version = MIN_DWG_VERSION;
match version {
Some(v) => doc.version = v,
// Without a version asked for, write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG
// has no true colours, transparency, table styles or gradients. The DXF stays R2000;
// only the DWG is newer.
None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION,
None => {}
}
other_layout_owners(&mut doc);
table_style_rows(&mut doc, true);
dimension_flags(&mut doc);
drop_unwritable(&mut doc);
current_dimstyle(&mut doc);
current_text_style(&mut doc);
std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc)))
.map_err(|_| "the DWG writer failed on this drawing".to_string())?
.map_err(|e| format!("DWG write: {e}"))
}
/// Entities of a layout other than the one in `*Paper_Space` are written owned by their block
/// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1,
/// "paper space", which AutoCAD reads as the `*Paper_Space` block's: everything drawn on a
/// second layout landed on the first one, and the second stayed empty (#1057).
fn other_layout_owners(doc: &mut acadrust::CadDocument) {
let others: std::collections::HashSet<acadrust::Handle> = doc
.block_records
.iter()
.filter(|br| {
let n = br.name.to_ascii_uppercase();
n.len() > 12 && n.starts_with("*PAPER_SPACE") && n[12..].bytes().all(|b| b.is_ascii_digit())
})
.map(|br| br.handle)
.collect();
if others.is_empty() {
return;
}
for e in doc.entities_mut() {
let c = e.common_mut();
if others.contains(&c.owner_handle) {
c.entity_mode = Some(0);
}
}
acadrust::DwgWriter::write_to_vec(&doc).map_err(|e| format!("DWG write: {e}"))
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use native::{dwg_to_dxf, dwg_to_dxf_with, dxf_to_dwg};
pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as};
/// The error for a DWG version CADCraft can't write.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn unsupported(version: &str) -> String {
let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect();
format!("DWG version `{version}` can't be written (CADCraft writes {})", list.join(", "))
}
#[cfg(target_arch = "wasm32")]
pub fn dwg_to_dxf(_bytes: &[u8]) -> Result<Vec<u8>, String> {
Err("DWG files can't be opened in the web build yet; save as DXF".into())
}
#[cfg(target_arch = "wasm32")]
pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec<u8>, Vec<String>), String> {
Err("DWG files can't be opened in the web build yet; save as DXF".into())
}
#[cfg(target_arch = "wasm32")]
pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result<Vec<u8>, String> {
Err("DWG files can't be opened in the web build yet; save as DXF".into())
}
@@ -175,6 +599,10 @@ pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result<Vec<u8>, String
pub fn dxf_to_dwg(_dxf: &[u8]) -> Result<Vec<u8>, String> {
Err("DWG files can't be written in the web build yet; save as DXF".into())
}
#[cfg(target_arch = "wasm32")]
pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result<Vec<u8>, String> {
Err("DWG files can't be written in the web build yet; save as DXF".into())
}
#[cfg(test)]
mod tests {
@@ -187,9 +615,232 @@ mod tests {
assert_eq!(version(b"AC1018xxxx").as_deref(), Some("AC1018"));
}
/// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not
/// Standard: the DXF names the style, and the handle read with it was Standard's (#1650).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn current_text_style_reaches_the_dwg() {
let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n";
let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n";
let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n");
let dxf = format!("{header} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n");
let dwg = dxf_to_dwg(dxf.as_bytes()).unwrap();
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap();
let romans = doc.text_styles.iter().find(|ts| ts.name == "ROMANS").map(|ts| ts.handle);
assert!(romans.is_some(), "ROMANS is missing from the DWG");
assert_eq!(Some(doc.header.current_text_style_handle), romans);
}
#[test]
fn garbage_is_an_error_not_a_crash() {
assert!(dwg_to_dxf(b"AC1032 this is not a dwg file at all").is_err());
assert!(dwg_to_dxf(b"").is_err());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn dxf_to_dwg_rejects_garbage_without_crashing() {
// The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures
// rather than crashing (and rejects oversized input before decoding).
assert!(dxf_to_dwg(b"not a dxf file").is_err());
assert!(dxf_to_dwg(b"").is_err());
}
/// A DXF with one DIMENSION per (text, group 70, subclass, points) row.
#[cfg(not(target_arch = "wasm32"))]
fn dims_dxf(dims: &[(&str, i64, &str, &[(i32, [f64; 2])])]) -> String {
let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n");
for (text, flags, sub, pts) in dims {
s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n";
s += &format!(" 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n");
for (code, [x, y]) in pts.iter() {
s += &format!("{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20);
}
}
s + " 0\nENDSEC\n 0\nEOF\n"
}
/// DWG stores DXF group 70's bit 128 inverted, in bit 0 of the dimension flags byte (set:
/// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common
/// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way
/// as the writer can't hide a wrong byte.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() {
let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])];
let radius: &[(i32, [f64; 2])] = &[(15, [10.0, 0.0])];
let angular: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [10.0, 0.0]), (15, [0.0, 0.0]), (16, [0.0, 10.0])];
let kinds = [
(0, "AcDbAlignedDimension", linear),
(1, "AcDbAlignedDimension", linear),
(4, "AcDbRadialDimension", radius),
(2, "AcDb2LineAngularDimension", angular),
];
let mut dims = Vec::new();
for (ty, sub, pts) in kinds {
dims.push(("HOME", ty | 32, sub, pts));
dims.push(("MOVED", ty | 32 | 128, sub, pts));
}
let dwg = dxf_to_dwg(dims_dxf(&dims).as_bytes()).unwrap();
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap();
let mut seen = Vec::new();
for e in doc.entities() {
let acadrust::entities::EntityType::Dimension(d) = e else { continue };
let (text, byte) = (d.base().text_override().unwrap_or_default(), d.base().dwg_flags_byte);
seen.push((text.to_string(), byte & 0x03));
assert_eq!(byte & 0x02, 0x02, "{text} {:?}: bit 32 of group 70 is lost (flags byte {byte:#04x})", d.base().dimension_type);
let default_pos = text == "HOME";
assert_eq!(byte & 0x01 != 0, default_pos, "{text} {:?}: flags byte {byte:#04x}", d.base().dimension_type);
}
for text in ["HOME", "MOVED"] {
assert_eq!(seen.iter().filter(|(t, _)| t == text).count(), 4, "{seen:?}");
}
// And CADCraft reads its own DWG back as it wrote it: 128 only on the moved texts.
let dxf = String::from_utf8(dwg_to_dxf(&dwg).unwrap()).unwrap();
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
let mut flags = Vec::new();
for rec in lines.chunks(2).collect::<Vec<_>>().split(|p| p.first() == Some(&"0")) {
let value = |code: &str| rec.iter().find(|p| p.first() == Some(&code)).and_then(|p| p.get(1).copied());
if let (Some(text @ ("HOME" | "MOVED")), Some(v)) = (value("1"), value("70")) {
flags.push((text, v.parse::<i64>().unwrap_or(-1) & 128));
}
}
assert_eq!(flags.len(), 8, "{flags:?}");
assert!(flags.iter().all(|(l, f)| (*f == 128) == (*l == "MOVED")), "{flags:?}");
}
/// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369).
#[cfg(not(target_arch = "wasm32"))]
fn dxf_handles(dxf: &str) -> std::collections::HashSet<u64> {
let lines: Vec<&str> = dxf.lines().collect();
lines
.chunks(2)
.filter_map(|p| match p {
[c, v] if matches!(c.trim().parse::<i32>(), Ok(5 | 105 | 330..=369)) => u64::from_str_radix(v.trim(), 16).ok(),
_ => None,
})
.collect()
}
/// Issue #1482: a DWG that once came from MicroStation can carry hundreds of thousands of DGN
/// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a
/// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and
/// their dictionary entries with them; the definition and every component it reaches —
/// through compound and point components, around a cycle — are kept.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn orphaned_dgn_line_style_components_are_left_out() {
use acadrust::objects::*;
let mut doc = acadrust::CadDocument::new();
let container = doc.allocate_handle();
let nod = doc.header.named_objects_dict_handle;
let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&nod) else { panic!("no named object dictionary") };
root.entries.push(("ACAD_DGNLINESTYLECOMP".into(), container));
let pattern = || DgnLsStrokePattern {
has_iteration_limit: false,
is_single_segment: false,
iteration_limit: 0,
auto_phase: 0.0,
phase: 0.0,
phase_mode: DgnLsPhaseMode::Distance,
strokes: vec![DgnLsStroke {
is_dash: true,
bypass_corner: false,
can_be_scaled: true,
invert_at_origin: false,
invert_at_end: false,
length: 2.5,
start_width: 0.0,
end_width: 0.0,
width_mode: 0,
cap_mode: 0,
}],
};
let kind = |c: &DgnLsComponentData| match c {
DgnLsComponentData::Symbol(_) => DgnLsComponentType::Symbol,
DgnLsComponentData::Compound(_) => DgnLsComponentType::Compound,
DgnLsComponentData::Stroke(_) => DgnLsComponentType::Stroke,
DgnLsComponentData::Point(_) => DgnLsComponentType::Point,
DgnLsComponentData::Internal(_) => DgnLsComponentType::Internal,
};
let compound = |of: &[acadrust::Handle]| {
DgnLsComponentData::Compound(DgnLsCompoundComponent {
entries: of.iter().map(|&component| DgnLsCompoundEntry { component, offset: 0.0 }).collect(),
})
};
let mut entries = Vec::new();
let mut put = |doc: &mut acadrust::CadDocument, h: acadrust::Handle, data: DgnLineStyleData| {
entries.push((format!("{:X}", h.value()), h));
let reactors = vec![container];
doc.objects
.insert(h, ObjectType::DgnLineStyle(DgnLineStyleObject { handle: h, owner: container, reactors, xdictionary_handle: None, data }));
};
let component = |c: DgnLsComponentData| DgnLineStyleData::Component {
kind: kind(&c),
description: "dash".into(),
version: 1,
component_uid: [7; 16],
scale: 1.0,
property_flags: 0,
component: c,
properties: vec![],
};
let h: Vec<acadrust::Handle> = (0..9).map(|_| doc.allocate_handle()).collect();
let [def, root, stroke, point, back, orphan, orphan_cycle, internal, shared] = h[..] else { panic!("nine handles") };
put(
&mut doc,
def,
DgnLineStyleData::Definition {
description: "{ dash }".into(),
version: 1,
style_number: 1,
component_uid: [1; 16],
is_continuous: false,
unit_definition: 1.0,
unit_scale: 1.0,
units_type: 0,
is_element: false,
is_physical: false,
is_scale_independent: false,
is_snappable: false,
root_component: root,
properties: vec![],
},
);
// Used: def → root → {stroke, point → shared, back → root (a cycle)}.
put(&mut doc, root, component(compound(&[stroke, point, back])));
put(&mut doc, stroke, component(DgnLsComponentData::Stroke(pattern())));
put(&mut doc, point, component(DgnLsComponentData::Point(DgnLsPointComponent { stroke_component: shared, symbols: vec![] })));
put(&mut doc, back, component(compound(&[root])));
put(&mut doc, shared, component(DgnLsComponentData::Stroke(pattern())));
// Orphans: an internal component, and two compounds that refer to each other and to a
// used component (which stays).
let pattern_internal =
DgnLsInternalComponent { pattern: pattern(), internal_version: 0, hardware_style: 0, is_hardware_style: false, line_code: 0 };
put(&mut doc, internal, component(DgnLsComponentData::Internal(pattern_internal)));
put(&mut doc, orphan, component(compound(&[orphan_cycle, shared])));
put(&mut doc, orphan_cycle, component(compound(&[orphan])));
let mut dict = Dictionary::new();
dict.handle = container;
dict.owner = nod;
dict.entries = entries;
doc.objects.insert(container, ObjectType::Dictionary(dict));
let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap();
let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap();
let dxf = String::from_utf8(dxf).unwrap();
let handles = dxf_handles(&dxf);
for kept in [def, root, stroke, point, back, shared] {
assert!(handles.contains(&kept.value()), "{:X} was left out", kept.value());
}
for gone in [internal, orphan, orphan_cycle] {
assert!(!handles.contains(&gone.value()), "{:X} was kept or is still referred to", gone.value());
}
let lines: Vec<&str> = dxf.lines().collect();
let ls: Vec<&str> = lines.chunks(2).filter_map(|p| p.get(1).filter(|_| p[0].trim() == "0" && p[1].starts_with("LS")).copied()).collect();
assert_eq!(ls.iter().filter(|t| t.ends_with("COMPONENT")).count(), 5, "{ls:?}");
assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}");
assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]);
}
}
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cadcraft-dxf"
description = "Standalone DXF tag reader/writer (ASCII and binary), from the published DXF reference"
description = "Standalone DXF tag reader/writer (ASCII and binary, pre-2007 code pages), from the published DXF reference"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -10,3 +10,5 @@ workspace = true
[dependencies]
thiserror = { workspace = true }
log = { workspace = true }
encoding_rs = { workspace = true }
+294
View File
@@ -0,0 +1,294 @@
//! Text decoding for DXF files.
//!
//! R2007 (AC1021) and later DXF files are UTF-8. Older ones store text in the code page named by
//! the `$DWGCODEPAGE` header variable (`ANSI_1252`, `ANSI_932`, `DOS850`, …); characters outside
//! it are written as `\U+XXXX` (any character) or `\M+nXXXX` (a double-byte character of an East
//! Asian code page) escapes, which [`crate::parse`] decodes after the bytes.
//!
//! The Windows, ISO and East Asian code pages are decoded with `encoding_rs`; DOS 437, 850 and
//! 852 with the tables below (the upper halves of the IBM PC code pages; the lower halves are
//! ASCII). Decoding never fails: a byte sequence that is invalid in the code page (a truncated
//! double-byte character, an unassigned byte) becomes U+FFFD and the bytes after it decode
//! normally, so line ends and the group structure survive.
use std::borrow::Cow;
use encoding_rs::Encoding;
/// How the bytes of a code page become text.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Decoder {
Utf8,
Encoding(&'static Encoding),
/// Single-byte DOS code page: ASCII, then these 128 characters for bytes 0x80–0xFF.
Table(&'static [char; 128]),
}
/// The decoder for a `$DWGCODEPAGE` value (case-insensitive), or `None` when CADCraft doesn't
/// know the code page.
pub(crate) fn decoder(code_page: &str) -> Option<Decoder> {
use encoding_rs as e;
let name = code_page.trim().to_ascii_uppercase().replace(['-', ' '], "_");
let enc = match name.as_str() {
"UTF8" | "UTF_8" | "UNICODE" => return Some(Decoder::Utf8),
"ASCII" | "ANSI_1252" | "ISO8859_1" | "ISO_8859_1" => e::WINDOWS_1252,
"ANSI_874" => e::WINDOWS_874,
"ANSI_932" | "DOS932" | "SHIFT_JIS" => e::SHIFT_JIS,
"ANSI_936" | "GB2312" | "GBK" => e::GBK,
"ANSI_949" | "KSC5601" | "KOREAN" => e::EUC_KR,
"ANSI_950" | "BIG5" => e::BIG5,
"ANSI_1250" => e::WINDOWS_1250,
"ANSI_1251" => e::WINDOWS_1251,
"ANSI_1253" => e::WINDOWS_1253,
"ANSI_1254" | "ISO8859_9" | "ISO_8859_9" => e::WINDOWS_1254,
"ANSI_1255" => e::WINDOWS_1255,
"ANSI_1256" => e::WINDOWS_1256,
"ANSI_1257" => e::WINDOWS_1257,
"ANSI_1258" => e::WINDOWS_1258,
"ISO8859_2" | "ISO_8859_2" => e::ISO_8859_2,
"ISO8859_3" | "ISO_8859_3" => e::ISO_8859_3,
"ISO8859_4" | "ISO_8859_4" => e::ISO_8859_4,
"ISO8859_5" | "ISO_8859_5" => e::ISO_8859_5,
"ISO8859_6" | "ISO_8859_6" => e::ISO_8859_6,
"ISO8859_7" | "ISO_8859_7" => e::ISO_8859_7,
"ISO8859_8" | "ISO_8859_8" => e::ISO_8859_8,
"DOS866" => e::IBM866,
"MACINTOSH" | "MAC_ROMAN" => e::MACINTOSH,
"DOS437" => return Some(Decoder::Table(&DOS437)),
"DOS850" => return Some(Decoder::Table(&DOS850)),
"DOS852" => return Some(Decoder::Table(&DOS852)),
_ => return None,
};
Some(Decoder::Encoding(enc))
}
/// Decode `bytes` from the code page `code_page` names (a `$DWGCODEPAGE` value such as
/// `ANSI_1251`), or `None` when CADCraft doesn't know that code page. Invalid sequences become
/// U+FFFD; escapes (`\U+XXXX`, `\M+nXXXX`) are left as they are.
pub fn decode_code_page(bytes: &[u8], code_page: &str) -> Option<String> {
decoder(code_page).map(|d| decode(bytes, d).into_owned())
}
/// Decode bytes with a decoder. UTF-8 that isn't valid falls back to Windows-1252.
pub(crate) fn decode(bytes: &[u8], d: Decoder) -> Cow<'_, str> {
match d {
Decoder::Utf8 => match std::str::from_utf8(bytes) {
Ok(s) => Cow::Borrowed(s),
Err(_) => encoding_rs::WINDOWS_1252.decode_without_bom_handling(bytes).0,
},
Decoder::Encoding(e) => e.decode_without_bom_handling(bytes).0,
Decoder::Table(t) => match std::str::from_utf8(bytes) {
Ok(s) if s.is_ascii() => Cow::Borrowed(s),
_ => Cow::Owned(
bytes
.iter()
.map(|&b| if b.is_ascii() { char::from(b) } else { t.get(usize::from(b & 0x7F)).copied().unwrap_or('\u{FFFD}') })
.collect(),
),
},
}
}
/// The `$DWGCODEPAGE` value of an ASCII DXF file: the line two lines after a `$DWGCODEPAGE`
/// 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);
while let Some(line) = lines.next() {
if line == b"ENDSEC" {
return None;
}
if line.eq_ignore_ascii_case(b"$DWGCODEPAGE") {
return match (lines.next(), lines.next()) {
(Some(b"3"), Some(value)) => Some(value),
_ => None,
};
}
}
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.
pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> {
if let Ok(s) = std::str::from_utf8(bytes) {
return Cow::Borrowed(s);
}
let d = match ascii_code_page(bytes) {
Some(name) => {
let name = String::from_utf8_lossy(name);
decoder(&name).unwrap_or_else(|| {
log::warn!("DXF: unknown code page `{name}`; reading the text as ANSI_1252");
Decoder::Utf8
})
}
None => Decoder::Utf8,
};
decode(bytes, d)
}
/// The text state of a binary DXF file, learnt from its 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)]
pub(crate) struct BinaryText {
/// The header variable whose value comes next (after a group 9).
var: Option<HeaderVar>,
utf8: bool,
code_page: Option<Decoder>,
}
#[derive(Clone, Copy, PartialEq)]
enum HeaderVar {
AcadVer,
CodePage,
}
impl BinaryText {
/// 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.
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();
match (code, self.var.take()) {
(9, _) => {
self.var = match s.trim() {
"$ACADVER" => Some(HeaderVar::AcadVer),
"$DWGCODEPAGE" => Some(HeaderVar::CodePage),
_ => None,
}
}
(1, Some(HeaderVar::AcadVer)) => self.utf8 = is_utf8_version(&s),
(3, Some(HeaderVar::CodePage)) => {
self.code_page = decoder(&s);
if self.code_page.is_none() {
log::warn!("DXF: unknown code page `{}`; reading the text as ANSI_1252", s.trim());
}
}
_ => {}
}
s
}
}
/// True for an `$ACADVER` of R2007 (AC1021) or later, whose text is UTF-8.
fn is_utf8_version(acadver: &str) -> bool {
acadver.trim().strip_prefix("AC").and_then(|n| n.parse::<u32>().ok()).is_some_and(|n| n >= 1021)
}
/// The double-byte code page of a `\M+n` escape: 1 Japanese (Shift-JIS), 2 Traditional Chinese
/// (Big5), 3 Korean (Wansung), 5 Simplified Chinese (GB 2312). 4 (Korean Johab) is not
/// supported, so its escapes stay literal.
pub(crate) fn mif_encoding(n: char) -> Option<&'static Encoding> {
match n {
'1' => Some(encoding_rs::SHIFT_JIS),
'2' => Some(encoding_rs::BIG5),
'3' => Some(encoding_rs::EUC_KR),
'5' => Some(encoding_rs::GBK),
_ => None,
}
}
// Generated from the IBM PC code page definitions (bytes 0x80–0xFF in order).
const DOS437: [char; 128] = [
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{00E0}', '\u{00E5}', '\u{00E7}', '\u{00EA}', '\u{00EB}', '\u{00E8}', '\u{00EF}',
'\u{00EE}', '\u{00EC}', '\u{00C4}', '\u{00C5}', '\u{00C9}', '\u{00E6}', '\u{00C6}', '\u{00F4}', '\u{00F6}', '\u{00F2}', '\u{00FB}', '\u{00F9}',
'\u{00FF}', '\u{00D6}', '\u{00DC}', '\u{00A2}', '\u{00A3}', '\u{00A5}', '\u{20A7}', '\u{0192}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}',
'\u{00F1}', '\u{00D1}', '\u{00AA}', '\u{00BA}', '\u{00BF}', '\u{2310}', '\u{00AC}', '\u{00BD}', '\u{00BC}', '\u{00A1}', '\u{00AB}', '\u{00BB}',
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{2561}', '\u{2562}', '\u{2556}', '\u{2555}', '\u{2563}', '\u{2551}', '\u{2557}',
'\u{255D}', '\u{255C}', '\u{255B}', '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{255E}', '\u{255F}',
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{2567}', '\u{2568}', '\u{2564}', '\u{2565}', '\u{2559}',
'\u{2558}', '\u{2552}', '\u{2553}', '\u{256B}', '\u{256A}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{258C}', '\u{2590}', '\u{2580}',
'\u{03B1}', '\u{00DF}', '\u{0393}', '\u{03C0}', '\u{03A3}', '\u{03C3}', '\u{00B5}', '\u{03C4}', '\u{03A6}', '\u{0398}', '\u{03A9}', '\u{03B4}',
'\u{221E}', '\u{03C6}', '\u{03B5}', '\u{2229}', '\u{2261}', '\u{00B1}', '\u{2265}', '\u{2264}', '\u{2320}', '\u{2321}', '\u{00F7}', '\u{2248}',
'\u{00B0}', '\u{2219}', '\u{00B7}', '\u{221A}', '\u{207F}', '\u{00B2}', '\u{25A0}', '\u{00A0}',
];
const DOS850: [char; 128] = [
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{00E0}', '\u{00E5}', '\u{00E7}', '\u{00EA}', '\u{00EB}', '\u{00E8}', '\u{00EF}',
'\u{00EE}', '\u{00EC}', '\u{00C4}', '\u{00C5}', '\u{00C9}', '\u{00E6}', '\u{00C6}', '\u{00F4}', '\u{00F6}', '\u{00F2}', '\u{00FB}', '\u{00F9}',
'\u{00FF}', '\u{00D6}', '\u{00DC}', '\u{00F8}', '\u{00A3}', '\u{00D8}', '\u{00D7}', '\u{0192}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}',
'\u{00F1}', '\u{00D1}', '\u{00AA}', '\u{00BA}', '\u{00BF}', '\u{00AE}', '\u{00AC}', '\u{00BD}', '\u{00BC}', '\u{00A1}', '\u{00AB}', '\u{00BB}',
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{00C1}', '\u{00C2}', '\u{00C0}', '\u{00A9}', '\u{2563}', '\u{2551}', '\u{2557}',
'\u{255D}', '\u{00A2}', '\u{00A5}', '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{00E3}', '\u{00C3}',
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{00A4}', '\u{00F0}', '\u{00D0}', '\u{00CA}', '\u{00CB}',
'\u{00C8}', '\u{0131}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{00A6}', '\u{00CC}', '\u{2580}',
'\u{00D3}', '\u{00DF}', '\u{00D4}', '\u{00D2}', '\u{00F5}', '\u{00D5}', '\u{00B5}', '\u{00FE}', '\u{00DE}', '\u{00DA}', '\u{00DB}', '\u{00D9}',
'\u{00FD}', '\u{00DD}', '\u{00AF}', '\u{00B4}', '\u{00AD}', '\u{00B1}', '\u{2017}', '\u{00BE}', '\u{00B6}', '\u{00A7}', '\u{00F7}', '\u{00B8}',
'\u{00B0}', '\u{00A8}', '\u{00B7}', '\u{00B9}', '\u{00B3}', '\u{00B2}', '\u{25A0}', '\u{00A0}',
];
const DOS852: [char; 128] = [
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{016F}', '\u{0107}', '\u{00E7}', '\u{0142}', '\u{00EB}', '\u{0150}', '\u{0151}',
'\u{00EE}', '\u{0179}', '\u{00C4}', '\u{0106}', '\u{00C9}', '\u{0139}', '\u{013A}', '\u{00F4}', '\u{00F6}', '\u{013D}', '\u{013E}', '\u{015A}',
'\u{015B}', '\u{00D6}', '\u{00DC}', '\u{0164}', '\u{0165}', '\u{0141}', '\u{00D7}', '\u{010D}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}',
'\u{0104}', '\u{0105}', '\u{017D}', '\u{017E}', '\u{0118}', '\u{0119}', '\u{00AC}', '\u{017A}', '\u{010C}', '\u{015F}', '\u{00AB}', '\u{00BB}',
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{00C1}', '\u{00C2}', '\u{011A}', '\u{015E}', '\u{2563}', '\u{2551}', '\u{2557}',
'\u{255D}', '\u{017B}', '\u{017C}', '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{0102}', '\u{0103}',
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{00A4}', '\u{0111}', '\u{0110}', '\u{010E}', '\u{00CB}',
'\u{010F}', '\u{0147}', '\u{00CD}', '\u{00CE}', '\u{011B}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{0162}', '\u{016E}', '\u{2580}',
'\u{00D3}', '\u{00DF}', '\u{00D4}', '\u{0143}', '\u{0144}', '\u{0148}', '\u{0160}', '\u{0161}', '\u{0154}', '\u{00DA}', '\u{0155}', '\u{0170}',
'\u{00FD}', '\u{00DD}', '\u{0163}', '\u{00B4}', '\u{00AD}', '\u{02DD}', '\u{02DB}', '\u{02C7}', '\u{02D8}', '\u{00A7}', '\u{00F7}', '\u{00B8}',
'\u{00B0}', '\u{00A8}', '\u{02D9}', '\u{0171}', '\u{0158}', '\u{0159}', '\u{25A0}', '\u{00A0}',
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn code_page_names() {
let d = |bytes: &[u8], cp: &str| decode_code_page(bytes, cp);
assert_eq!(d(b"\xCF\xF0\xE8\xE2\xE5\xF2", "ANSI_1251").as_deref(), Some("Привет"));
assert_eq!(d(b"\xCF\xF0\xE8\xE2\xE5\xF2", " ansi_1251 ").as_deref(), Some("Привет"));
assert_eq!(d(b"\x90\x7D\x96\xCA", "ANSI_932").as_deref(), Some("図面"));
assert_eq!(d(b"\xCD\xBC\xB2\xE3", "GB2312").as_deref(), Some("图层"));
assert_eq!(d(b"\xB9\xCF\xBC\x68", "BIG5").as_deref(), Some("圖層"));
assert_eq!(d(b"\xB5\xB5\xB8\xE9", "ANSI_949").as_deref(), Some("도면"));
assert_eq!(d(b"\xD3\xF7\xDD\xE4\xE9\xEF", "ANSI_1253").as_deref(), Some("Σχέδιο"));
assert_eq!(d(b"\xC0\xD2\xBE", "ANSI_874").as_deref(), Some("ภาพ"));
assert_eq!(d(b"\x80", "ANSI_1252").as_deref(), Some("€"));
// DOS 437 and 850 agree on letters but differ on 0x9B (¢ / ø).
assert_eq!(d(b"Gr\x94\xE1e \x9B", "DOS437").as_deref(), Some("Größe ¢"));
assert_eq!(d(b"Gr\x94\xE1e \x9B", "dos850").as_deref(), Some("Größe ø"));
assert_eq!(d(b"\xBD\xA2\x88w", "DOS852").as_deref(), Some("Żółw"));
assert_eq!(d(b"\x91\xAB\xAE\xA9", "DOS866").as_deref(), Some("Слой"));
assert_eq!(d("é".as_bytes(), "UTF8").as_deref(), Some("é"));
assert_eq!(d(b"x", "ANSI_1361"), None);
assert_eq!(d(b"x", "EBCDIC"), None);
assert_eq!(d(b"x", ""), None);
}
#[test]
fn invalid_sequences_become_replacement_characters() {
// A Shift-JIS lead byte cut off by the line end keeps the line end.
assert_eq!(decode_code_page(b"\x90\n1\n", "ANSI_932").as_deref(), Some("\u{FFFD}\n1\n"));
assert_eq!(decode_code_page(b"\x90", "ANSI_932").as_deref(), Some("\u{FFFD}"));
assert_eq!(decode_code_page(b"\xFF\xFF", "ANSI_936").as_deref(), Some("\u{FFFD}\u{FFFD}"));
}
#[test]
fn header_scan() {
let head = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1251\r\n0\nENDSEC\n";
assert_eq!(ascii_code_page(head), Some(&b"ANSI_1251"[..]));
// Only the HEADER section counts.
assert_eq!(ascii_code_page(b"0\nSECTION\n2\nHEADER\n0\nENDSEC\n9\n$DWGCODEPAGE\n3\nANSI_1251\n"), None);
// Wrong group code, or the file ends early.
assert_eq!(ascii_code_page(b"9\n$DWGCODEPAGE\n1\nANSI_1251\n"), None);
assert_eq!(ascii_code_page(b"9\n$DWGCODEPAGE\n3"), None);
assert!(is_utf8_version("AC1021") && is_utf8_version(" AC1032 "));
assert!(!is_utf8_version("AC1018") && !is_utf8_version("AC1009") && !is_utf8_version("garbage"));
}
#[test]
fn mif_escapes() {
let one = |s: &str| crate::parse(format!("1\n{s}\n0\nEOF\n").as_bytes()).unwrap()[0].str();
assert_eq!(one("\\M+5BCFE\\M+1907D\\M+2B9CF\\M+3B5B5!"), "件図圖도!");
assert_eq!(one("\\M+5BCFE\\U+0021"), "件!");
// Johab, unknown code pages, bad hex, short escapes and unassigned codes stay literal.
for s in ["\\M+4ABCD", "\\M+9BCFE", "\\M+5GGGG", "\\M+5BC", "\\M+", "\\M+50041", "\\M+5FFFF"] {
assert_eq!(one(s), s);
}
}
}
+129 -15
View File
@@ -9,6 +9,9 @@
use std::fmt::Write as _;
mod version;
pub use version::Version;
#[derive(Debug, thiserror::Error)]
pub enum DxfError {
#[error("not a DXF file")]
@@ -163,14 +166,8 @@ const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0";
/// tag list to a few GB; real drawings stay far below (a 10 MB DWG is typically a few million).
pub const MAX_TAGS: usize = 50_000_000;
/// Decode bytes as text: UTF-8 when valid (borrowed, no copy), otherwise Latin-1 (old ANSI_1252
/// files).
fn decode_text(b: &[u8]) -> std::borrow::Cow<'_, str> {
match std::str::from_utf8(b) {
Ok(s) => std::borrow::Cow::Borrowed(s),
Err(_) => std::borrow::Cow::Owned(b.iter().map(|&c| char::from(c)).collect()),
}
}
mod codepage;
pub use codepage::decode_code_page;
/// Parse a DXF file (ASCII or binary).
pub fn parse(bytes: &[u8]) -> Result<Vec<Tag>> {
@@ -189,7 +186,7 @@ pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
if tags > max_tags {
return Err(DxfError::TooLarge { tags, limit: max_tags });
}
parse_ascii_with_limit(&decode_text(bytes), max_tags)
parse_ascii_with_limit(&codepage::decode_ascii_file(bytes), max_tags)
}
/// The four hex digits of a `\U+XXXX` escape starting at `chars[i]`, if there is one.
@@ -204,17 +201,41 @@ fn escape_at(chars: &[char], i: usize) -> Option<u32> {
hex.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?))
}
/// 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<char> {
if chars.get(i) != Some(&'\\') || chars.get(i + 1) != Some(&'M') || chars.get(i + 2) != Some(&'+') {
return None;
}
let enc = codepage::mif_encoding(*chars.get(i + 3)?)?;
let hex = chars.get(i + 4..i + 8)?;
if !hex.iter().all(char::is_ascii_hexdigit) {
return None;
}
let code = hex.iter().try_fold(0u16, |acc, c| Some(acc * 16 + u16::try_from(c.to_digit(16)?).ok()?))?;
let bytes = code.to_be_bytes();
let text = enc.decode_without_bom_handling_and_without_replacement(&bytes)?;
let mut it = text.chars();
it.next().filter(|_| it.next().is_none())
}
/// Unescape the `\U+XXXX` sequences pre-R2007 DXF uses for characters outside the file's code
/// page (four hex digits, one UTF-16 code unit; characters above U+FFFF are a surrogate pair of
/// escapes). Malformed escapes and unpaired surrogates are kept as literal text.
/// escapes), and the `\M+nXXXX` sequences for double-byte East Asian characters. Malformed
/// escapes, unpaired surrogates and unknown `\M+` code pages are kept as literal text.
fn unescape_unicode(s: &str) -> String {
if !s.contains("\\U+") {
if !s.contains("\\U+") && !s.contains("\\M+") {
return s.to_string();
}
let mut out = String::with_capacity(s.len());
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while let Some(&c) = chars.get(i) {
if let Some(ch) = mif_escape_at(&chars, i) {
out.push(ch);
i += 8;
continue;
}
if let Some(unit) = escape_at(&chars, i) {
if let Some(ch) = char::from_u32(unit) {
out.push(ch);
@@ -276,7 +297,7 @@ struct Cur<'a> {
p: usize,
}
impl Cur<'_> {
impl<'a> Cur<'a> {
fn take(&mut self, n: usize) -> Result<&[u8]> {
let end = self.p.checked_add(n).ok_or(DxfError::Eof)?;
let s = self.b.get(self.p..end).ok_or(DxfError::Eof)?;
@@ -306,12 +327,13 @@ impl Cur<'_> {
a.copy_from_slice(s);
Ok(f64::from_le_bytes(a))
}
fn cstr(&mut self) -> Result<String> {
/// The bytes of a zero-terminated string (without the zero), decoded by the caller.
fn cstr(&mut self) -> Result<&'a [u8]> {
let start = self.p;
while self.p < self.b.len() && self.b.get(self.p) != Some(&0) {
self.p += 1;
}
let s = decode_text(self.b.get(start..self.p).unwrap_or(&[])).into_owned();
let s = self.b.get(start..self.p).unwrap_or(&[]);
if self.p >= self.b.len() {
return Err(DxfError::Eof);
}
@@ -327,6 +349,7 @@ pub fn parse_binary(b: &[u8]) -> Result<Vec<Tag>> {
fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
let mut c = Cur { b, p: 0 };
let mut text = codepage::BinaryText::default();
let mut tags = Vec::new();
while c.p < b.len() {
let mut code = i32::from(c.i16()?);
@@ -334,7 +357,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
code = i32::from(c.i16()?);
}
let v = match kind_of(code) {
Kind::Str => Value::Str(unescape_unicode(&c.cstr()?)),
Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))),
Kind::Real => Value::Real(c.f64()?),
Kind::Int16 => Value::Int(i64::from(c.i16()?)),
Kind::Int32 => Value::Int(i64::from(c.i32()?)),
@@ -359,6 +382,9 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
break;
}
}
if tags.is_empty() {
return Err(DxfError::NotDxf);
}
Ok(tags)
}
@@ -376,10 +402,18 @@ pub fn format_real(v: f64) -> String {
/// The output is pure ASCII: non-ASCII characters in strings are written as `\U+XXXX` escapes,
/// the pre-R2007 convention, so it is correct whatever `$DWGCODEPAGE` the header declares.
pub fn write_ascii(tags: &[Tag]) -> String {
write_ascii_as(tags, false)
}
/// Write tags as ASCII DXF with text in UTF-8 (`utf8`, the R2007+ convention: non-ASCII
/// characters as they are) or escaped as `\U+XXXX` (older versions, see [`write_ascii`]). Line
/// breaks inside strings become spaces either way.
pub fn write_ascii_as(tags: &[Tag], utf8: bool) -> String {
let mut out = String::with_capacity(tags.len() * 16);
for t in tags {
let _ = write!(out, "{:>3}\r\n", t.code);
match &t.value {
Value::Str(s) if utf8 => out.extend(s.chars().map(|c| if matches!(c, '\r' | '\n') { ' ' } else { c })),
Value::Str(s) => escape_unicode(s, &mut out),
Value::Real(r) => out.push_str(&format_real(*r)),
Value::Int(i) => out.push_str(&i.to_string()),
@@ -391,6 +425,86 @@ pub fn write_ascii(tags: &[Tag]) -> String {
out
}
/// Write tags as binary DXF (DXF Reference, "Binary DXF Files", R13+ layout): the sentinel,
/// then per tag a 2-byte little-endian group code and the value in the binary form of the code's
/// [`Kind`]: a zero-terminated string, an 8-byte real, a 2-, 4- or 8-byte integer, a 1-byte
/// boolean, or a binary chunk (one length byte, then up to 255 bytes; longer data is split into
/// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as
/// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text
/// is stored as a number; a code outside the 16-bit range is skipped.
pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec<u8> {
let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12);
out.extend_from_slice(BINARY_SENTINEL);
for t in tags {
let Ok(code) = i16::try_from(t.code) else { continue };
let code_bytes = code.to_le_bytes();
match kind_of(t.code) {
Kind::Str => {
out.extend_from_slice(&code_bytes);
let s = match &t.value {
Value::Str(s) => s.clone(),
v => v.as_str(),
};
let mut text = String::with_capacity(s.len());
if utf8 {
text.extend(s.chars().map(|c| if matches!(c, '\r' | '\n') { ' ' } else { c }));
} else {
escape_unicode(&s, &mut text);
}
out.extend(text.bytes().filter(|&b| b != 0));
out.push(0);
}
Kind::Real => {
out.extend_from_slice(&code_bytes);
out.extend_from_slice(&t.value.as_f64().to_le_bytes());
}
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());
}
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());
}
Kind::Int64 => {
out.extend_from_slice(&code_bytes);
out.extend_from_slice(&t.value.as_i64().to_le_bytes());
}
Kind::Bool => {
out.extend_from_slice(&code_bytes);
out.push(u8::from(t.value.as_i64() != 0));
}
Kind::Hex => {
let bytes = hex_bytes(&t.value.as_str());
// An empty chunk is still one group, as in ASCII.
let mut chunks: Vec<&[u8]> = bytes.chunks(255).collect();
if chunks.is_empty() {
chunks.push(&[]);
}
for chunk in chunks {
out.extend_from_slice(&code_bytes);
out.push(u8::try_from(chunk.len()).unwrap_or(u8::MAX));
out.extend_from_slice(chunk);
}
}
}
}
out
}
/// The bytes of hex text, two digits each; anything that isn't a pair of hex digits is skipped.
fn hex_bytes(s: &str) -> Vec<u8> {
let digits: Vec<u8> = 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()
}
/// 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)
}
/// Escape a string for a pre-R2007 DXF, whose text is in the `$DWGCODEPAGE` code page: ASCII
/// stays as it is and every other character becomes `\U+XXXX` (a surrogate pair of escapes
/// above U+FFFF), so the bytes are valid in any code page. Line breaks become spaces.
+117
View File
@@ -0,0 +1,117 @@
//! The DXF/DWG file versions CADCraft writes (DXF Reference, HEADER `$ACADVER`).
/// A file version CADCraft can save: the AutoCAD release that introduced the format. Each format
/// also serves the releases after it (2018 is still AutoCAD's current format).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Version {
/// AutoCAD 2000/2002 (AC1015).
R2000,
/// AutoCAD 2004–2006 (AC1018).
R2004,
/// AutoCAD 2007–2009 (AC1021): the first version whose DXF text is UTF-8.
R2007,
/// AutoCAD 2010–2012 (AC1024).
R2010,
/// AutoCAD 2013–2017 (AC1027).
R2013,
/// AutoCAD 2018 and later (AC1032), the default.
#[default]
R2018,
}
impl Version {
/// Every version, oldest first.
pub const ALL: [Version; 6] = [Version::R2000, Version::R2004, Version::R2007, Version::R2010, Version::R2013, Version::R2018];
/// The `$ACADVER` code ("AC1032").
pub fn code(self) -> &'static str {
match self {
Version::R2000 => "AC1015",
Version::R2004 => "AC1018",
Version::R2007 => "AC1021",
Version::R2010 => "AC1024",
Version::R2013 => "AC1027",
Version::R2018 => "AC1032",
}
}
/// The release year that names the version ("2018").
pub fn year(self) -> &'static str {
match self {
Version::R2000 => "2000",
Version::R2004 => "2004",
Version::R2007 => "2007",
Version::R2010 => "2010",
Version::R2013 => "2013",
Version::R2018 => "2018",
}
}
/// A version named by its year ("2018", "R2018") or its `$ACADVER` code ("AC1032"), any case.
pub fn parse(s: &str) -> Option<Version> {
let s = s.trim();
let year = s.strip_prefix(['R', 'r']).unwrap_or(s);
Version::ALL.into_iter().find(|v| v.year() == year || v.code().eq_ignore_ascii_case(s))
}
/// The version to save a file of `$ACADVER` `code` in: the same version when CADCraft writes
/// it, else the nearest one it does (R2000 for older files, 2018 for newer ones); `None` when
/// the code isn't a version code at all.
pub fn for_acadver(code: &str) -> Option<Version> {
let code = code.trim();
if let Some(v) = Version::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(code)) {
return Some(v);
}
code.get(..2).filter(|p| p.eq_ignore_ascii_case("AC"))?;
let n = code.get(2..).filter(|d| d.bytes().all(|b| b.is_ascii_digit())).and_then(|d| d.parse::<u32>().ok())?;
Some(match n {
..1018 => Version::R2000,
1018..1021 => Version::R2004,
1021..1024 => Version::R2007,
1024..1027 => Version::R2010,
1027..1032 => Version::R2013,
_ => Version::R2018,
})
}
/// Whether text in this version's DXF is UTF-8 (2007 and later). Older versions keep text in
/// the `$DWGCODEPAGE` code page, which CADCraft avoids by escaping non-ASCII as `\U+XXXX`.
pub fn utf8(self) -> bool {
self >= Version::R2007
}
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.year())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_years_and_codes() {
assert_eq!(Version::parse("2018"), Some(Version::R2018));
assert_eq!(Version::parse(" r2004 "), Some(Version::R2004));
assert_eq!(Version::parse("ac1021"), Some(Version::R2007));
assert_eq!(Version::parse("2005"), None);
assert_eq!(Version::parse(""), None);
for v in Version::ALL {
assert_eq!(Version::parse(v.code()), Some(v));
assert_eq!(Version::parse(v.year()), Some(v));
}
}
#[test]
fn file_versions_map_to_the_nearest_writable_one() {
assert_eq!(Version::for_acadver("AC1009"), Some(Version::R2000));
assert_eq!(Version::for_acadver("AC1014"), Some(Version::R2000));
assert_eq!(Version::for_acadver("AC1024"), Some(Version::R2010));
assert_eq!(Version::for_acadver("AC1035"), Some(Version::R2018));
assert_eq!(Version::for_acadver("MC0.0"), None);
assert_eq!(Version::for_acadver("AC"), None);
assert_eq!(Version::for_acadver("AC99999999999999999999"), None);
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Binary DXF writing (#421): every value kind round-trips through `write_binary` and `parse`,
//! and hostile binary input never panics.
use cadcraft_dxf::{Tag, Value, is_binary, parse, write_ascii_as, write_binary};
fn sample() -> Vec<Tag> {
vec![
Tag::s(0, "SECTION"),
Tag::s(2, "ENTITIES"),
Tag::s(0, "TEXT"),
Tag::s(5, "1F"),
Tag::f(10, -3.25),
Tag::i(62, 5),
Tag::i(90, 70_000),
Tag::i(160, 1 << 40),
Tag::new(290, Value::Bool(true)),
Tag::new(310, Value::Hex("00FFA5".into())),
Tag::s(1, "图号 Café 😀"),
Tag::i(1071, -2),
Tag::s(0, "ENDSEC"),
Tag::s(0, "EOF"),
]
}
#[test]
fn binary_roundtrips_every_value_kind() {
for utf8 in [false, true] {
let bytes = write_binary(&sample(), utf8);
assert!(is_binary(&bytes));
assert_eq!(parse(&bytes).unwrap(), sample(), "utf8 = {utf8}");
}
// Pre-2007 strings are escaped to ASCII, 2007+ ones are UTF-8.
let old = write_binary(&sample(), false);
assert!(old.windows(7).any(|w| w == b"\\U+56FE"));
let new = write_binary(&sample(), true);
assert!(new.windows("图号".len()).any(|w| w == "图号".as_bytes()));
}
#[test]
fn binary_converts_values_to_their_codes_kind() {
// A number held as text at a numeric code, an out-of-range 16-bit value, a long chunk.
let long = "AB".repeat(300);
let tags = vec![Tag::s(70, "12"), Tag::i(62, 1 << 20), Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")];
let back = parse(&write_binary(&tags, true)).unwrap();
assert_eq!(back[0], Tag::i(70, 12));
assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX)));
assert_eq!(back[2].code, 310);
assert_eq!(back[3].code, 310, "300 bytes are split into chunks of at most 255");
assert_eq!(back[2].str().len() + back[3].str().len(), 600);
}
#[test]
fn utf8_ascii_keeps_text_and_drops_line_breaks() {
let text = write_ascii_as(&[Tag::s(1, "图号\r\nÄ"), Tag::s(0, "EOF")], true);
assert!(text.contains("图号 Ä\r\n"));
assert_eq!(parse(text.as_bytes()).unwrap()[0].str(), "图号 Ä");
}
#[test]
fn hostile_binary_input_never_panics() {
let good = write_binary(&sample(), true);
// Every truncation, and every single-byte corruption of the body.
for n in 0..good.len() {
let _ = parse(good.get(..n).unwrap());
}
for i in 22..good.len() {
for b in [0u8, 0x7f, 0xff] {
let mut bad = good.clone();
bad[i] = b;
let _ = parse(&bad);
}
}
// A sentinel and nothing else is not a drawing.
assert!(parse(b"AutoCAD Binary DXF\r\n\x1a\0").is_err());
}
+10 -1
View File
@@ -12,12 +12,21 @@ workspace = true
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
cadcraft-dxf = { workspace = true }
cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
craft-docpath = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# R-tree spatial index for picking, window selection and object snaps (MIT OR Apache-2.0).
rstar = { version = "0.12", default-features = false }
rstar = { version = "0.13", default-features = false }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dev-dependencies]
# Real DXF files for the external reference tests (io is a lower layer).
cadcraft-io = { workspace = true }
+4 -2
View File
@@ -274,8 +274,7 @@ pub fn recompute(dm: &Dimension, prev: Option<&Dimension>, before: &Drawing, aft
// An ordinate's `defpt` is its fixed datum (the drawing origin); it must not follow the feature.
let ordinate = matches!(nd.kind, DimKind::Ordinate { .. });
for name in POINTS {
if !moved.iter().any(|m| m == name)
&& !(ordinate && name == "defpt")
if !(moved.iter().any(|m| m == name) || ordinate && name == "defpt")
&& !(linear && (name == "p13" || name == "p14"))
&& let Some(slot) = def_point_mut(&mut nd, name)
{
@@ -337,10 +336,13 @@ pub fn update(after: &mut Arc<Drawing>, before: &Drawing) -> usize {
/// finishes. `uid` (when known) is the document the command started in.
pub fn after_command(s: &mut crate::Session, before: Option<&Arc<Drawing>>, uid: Option<u64>) {
let Some(before) = before else { return };
let mut notes = Vec::new();
if let Ok(st) = s.state_mut()
&& uid.is_none_or(|u| u == st.uid)
&& !Arc::ptr_eq(before, &st.doc)
{
update(&mut st.doc, before);
notes = crate::cmd::hatch::refill_associative(&mut st.doc, before);
}
notes.into_iter().for_each(|n| s.echo(n));
}
+163
View File
@@ -0,0 +1,163 @@
//! Safe, atomic file replacement.
//!
//! Save, export, plot, autosave and the audit log all write a file by first putting the bytes in
//! a sibling temporary file and then renaming it over the destination, so a failed or partial
//! write never truncates the real file. The temporary file must be created *exclusively*: opening
//! a predictable, pre-existing temporary path for a truncating write lets another local user plant
//! a symlink there and redirect the write onto a file the victim can write but the attacker chose
//! (CWE-59). [`write_atomic`] creates a fresh temporary file with `create_new` (`O_CREAT|O_EXCL`),
//! so an existing entry at that path — symlink or not — makes the create fail rather than follow
//! it. The handle is retained for the whole write, and only its own fresh file is renamed into
//! place.
#![cfg(not(target_arch = "wasm32"))]
use std::fs::{File, OpenOptions, Permissions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Monotonic counter making temporary names unique within this process without a RNG dependency.
static SEQ: AtomicU64 = AtomicU64::new(0);
/// How many fresh temporary names to try before giving up (each collision is another local race).
const MAX_TRIES: u32 = 32;
/// Write `bytes` to `path`, replacing it atomically and without ever following a pre-existing
/// temporary symlink.
///
/// A fresh temporary file is created with exclusive semantics in `path`'s own directory, the bytes
/// are written through the retained handle and flushed, and the temporary is then renamed over
/// `path`. On any failure the temporary is removed and the original `path` is left untouched.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let permissions = match std::fs::symlink_metadata(path) {
Ok(meta) if meta.is_file() => Some(meta.permissions()),
Ok(_) => None,
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf);
let (mut file, tmp) = create_temp(&dir, permissions.as_ref())?;
let write = (|| {
if let Some(permissions) = permissions {
file.set_permissions(permissions)?;
}
file.write_all(bytes)?;
file.flush()?;
file.sync_all()
})();
if let Err(e) = write {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
drop(file);
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// Create a fresh, exclusively-owned temporary file inside `dir`, returning its handle and path.
///
/// `create_new(true)` opens with `O_CREAT | O_EXCL`, which refuses to follow or reuse an existing
/// entry (including a symlink), closing the plant-a-symlink race. Names are unpredictable enough to
/// avoid collisions in practice, and genuine collisions are retried with a new name.
fn create_temp(dir: &Path, permissions: Option<&Permissions>) -> io::Result<(File, PathBuf)> {
let pid = std::process::id();
let mut last_err = None;
for _ in 0..MAX_TRIES {
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
let tmp = dir.join(format!(".cadcraft-tmp-{pid}-{seq}-{nanos}"));
match create_exclusive(&tmp, permissions) {
Ok(file) => return Ok((file, tmp)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
last_err = Some(e);
continue;
}
Err(e) => return Err(e),
}
}
Err(last_err.unwrap_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, "could not create a unique temporary file")))
}
fn create_exclusive(path: &Path, permissions: Option<&Permissions>) -> io::Result<File> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
if let Some(permissions) = permissions {
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
// Restrict access in the create syscall: chmod afterwards leaves a window in which a
// different user can open the inode and retain read access to bytes written later.
options.mode(permissions.mode() & 0o777);
}
#[cfg(not(unix))]
let _ = permissions;
options.open(path)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replaces_contents_atomically() {
let dir = std::env::temp_dir().join(format!("cadcraft-aw-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
let dest = dir.join("out.bin");
std::fs::write(&dest, b"old").unwrap();
write_atomic(&dest, b"new bytes").unwrap();
assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes");
// No temporary files left behind.
let leftovers: Vec<_> =
std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).filter(|n| n.to_string_lossy().starts_with(".cadcraft-tmp")).collect();
assert!(leftovers.is_empty(), "left temp files: {leftovers:?}");
std::fs::remove_dir_all(&dir).ok();
}
#[cfg(unix)]
#[test]
fn does_not_follow_a_planted_temp_symlink() {
use std::os::unix::fs::symlink;
let dir = std::env::temp_dir().join(format!("cadcraft-aw-sym-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
let victim = dir.join("victim");
std::fs::write(&victim, b"precious").unwrap();
let planted = dir.join(".cadcraft-tmp-plant");
symlink(&victim, &planted).unwrap();
assert_eq!(create_exclusive(&planted, None).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
let dest = dir.join("drawing.dxf");
write_atomic(&dest, b"drawing bytes").unwrap();
assert_eq!(std::fs::read(&victim).unwrap(), b"precious", "victim file was overwritten");
assert_eq!(std::fs::read(&dest).unwrap(), b"drawing bytes");
std::fs::remove_dir_all(&dir).ok();
}
#[cfg(unix)]
#[test]
fn replacement_preserves_private_permissions() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("cadcraft-aw-mode-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
let dest = dir.join("private.adt");
std::fs::write(&dest, b"old").unwrap();
std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap();
write_atomic(&dest, b"private report").unwrap();
assert_eq!(std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::read(&dest).unwrap(), b"private report");
std::fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn private_temp_is_restricted_from_creation() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("cadcraft-aw-create-mode-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("private-temp");
let permissions = Permissions::from_mode(0o600);
let file = create_exclusive(&path, Some(&permissions)).unwrap();
assert_eq!(file.metadata().unwrap().permissions().mode() & 0o077, 0);
drop(file);
std::fs::remove_dir_all(dir).unwrap();
}
}
+661
View File
@@ -0,0 +1,661 @@
//! AUDIT: find and repair errors in a drawing's database.
//!
//! [`check`] reports what is wrong; [`repair`] fixes it. Repairs never guess at content: a missing
//! layer or block definition is recreated with default properties (an empty block), a reference to
//! a missing style or linetype is reassigned to `Standard` or `ByLayer`, references to objects that
//! don't exist are dropped, objects whose geometry can't be drawn are removed, block definitions
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
//! get new ones.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle};
use serde::Serialize;
use serde_json::{Value, json};
/// One error found in the drawing.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Issue {
/// What is wrong, as a stable identifier (`missingLayer`, `invalidGeometry`, `blockCycle`…).
pub kind: &'static str,
/// Where: `header`, `tables`, `Model`, `layout <name>`, `block <name>`, `groups` or `constraints`.
pub location: String,
/// The object concerned, as a hex handle.
#[serde(skip_serializing_if = "Option::is_none")]
pub handle: Option<String>,
pub message: String,
/// What the repair does (or did).
pub fix: String,
}
/// The result of an audit.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Report {
pub issues: Vec<Issue>,
/// Whether the issues were fixed.
pub fixed: bool,
}
/// The most issue lines a report message lists; the rest are counted.
const MAX_LINES: usize = 100;
impl Report {
pub fn errors(&self) -> usize {
self.issues.len()
}
/// The command-line text: one line per issue (up to [`MAX_LINES`]), then the totals.
pub fn message(&self) -> String {
let mut lines: Vec<String> = self
.issues
.iter()
.take(MAX_LINES)
.map(|i| {
let what = match &i.handle {
Some(h) => format!("{}: object {h}: {}", i.location, i.message),
None => format!("{}: {}", i.location, i.message),
};
if self.fixed { format!("{what} ({})", i.fix) } else { what }
})
.collect();
if self.issues.len() > MAX_LINES {
lines.push(format!("… and {} more", self.issues.len() - MAX_LINES));
}
let n = self.errors();
let fixed = if self.fixed { n } else { 0 };
lines.push(format!("Audit: {n} error{} found, {fixed} fixed.", if n == 1 { "" } else { "s" }));
if n > 0 && !self.fixed {
lines.push("Run AUDIT and answer Yes to fix them.".into());
}
lines.join("\n")
}
/// The programmatic result: `{errors, fixed, issues, message}`.
pub fn to_json(&self) -> Value {
json!({
"errors": self.errors(),
"fixed": if self.fixed { self.errors() } else { 0 },
"issues": self.issues,
"message": self.message(),
})
}
/// Format this report for an AUDITCTL `.adt` log file.
pub fn format_adt(&self, title: &str, path: Option<&str>) -> String {
let name = path.unwrap_or(title);
format!("Audit of drawing: {name}\n\n{}\n", self.message())
}
}
/// Audit `d` without changing it.
pub fn check(d: &Drawing) -> Report {
let mut copy = d.clone();
Report { issues: repair(&mut copy), fixed: false }
}
/// Audit `d` and fix what is wrong in place. A drawing without errors is left untouched.
pub fn fix(d: &mut Drawing) -> Report {
Report { issues: repair(d), fixed: true }
}
/// Where a set of objects lives.
#[derive(Clone, Debug)]
enum Loc {
Model,
Layout(usize),
Block(String),
}
impl Loc {
fn label(&self, d: &Drawing) -> String {
match self {
Loc::Model => "Model".into(),
Loc::Layout(i) => format!("layout {}", d.layouts.get(*i).map(|l| l.name.as_str()).unwrap_or("?")),
Loc::Block(n) => format!("block {n}"),
}
}
}
fn locations(d: &Drawing) -> Vec<Loc> {
std::iter::once(Loc::Model).chain((0..d.layouts.len()).map(Loc::Layout)).chain(d.blocks.keys().cloned().map(Loc::Block)).collect()
}
fn store<'a>(d: &'a Drawing, l: &Loc) -> Option<&'a EntityStore> {
match l {
Loc::Model => Some(&d.model),
Loc::Layout(i) => d.layouts.get(*i).map(|l| &l.entities),
Loc::Block(n) => d.blocks.get(n).map(|b| &b.entities),
}
}
fn store_mut<'a>(d: &'a mut Drawing, l: &Loc) -> Option<&'a mut EntityStore> {
match l {
Loc::Model => Some(&mut d.model),
Loc::Layout(i) => d.layouts.get_mut(*i).map(|l| &mut l.entities),
Loc::Block(n) => d.blocks.get_mut(n).map(|b| &mut Arc::make_mut(b).entities),
}
}
/// A change to one object, applied after its store was read.
enum Action {
Remove(Handle),
Replace(Box<Entity>),
/// Give the object (by its old handle) a new handle.
Rehandle(Handle),
}
fn apply(d: &mut Drawing, loc: &Loc, actions: Vec<Action>) {
if actions.is_empty() {
return;
}
// New handles first: the store is borrowed below.
let fresh: Vec<Handle> = actions.iter().filter(|a| matches!(a, Action::Rehandle(_))).map(|_| d.new_handle()).collect();
let mut fresh = fresh.into_iter();
let Some(st) = store_mut(d, loc) else { return };
for a in actions {
match a {
Action::Remove(h) => {
st.remove(h);
}
Action::Replace(e) => {
st.replace(*e);
}
Action::Rehandle(h) => {
if let (Some(e), Some(new)) = (st.remove(h), fresh.next()) {
let mut e = (*e).clone();
e.handle = new;
st.push(e);
}
}
}
}
}
fn issue(kind: &'static str, location: impl Into<String>, handle: Option<Handle>, message: String, fix: impl Into<String>) -> Issue {
Issue { kind, location: location.into(), handle: handle.map(Handle::hex), message, fix: fix.into() }
}
/// Find every error in `d` and fix it; returns what was found. Nothing is changed when nothing is
/// wrong.
pub fn repair(d: &mut Drawing) -> Vec<Issue> {
let mut out = Vec::new();
tables(d, &mut out);
header(d, &mut out);
handseed(d, &mut out);
objects(d, &mut out);
missing_blocks(d, &mut out);
references(d, &mut out);
block_cycles(d, &mut out);
let all = all_handles(d);
groups(d, &all, &mut out);
constraints(d, &all, &mut out);
out
}
fn has_name<T>(items: &[T], name: &str, of: impl Fn(&T) -> &str) -> bool {
items.iter().any(|t| of(t).eq_ignore_ascii_case(name))
}
/// The entries every drawing has, and references between table entries.
fn tables(d: &mut Drawing, out: &mut Vec<Issue>) {
let missing = |what: &str, name: &str, out: &mut Vec<Issue>| {
out.push(issue("missingTableEntry", "tables", None, format!("the {what} \"{name}\" is missing"), "recreated with default properties"));
};
if d.layer("0").is_none() {
missing("layer", "0", out);
d.layers.insert(0, Layer::default());
}
for name in ["ByBlock", "ByLayer"] {
if d.linetype(name).is_none() {
missing("linetype", name, out);
d.linetypes.push(Linetype { name: name.into(), description: String::new(), pattern: Vec::new() });
}
}
if d.linetype("Continuous").is_none() {
missing("linetype", "Continuous", out);
d.linetypes.push(Linetype::continuous());
}
if d.text_style("Standard").is_none() {
missing("text style", "Standard", out);
d.text_styles.insert(0, TextStyle::default());
}
if d.dim_style("Standard").is_none() {
missing("dimension style", "Standard", out);
d.dim_styles.insert(0, DimStyle::default());
}
if !has_name(&d.mleader_styles, "Standard", |s| &s.name) {
missing("multileader style", "Standard", out);
d.mleader_styles.insert(0, MLeaderStyle::default());
}
if !has_name(&d.table_styles, "Standard", |s| &s.name) {
missing("table style", "Standard", out);
d.table_styles.insert(0, TableStyle::default());
}
let linetypes: Vec<String> = d.linetypes.iter().map(|l| l.name.clone()).collect();
for l in &mut d.layers {
if !linetypes.iter().any(|n| n.eq_ignore_ascii_case(&l.linetype)) {
out.push(issue(
"missingLinetype",
"tables",
None,
format!("layer \"{}\" uses linetype \"{}\", which doesn't exist", l.name, l.linetype),
"set to Continuous",
));
l.linetype = "Continuous".into();
}
}
let styles: Vec<String> = d.text_styles.iter().map(|s| s.name.clone()).collect();
let known = |n: &str| styles.iter().any(|s| s.eq_ignore_ascii_case(n));
for s in &mut d.dim_styles {
if !known(&s.text_style) {
out.push(issue(
"missingTextStyle",
"tables",
None,
format!("dimension style \"{}\" uses text style \"{}\", which doesn't exist", s.name, s.text_style),
"set to Standard",
));
s.text_style = "Standard".into();
}
}
for s in &mut d.mleader_styles {
if !known(&s.text_style) {
out.push(issue(
"missingTextStyle",
"tables",
None,
format!("multileader style \"{}\" uses text style \"{}\", which doesn't exist", s.name, s.text_style),
"set to Standard",
));
s.text_style = "Standard".into();
}
}
}
/// The current layer, linetype and style variables name entries that exist.
fn header(d: &mut Drawing, out: &mut Vec<Issue>) {
let vars: [(&str, &str, &str); 6] = [
("CLAYER", "layer", "0"),
("CELTYPE", "linetype", "ByLayer"),
("TEXTSTYLE", "text style", "Standard"),
("DIMSTYLE", "dimension style", "Standard"),
("CMLEADERSTYLE", "multileader style", "Standard"),
("CTABLESTYLE", "table style", "Standard"),
];
for (var, what, default) in vars {
let Some(name) = d.header.get(var).map(|v| v.as_str().map(str::to_string)) else { continue };
let exists = name.as_deref().is_some_and(|n| match var {
"CLAYER" => d.layer(n).is_some(),
"CELTYPE" => d.linetype(n).is_some(),
"TEXTSTYLE" => d.text_style(n).is_some(),
"DIMSTYLE" => d.dim_style(n).is_some(),
"CMLEADERSTYLE" => has_name(&d.mleader_styles, n, |s| &s.name),
_ => has_name(&d.table_styles, n, |s| &s.name),
});
if !exists {
let shown = name.map(|n| format!("\"{n}\"")).unwrap_or_else(|| "a value that is not a name".into());
out.push(issue(
"missingCurrent",
"header",
None,
format!("the current {what} ({var}) is {shown}, which doesn't exist"),
format!("set to {default}"),
));
d.header.set_str(var, default);
}
}
}
fn each_entity(d: &Drawing) -> impl Iterator<Item = &Arc<Entity>> {
std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)).flat_map(|s| s.iter())
}
fn all_handles(d: &Drawing) -> HashSet<Handle> {
each_entity(d).map(|e| e.handle).collect()
}
/// The next handle is above every handle in use, so new objects never take an existing one.
fn handseed(d: &mut Drawing, out: &mut Vec<Issue>) {
let Some(max) = each_entity(d).map(|e| e.handle).max() else { return };
if max.0 >= d.handseed {
out.push(issue(
"handseed",
"header",
None,
format!("the next handle ({:X}) is not above the largest one in use ({})", d.handseed, max.hex()),
"moved past it",
));
d.bump_handseed(max);
}
}
/// Why `e`'s geometry is invalid, if it is.
fn invalid_geometry(e: &Entity) -> Option<&'static str> {
if !crate::finite::is_finite(e) {
return Some("has infinite or undefined numbers");
}
match &e.kind {
EntityKind::Line(l) if l.a == l.b => Some("has zero length"),
EntityKind::Circle(c) if c.radius <= 0.0 => Some("has no radius"),
EntityKind::Arc(a) if a.radius <= 0.0 => Some("has no radius"),
EntityKind::Ellipse(el) if el.major.len() <= 0.0 || el.ratio <= 0.0 => Some("has no size"),
_ => None,
}
}
/// Objects with invalid geometry are removed; handle 0 and handles used twice get new ones.
fn objects(d: &mut Drawing, out: &mut Vec<Issue>) {
let mut seen: HashSet<Handle> = HashSet::new();
for loc in locations(d) {
let Some(st) = store(d, &loc) else { continue };
let label = loc.label(d);
let mut actions = Vec::new();
for e in st.iter() {
if let Some(why) = invalid_geometry(e) {
out.push(issue("invalidGeometry", &label, Some(e.handle), format!("{} {why}", e.kind.type_name()), "removed"));
actions.push(Action::Remove(e.handle));
} else if e.handle.0 == 0 || !seen.insert(e.handle) {
let why = if e.handle.0 == 0 { "has no handle" } else { "has the same handle as another object" };
out.push(issue("duplicateHandle", &label, Some(e.handle), format!("{} {why}", e.kind.type_name()), "given a new handle"));
actions.push(Action::Rehandle(e.handle));
}
}
apply(d, &loc, actions);
}
}
/// Block references whose block definition is missing get an empty definition, keeping the
/// references (and their attributes) until the block is redefined.
fn missing_blocks(d: &mut Drawing, out: &mut Vec<Issue>) {
let mut missing: BTreeMap<String, usize> = BTreeMap::new();
for e in each_entity(d) {
if let EntityKind::Insert(i) = &e.kind
&& d.block(&i.block).is_none()
{
*missing.entry(i.block.clone()).or_insert(0) += 1;
}
}
for (name, n) in missing {
out.push(issue(
"missingBlock",
"tables",
None,
format!("{n} block reference{} to \"{name}\", which has no definition", if n == 1 { "" } else { "s" }),
"created an empty block definition",
));
d.blocks.insert(name.clone(), Arc::new(Block::new(&name)));
}
}
/// Layers objects are on that don't exist are created with default properties.
fn missing_layers(d: &mut Drawing, out: &mut Vec<Issue>) {
// By folded name: a file may have very many layers.
let mut known: HashSet<String> = d.layers.iter().map(|l| l.name.to_ascii_lowercase()).collect();
let mut missing: Vec<String> = Vec::new();
for e in each_entity(d) {
let n = &e.common.layer;
if !n.trim().is_empty() && known.insert(n.to_ascii_lowercase()) {
missing.push(n.clone());
}
}
for n in missing {
out.push(issue(
"missingLayer",
"tables",
None,
format!("layer \"{n}\" is used by objects but doesn't exist"),
"created with default properties",
));
d.layers.push(Layer::new(&n));
}
}
/// Missing layers, linetypes, styles, dimension blocks and associated objects referenced by objects.
fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
let all = all_handles(d);
let ok_text = |d: &Drawing, n: &str| d.text_style(n).is_some();
let ok_dim = |d: &Drawing, n: &str| d.dim_style(n).is_some();
// Missing names, counted: (what, name) → (objects, first location).
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
missing_layers(d, out);
for loc in locations(d) {
let Some(st) = store(d, &loc) else { continue };
let label = loc.label(d);
let mut actions = Vec::new();
for e in st.iter() {
let mut fixed = (**e).clone();
let mut note = |what: &'static str, name: &str| {
let c = counts.entry((what, name.to_string())).or_insert((0, label.clone()));
c.0 += 1;
};
if fixed.common.layer.trim().is_empty() {
note("layer", "");
fixed.common.layer = "0".into();
}
let lt = &fixed.common.linetype;
if !lt.eq_ignore_ascii_case("ByLayer") && !lt.eq_ignore_ascii_case("ByBlock") && d.linetype(lt).is_none() {
note("linetype", lt);
fixed.common.linetype = "ByLayer".into();
}
let mut text_style = |s: &mut String| {
if !ok_text(d, s) {
note("text style", s);
*s = "Standard".into();
}
};
match &mut fixed.kind {
EntityKind::Text(t) => text_style(&mut t.style),
EntityKind::MText(t) => text_style(&mut t.style),
EntityKind::AttDef(a) => text_style(&mut a.text.style),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| text_style(&mut a.text.style)),
EntityKind::MLeader(m) => {
if let Some(t) = &mut m.text {
text_style(&mut t.style);
}
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
note("multileader style", &m.style);
m.style = "Standard".into();
}
}
EntityKind::Table(t) => {
if !has_name(&d.table_styles, &t.style, |s| &s.name) {
note("table style", &t.style);
t.style = "Standard".into();
}
}
EntityKind::Leader(l) => {
if !ok_dim(d, &l.style) {
note("dimension style", &l.style);
l.style = "Standard".into();
}
}
EntityKind::Dimension(dim) => {
if !ok_dim(d, &dim.style) {
note("dimension style", &dim.style);
dim.style = "Standard".into();
}
if let Some(b) = &dim.block
&& d.block(b).is_none()
{
out.push(issue(
"missingBlock",
&label,
Some(e.handle),
format!("dimension's block \"{b}\" doesn't exist"),
"the dimension draws itself again",
));
dim.block = None;
}
let before = dim.assoc.len();
dim.assoc.retain(|a| all.contains(&a.handle));
if dim.assoc.len() < before {
out.push(issue(
"danglingReference",
&label,
Some(e.handle),
"dimension is associated with an object that doesn't exist".into(),
"association removed",
));
}
}
EntityKind::Viewport(vp) => {
let before = vp.frozen_layers.len() + vp.layer_colors.len();
vp.frozen_layers.retain(|n| d.layer(n).is_some());
vp.layer_colors.retain(|(n, _)| d.layer(n).is_some());
if vp.frozen_layers.len() + vp.layer_colors.len() < before {
out.push(issue(
"danglingReference",
&label,
Some(e.handle),
"viewport lists layer settings for layers that don't exist".into(),
"those entries removed",
));
}
if let Some(b) = vp.clip
&& (b == e.handle || !all.contains(&b))
{
vp.clip = None;
out.push(issue(
"danglingReference",
&label,
Some(e.handle),
"viewport's clip boundary doesn't exist".into(),
"the viewport is rectangular again",
));
}
}
_ => {}
}
if fixed != **e {
actions.push(Action::Replace(Box::new(fixed)));
}
}
apply(d, &loc, actions);
}
for ((what, name), (n, first)) in counts {
let (fix, shown) = match what {
"layer" => ("put on layer 0".to_string(), "no name".to_string()),
"linetype" => ("set to ByLayer".into(), format!("\"{name}\"")),
_ => ("set to Standard".into(), format!("\"{name}\"")),
};
out.push(issue(
"missingReference",
first,
None,
format!("{n} object{} {what} {shown}, which doesn't exist", if n == 1 { " uses" } else { "s use" }),
fix,
));
}
}
/// Block definitions that contain themselves (directly or through other blocks) lose the
/// reference that closes the loop.
fn block_cycles(d: &mut Drawing, out: &mut Vec<Issue>) {
let names: Vec<String> = d.blocks.keys().cloned().collect();
// Names resolve as `Drawing::block` does: the exact name, else one differing only in case.
let exact: HashMap<&str, usize> = names.iter().enumerate().map(|(i, n)| (n.as_str(), i)).collect();
let folded: HashMap<String, usize> = names.iter().enumerate().rev().map(|(i, n)| (n.to_ascii_lowercase(), i)).collect();
let lookup = |n: &str| exact.get(n).or_else(|| folded.get(&n.to_ascii_lowercase())).copied();
let edges: Vec<Vec<(Handle, usize)>> = names
.iter()
.map(|n| {
d.blocks
.get(n)
.map(|b| {
b.entities
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Insert(i) => lookup(&i.block).map(|t| (e.handle, t)),
_ => None,
})
.collect()
})
.unwrap_or_default()
})
.collect();
// Iterative depth-first search: 0 unvisited, 1 on the current path, 2 done.
let mut state = vec![0u8; names.len()];
let mut cuts: Vec<(usize, Handle, usize)> = Vec::new();
for root in 0..names.len() {
if state.get(root) != Some(&0) {
continue;
}
let mut stack: Vec<(usize, usize)> = vec![(root, 0)];
if let Some(s) = state.get_mut(root) {
*s = 1;
}
while let Some((node, next)) = stack.last_mut() {
let node = *node;
match edges.get(node).and_then(|es| es.get(*next)) {
Some(&(h, to)) => {
*next += 1;
match state.get(to) {
Some(1) => cuts.push((node, h, to)),
Some(0) => {
if let Some(s) = state.get_mut(to) {
*s = 1;
}
stack.push((to, 0));
}
_ => {}
}
}
None => {
if let Some(s) = state.get_mut(node) {
*s = 2;
}
stack.pop();
}
}
}
}
for (from, h, to) in cuts {
let (Some(from), Some(to)) = (names.get(from), names.get(to)) else { continue };
let msg = if from == to {
"block contains a reference to itself".to_string()
} else {
format!("reference to block \"{to}\" makes the block contain itself")
};
out.push(issue("blockCycle", format!("block {from}"), Some(h), msg, "reference removed"));
apply(d, &Loc::Block(from.clone()), vec![Action::Remove(h)]);
}
}
/// Groups list only objects that exist.
fn groups(d: &mut Drawing, all: &HashSet<Handle>, out: &mut Vec<Issue>) {
for g in &mut d.groups {
let before = g.members.len();
g.members.retain(|h| all.contains(h));
let gone = before - g.members.len();
if gone > 0 {
out.push(issue(
"danglingReference",
"groups",
None,
format!("group \"{}\" lists {gone} object{} exist", g.name, if gone == 1 { " that doesn't" } else { "s that don't" }),
"removed from the group",
));
}
}
}
/// Constraints refer only to objects that exist.
fn constraints(d: &mut Drawing, all: &HashSet<Handle>, out: &mut Vec<Issue>) {
let mut kept = Vec::with_capacity(d.constraints.len());
for c in std::mem::take(&mut d.constraints) {
match c.refs.iter().find(|r| !all.contains(&r.handle)) {
Some(r) => out.push(issue(
"danglingReference",
"constraints",
Some(r.handle),
format!("constraint {} refers to an object that doesn't exist", c.id),
"constraint removed",
)),
None => kept.push(c),
}
}
d.constraints = kept;
}
+460
View File
@@ -0,0 +1,460 @@
//! Autosave (SAVETIME, SAVEFILEPATH) and the files Drawing Recovery offers after a crash.
//!
//! Every SAVETIME minutes after a change, each drawing with unsaved changes made since its last
//! autosave is written as DXF to `<SAVEFILEPATH>/<drawing>_<instance>_<uid>.sv$`. The file goes
//! away when the drawing is saved or closed and when the app exits normally, so a file left behind
//! means the app (or the machine) went down; the next start offers it for recovery. A running app
//! keeps a lock file (`<instance>.lock`) fresh, so another copy running at the same time doesn't
//! offer its files. SAVEFILEPATH may be a folder other programs use too, so only names built from
//! an instance id ([`is_instance_id`]) are ever read as ours or deleted.
//!
//! [`Autosaver::plan`] decides what to write and delete (no I/O, so it is testable); on the desktop
//! [`Autosaver::tick`] carries it out, writing on a background thread. SAVETIME and SAVEFILEPATH
//! are profile settings: process-wide, not saved in the drawing.
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, Weak};
use cadcraft_doc::Drawing;
use serde::Serialize;
use crate::Session;
/// The autosave file extension.
pub const EXT: &str = "sv$";
/// SAVETIME's default, in minutes.
pub const DEFAULT_SAVETIME: u32 = 10;
/// SAVETIME's largest value, in minutes.
pub const MAX_SAVETIME: u32 = 600;
/// A lock file not refreshed for this long belongs to an app that is no longer running.
pub const STALE_LOCK_SECS: u64 = 5 * 60;
/// How often a running app refreshes its lock file.
#[cfg(not(target_arch = "wasm32"))]
const HEARTBEAT_SECS: f64 = 60.0;
static SAVETIME: AtomicU32 = AtomicU32::new(DEFAULT_SAVETIME);
static SAVEFILEPATH: Mutex<String> = Mutex::new(String::new());
/// SAVETIME: minutes between autosaves; 0 turns autosave off.
pub fn savetime() -> u32 {
SAVETIME.load(Ordering::Relaxed)
}
/// Set SAVETIME (clamped to 0–600 minutes).
pub fn set_savetime(minutes: u32) {
SAVETIME.store(minutes.min(MAX_SAVETIME), Ordering::Relaxed);
}
/// SAVEFILEPATH: the folder autosave files go to (the host sets a per-user default at start).
pub fn savefilepath() -> String {
SAVEFILEPATH.lock().map(|p| p.clone()).unwrap_or_default()
}
pub fn set_savefilepath(path: &str) {
if let Ok(mut p) = SAVEFILEPATH.lock() {
*p = path.trim().to_string();
}
}
/// The autosave file name for drawing `uid` titled `title`, written by app instance `instance`.
pub fn file_name(title: &str, instance: &str, uid: u64) -> String {
let stem: String = title.chars().map(|c| if c.is_alphanumeric() || " .-_()".contains(c) { c } else { '-' }).take(80).collect();
let stem = stem.trim().trim_matches('.');
let stem = if stem.is_empty() { "Drawing" } else { stem };
format!("{stem}_{instance}_{uid}.{EXT}")
}
/// Whether `s` has the form of an app instance id (`<process id>-<start time in hex>`, see
/// `instance_id`). Only file names built from one are treated as CADCraft's own, so files of
/// other programs in the autosave folder are never offered for recovery or deleted.
pub fn is_instance_id(s: &str) -> bool {
let Some((pid, time)) = s.split_once('-') else { return false };
(1..=10).contains(&pid.len())
&& pid.bytes().all(|b| b.is_ascii_digit())
&& (1..=32).contains(&time.len())
&& time.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// An autosave file name's parts: the drawing's title, the instance and the drawing uid.
pub fn parse_file_name(name: &str) -> Option<(&str, &str, u64)> {
let base = name.strip_suffix(&format!(".{EXT}"))?;
let (rest, uid) = base.rsplit_once('_')?;
let (title, instance) = rest.rsplit_once('_')?;
let uid_ok = !uid.is_empty() && uid.bytes().all(|b| b.is_ascii_digit());
(!title.is_empty() && is_instance_id(instance) && uid_ok).then_some(())?;
Some((title, instance, uid.parse().ok()?))
}
/// The instance whose lock file is named `name` (`<instance>.lock`), if it is one of ours.
pub fn parse_lock_name(name: &str) -> Option<&str> {
name.strip_suffix(".lock").filter(|i| is_instance_id(i))
}
/// What to do with the file system.
#[derive(Clone, Debug)]
pub enum Job {
/// Write `doc` (drawing `uid`) to `path`.
Write {
uid: u64,
path: String,
doc: Arc<Drawing>,
},
Delete {
path: String,
},
}
#[derive(Debug, Default)]
struct Tracked {
/// The drawing as last autosaved (a weak pointer: compared, never kept alive).
written: Option<Weak<Drawing>>,
/// The drawing outside the Block Editor as last autosaved (the same as `written` when the
/// editor is closed): saving the editor's changes into the block changes only this.
host: Option<Weak<Drawing>>,
/// Its autosave file, once written (or adopted).
file: Option<String>,
/// When a change not yet autosaved was first seen (seconds).
since: Option<f64>,
}
/// Autosave state for one running app.
pub struct Autosaver {
/// This app instance's id (`<process id>-<start time>`), part of every file name.
pub instance: String,
docs: HashMap<u64, Tracked>,
/// Drawings whose autosave is being written right now.
busy: HashSet<u64>,
/// Writes in progress; each tells whether its file was written.
#[cfg(not(target_arch = "wasm32"))]
running: Vec<(u64, std::thread::JoinHandle<bool>)>,
#[cfg(not(target_arch = "wasm32"))]
start: std::time::Instant,
#[cfg(not(target_arch = "wasm32"))]
last_beat: Option<f64>,
}
impl Autosaver {
pub fn new(instance: impl Into<String>) -> Self {
Autosaver {
instance: instance.into(),
docs: HashMap::new(),
busy: HashSet::new(),
#[cfg(not(target_arch = "wasm32"))]
running: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
start: std::time::Instant::now(),
#[cfg(not(target_arch = "wasm32"))]
last_beat: None,
}
}
/// Take over an existing autosave file for drawing `uid` (a drawing opened from Drawing
/// Recovery, whose current state it holds): later autosaves overwrite it, and it is deleted
/// once the drawing is saved or closed.
pub fn adopt(&mut self, s: &Session, uid: u64, path: &str) {
let st = s.docs.iter().find(|d| d.uid == uid);
let (written, host) = (st.map(|d| Arc::downgrade(&d.doc)), st.map(|d| Arc::downgrade(d.drawing())));
self.docs.insert(uid, Tracked { written, host, file: Some(path.to_string()), since: None });
}
/// The autosave files this app has written or adopted.
pub fn files(&self) -> Vec<String> {
self.docs.values().filter_map(|t| t.file.clone()).collect()
}
/// What to do at `now` (seconds, any fixed origin) with SAVETIME `minutes` and autosave folder
/// `dir`: write drawings changed `minutes` ago or earlier and not autosaved since, delete the
/// files of drawings that were saved (no unsaved changes left) or closed.
pub fn plan(&mut self, s: &Session, now: f64, minutes: u32, dir: &str) -> Vec<Job> {
self.plan_with(s, now, minutes, dir, false)
}
/// [`Autosaver::plan`], with `urgent` writing every drawing with changes not yet autosaved
/// now instead of `minutes` after the change (autosave still off when `minutes` is 0).
fn plan_with(&mut self, s: &Session, now: f64, minutes: u32, dir: &str, urgent: bool) -> Vec<Job> {
let mut jobs = Vec::new();
let live: HashSet<u64> = s.docs.iter().map(|d| d.uid).collect();
let busy = &self.busy;
self.docs.retain(|uid, t| {
// A file being written is deleted once the write is done.
if live.contains(uid) || busy.contains(uid) {
return true;
}
if let Some(path) = t.file.take() {
jobs.push(Job::Delete { path });
}
false
});
for st in &s.docs {
if self.busy.contains(&st.uid) {
continue;
}
let t = self.docs.entry(st.uid).or_default();
if !st.is_dirty() {
if let Some(path) = t.file.take() {
jobs.push(Job::Delete { path });
}
*t = Tracked::default();
continue;
}
let same = |w: &Option<Weak<Drawing>>, d: &Arc<Drawing>| w.as_ref().is_some_and(|w| std::ptr::eq(w.as_ptr(), Arc::as_ptr(d)));
let changed = !same(&t.written, &st.doc) || !same(&t.host, st.drawing());
if !changed {
t.since = None;
continue;
}
let since = *t.since.get_or_insert(now);
if minutes == 0 || dir.trim().is_empty() || (!urgent && now - since < f64::from(minutes) * 60.0) {
continue;
}
let path = t
.file
.clone()
.unwrap_or_else(|| std::path::Path::new(dir).join(file_name(&st.title, &self.instance, st.uid)).to_string_lossy().to_string());
t.file = Some(path.clone());
t.written = Some(Arc::downgrade(&st.doc));
t.host = Some(Arc::downgrade(st.drawing()));
t.since = None;
// In the Block Editor: the drawing with the editor's unsaved changes in the block.
jobs.push(Job::Write { uid: st.uid, path, doc: st.recovery_drawing() });
}
jobs
}
/// Seconds from `now` until the next autosave is due, if one is waiting.
pub fn next_due(&self, now: f64, minutes: u32) -> Option<f64> {
if minutes == 0 {
return None;
}
self.docs.values().filter_map(|t| t.since).map(|since| (since + f64::from(minutes) * 60.0 - now).max(0.0)).reduce(f64::min)
}
}
/// A file Drawing Recovery offers: an autosave left behind by an app that is no longer running.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Recoverable {
pub path: String,
/// The drawing's title when it was autosaved.
pub drawing: String,
/// When it was written, in seconds since 1970.
pub modified: u64,
pub bytes: u64,
}
#[cfg(not(target_arch = "wasm32"))]
pub use native::*;
#[cfg(not(target_arch = "wasm32"))]
mod native {
use std::path::Path;
use std::time::{Duration, SystemTime};
use super::*;
/// A new instance id: the process id and the start time.
pub fn instance_id() -> String {
let t = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
format!("{}-{t:x}", std::process::id())
}
fn lock_path(dir: &Path, instance: &str) -> std::path::PathBuf {
dir.join(format!("{instance}.lock"))
}
/// Whether the app instance that owns a lock file modified `age` ago (`None`: no lock file)
/// may still be running.
pub fn instance_alive(age: Option<Duration>) -> bool {
age.is_some_and(|a| a < Duration::from_secs(STALE_LOCK_SECS))
}
fn lock_age(dir: &Path, instance: &str) -> Option<Duration> {
let m = std::fs::metadata(lock_path(dir, instance)).and_then(|m| m.modified()).ok()?;
// A time in the future (clock changes) counts as fresh.
Some(SystemTime::now().duration_since(m).unwrap_or_default())
}
/// The autosave files in `dir` left behind by apps that are no longer running (never those of
/// `own`, this app's instance), oldest first.
pub fn recoverable(dir: &Path, own: &str) -> Vec<Recoverable> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut alive: HashMap<String, bool> = HashMap::new();
let mut out = Vec::new();
for e in entries.flatten().take(10_000) {
let name = e.file_name().to_string_lossy().to_string();
let Some((title, instance, _)) = parse_file_name(&name) else { continue };
if instance == own || *alive.entry(instance.to_string()).or_insert_with(|| instance_alive(lock_age(dir, instance))) {
continue;
}
let Ok(meta) = e.metadata() else { continue };
if !meta.is_file() {
continue;
}
let modified = meta.modified().ok().and_then(|m| m.duration_since(SystemTime::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0);
out.push(Recoverable { path: e.path().to_string_lossy().to_string(), drawing: title.to_string(), modified, bytes: meta.len() });
}
out.sort_by(|a, b| a.modified.cmp(&b.modified).then_with(|| a.path.cmp(&b.path)));
out
}
/// Delete a recovery file the user discarded (or that was recovered and then saved), and lock
/// files of stopped apps that have no files left. Only an autosave file is deleted: a path
/// whose name doesn't parse as one ([`parse_file_name`]) is left alone.
pub fn discard(path: &str) {
let ours = Path::new(path).file_name().and_then(|n| n.to_str()).is_some_and(|n| parse_file_name(n).is_some());
if !ours {
log::warn!("autosave: not deleting {path}: not an autosave file");
return;
}
if let Err(e) = std::fs::remove_file(path)
&& e.kind() != std::io::ErrorKind::NotFound
{
log::warn!("autosave: can't delete {path}: {e}");
}
if let Some(dir) = Path::new(path).parent() {
prune_locks(dir);
}
}
/// Delete the lock files of apps that are no longer running and left no autosave files. Only
/// names of the form `<instance id>.lock` are ours ([`parse_lock_name`]): SAVEFILEPATH may
/// point at a folder shared with other programs, whose `Cargo.lock` or `foo.lock` stay.
pub fn prune_locks(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let names: Vec<String> = entries.flatten().take(10_000).map(|e| e.file_name().to_string_lossy().to_string()).collect();
for n in &names {
let Some(instance) = parse_lock_name(n) else { continue };
let has_files = names.iter().any(|f| parse_file_name(f).is_some_and(|(_, i, _)| i == instance));
if !has_files && !instance_alive(lock_age(dir, instance)) {
let _ = std::fs::remove_file(dir.join(n));
}
}
}
type WriteHook = fn(&Drawing, &str) -> std::result::Result<Vec<u8>, String>;
fn write_file(write: WriteHook, doc: &Drawing, path: &str) -> std::result::Result<(), String> {
let bytes = write(doc, "autosave.dxf")?;
if let Some(dir) = Path::new(path).parent() {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
// Create a fresh temporary file exclusively and rename it into place, so a planted
// `<path>.tmp` symlink in a shared autosave directory cannot redirect the write (CWE-59).
crate::atomic_write::write_atomic(Path::new(path), &bytes).map_err(|e| e.to_string())
}
impl Autosaver {
/// Autosave what is due (writing in the background) and delete files no longer needed.
/// Returns how long until the next autosave is due, so the host can wake up for it.
pub fn tick(&mut self, s: &Session) -> Option<Duration> {
let now = self.start.elapsed().as_secs_f64();
self.reap();
let dir = savefilepath();
let minutes = savetime();
let jobs = self.plan(s, now, minutes, &dir);
self.perform(jobs);
self.heartbeat(&dir, now);
self.next_due(now, minutes).map(Duration::from_secs_f64)
}
/// Autosave every drawing with changes not yet autosaved right away, without waiting for
/// SAVETIME (the app may not survive what just happened, e.g. a GPU error). Returns how
/// many drawings are being written.
pub fn save_now(&mut self, s: &Session) -> usize {
let now = self.start.elapsed().as_secs_f64();
let jobs = self.plan_with(s, now, savetime(), &savefilepath(), true);
let writes = jobs.iter().filter(|j| matches!(j, Job::Write { .. })).count();
self.perform(jobs);
// The lock file marks the files as this running app's (Drawing Recovery skips them).
self.last_beat = None;
self.heartbeat(&savefilepath(), now);
writes
}
/// Take in the writes that have finished ([`Autosaver::tick`] does this first). A drawing
/// whose write failed is no longer counted as autosaved: the next plan restarts its clock,
/// so it is tried again SAVETIME later even if it doesn't change.
pub fn reap(&mut self) {
let (done, running) = std::mem::take(&mut self.running).into_iter().partition::<Vec<_>, _>(|(_, h)| h.is_finished());
self.running = running;
for (uid, h) in done {
self.busy.remove(&uid);
if !h.join().unwrap_or(false) {
self.unwritten(uid);
}
}
}
fn unwritten(&mut self, uid: u64) {
if let Some(t) = self.docs.get_mut(&uid) {
t.written = None;
}
}
/// Carry out jobs from [`Autosaver::plan`]: writes on a background thread, deletes now.
pub fn perform(&mut self, jobs: Vec<Job>) {
for job in jobs {
match job {
Job::Delete { path } => discard(&path),
Job::Write { uid, path, doc } => {
let Some(write) = crate::cmd::file::io().map(|h| h.write) else {
log::warn!("autosave: file formats are not available in this build");
continue;
};
let spawned = std::thread::Builder::new().name("autosave".into()).spawn(move || match write_file(write, &doc, &path) {
Ok(()) => {
log::info!("autosaved {path}");
true
}
Err(e) => {
log::warn!("autosave {path}: {e}");
false
}
});
match spawned {
Ok(h) => {
self.busy.insert(uid);
self.running.push((uid, h));
}
Err(e) => {
log::warn!("autosave: {e}");
self.unwritten(uid);
}
}
}
}
}
}
/// Keep this app's lock file fresh while it has autosave files.
fn heartbeat(&mut self, dir: &str, now: f64) {
if dir.is_empty() || self.docs.values().all(|t| t.file.is_none()) || self.last_beat.is_some_and(|b| now - b < HEARTBEAT_SECS) {
return;
}
self.last_beat = Some(now);
let dir = Path::new(dir);
let r = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(lock_path(dir, &self.instance), std::process::id().to_string()));
if let Err(e) = r {
log::warn!("autosave: lock file in {}: {e}", dir.display());
}
}
/// The app is closing normally: finish writes in progress, then delete this app's autosave
/// files and its lock file.
pub fn shutdown(&mut self) {
for (_, h) in self.running.drain(..) {
let _ = h.join();
}
self.busy.clear();
for path in self.files() {
discard(&path);
}
self.docs.clear();
let dir = savefilepath();
if !dir.is_empty() && is_instance_id(&self.instance) {
let _ = std::fs::remove_file(lock_path(Path::new(&dir), &self.instance));
}
}
}
}
+313
View File
@@ -0,0 +1,313 @@
//! The Block Editor's state (BEDIT). While it is open, the drawing's tab shows the block's objects
//! as its model space, moved so that the block's base point is at the origin, and every command
//! edits them as it would any drawing. The drawing itself waits, untouched, with its undo history,
//! selection and views: BSAVE writes the objects back into the block definition (so every
//! reference shows them), BCLOSE puts the drawing back. The commands are in
//! `cmd::blocks::bedit`.
//!
//! Layer, style and block table changes made in the editor belong to the drawing too, as in
//! AutoCAD: saving keeps the editor's tables and only puts back what is the drawing's own (its
//! model and paper space objects, groups, constraints, tiled viewports and hidden objects).
//!
//! The editor can also open on the drawing itself ([`CURRENT_DRAWING`], AutoCAD's
//! `<Current Drawing>`): a dynamic block's own drawing, whose model space holds the block's
//! objects and authoring elements. Its objects are edited where they are; BSAVE keeps the
//! changes as the drawing's, BCLOSE without saving puts the drawing back as it was.
use std::sync::Arc;
use cadcraft_doc::{Drawing, EntityKind, EntityStore};
use cadcraft_geom::{Mat3, Vec2};
use crate::{DocState, EngineError, Result, Snapshot};
/// The undo step a save into the block records in the drawing.
const UNDO_LABEL: &str = "Block Editor";
/// The name the Block Editor gives the drawing itself (BEDIT `<Current Drawing>`).
pub const CURRENT_DRAWING: &str = "<Current Drawing>";
/// Whether block `name` (or `*Model_Space`, a drawing's own) carries dynamic block data from
/// another program: parameters and actions in the `ACAD_ENHANCEDBLOCK` dictionary of its
/// BLOCK_RECORD table entry.
pub fn has_dynamic_data(d: &Drawing, name: &str) -> bool {
let key = ("BLOCK_RECORD".to_string(), name.to_ascii_uppercase());
let Some(xdict) = d.foreign.records.get(&key).and_then(|x| x.xdict) else { return false };
d.foreign.objects.iter().any(|o| o.handle == xdict && o.tags.iter().any(|t| t.code == 3 && t.value.eq_ignore_ascii_case("ACAD_ENHANCEDBLOCK")))
}
/// Whether drawing `d` has authoring elements: it is a dynamic block's own drawing, its model
/// space carrying the block's parameters and actions (AutoCAD offers to open it in the Block
/// Editor).
pub fn has_authoring_elements(d: &Drawing) -> bool {
has_dynamic_data(d, "*Model_Space")
}
/// The Block Editor open in a drawing.
#[derive(Clone, Debug)]
pub struct BlockEdit {
/// The block being edited, as the drawing names it.
pub name: String,
/// The drawing outside the editor: its drawing, undo history, selection and views, put back
/// by BCLOSE. Its own `block_edit` is always `None`.
pub host: Box<DocState>,
/// The editor's drawing as last saved into the block; later changes are unsaved.
pub saved: Arc<Drawing>,
/// The block's objects as the drawing has them (block coordinates): objects left unchanged in
/// the editor are saved back exactly as they were.
original: EntityStore,
/// The block's base point, at the origin in the editor.
base: Vec2,
/// The editor is open on the drawing itself ([`CURRENT_DRAWING`]).
pub current: bool,
}
/// Why a block can't be opened in the Block Editor, if it can't.
pub fn refusal(d: &Drawing, name: &str) -> Option<String> {
let Some(b) = d.block(name) else { return Some(format!("Block \"{name}\" not found.")) };
if b.xref_path.is_some() {
return Some(format!("\"{}\" is an external reference; open its drawing (XOPEN) to edit it.", b.name));
}
if b.anonymous || b.name.starts_with('*') {
return Some(format!("\"{}\" is an anonymous block made by another object; it can't be edited in the Block Editor.", b.name));
}
None
}
/// `store` moved by `m`, objects in the same order with the same handles.
fn moved(store: &EntityStore, m: &Mat3) -> EntityStore {
let mut out = EntityStore::new();
for e in store.iter() {
let mut e = (**e).clone();
e.kind.transform(m);
out.push(e);
}
out
}
/// Whether any object of `store` refers to block `name`, directly or through nested blocks of `d`.
fn refers_to(d: &Drawing, store: &EntityStore, name: &str) -> bool {
let mut todo: Vec<String> = store.iter().filter_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.block.clone()) } else { None }).collect();
let mut seen = std::collections::HashSet::new();
while let Some(b) = todo.pop() {
if b.eq_ignore_ascii_case(name) {
return true;
}
if seen.insert(b.to_ascii_uppercase())
&& let Some(blk) = d.block(&b)
{
todo.extend(blk.entities.iter().filter_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.block.clone()) } else { None }));
}
}
false
}
impl BlockEdit {
/// The editor's objects in block coordinates, ready to be the block's: unchanged objects are
/// the block's own, the others are moved back from the editor's origin to the base point.
fn block_objects(&self, editor: &Drawing) -> EntityStore {
if self.base == Vec2::ZERO {
return editor.model.clone();
}
let (to_editor, back) = (Mat3::translate(-self.base), Mat3::translate(self.base));
let mut out = EntityStore::new();
for e in editor.model.iter() {
let unchanged = self.original.get(e.handle).filter(|o| {
let mut shown = (***o).clone();
shown.kind.transform(&to_editor);
shown == **e
});
match unchanged {
Some(o) => out.push((**o).clone()),
None => {
let mut e = (**e).clone();
e.kind.transform(&back);
out.push(e);
}
}
}
out
}
/// The drawing with the editor's objects saved into block `name` (the edited block, or a new
/// name for BSAVEAS), from `editor`, the editor's drawing.
pub fn compose(&self, editor: &Drawing, name: &str) -> Result<Drawing> {
// The drawing itself: the editor's drawing is the drawing.
if self.current {
if !name.eq_ignore_ascii_case(CURRENT_DRAWING) {
return Err(EngineError::Other("The current drawing can't be saved as a block from the Block Editor; use WBLOCK or BLOCK.".into()));
}
return Ok(editor.clone());
}
if refers_to(editor, &editor.model, name) {
return Err(EngineError::Other(format!("Block \"{name}\" can't contain a reference to itself.")));
}
let host = &self.host.doc;
let mut d = editor.clone();
d.model = host.model.clone();
d.layouts = host.layouts.clone();
d.groups = host.groups.clone();
d.constraints = host.constraints.clone();
d.vports = host.vports.clone();
d.hidden_objects = host.hidden_objects.clone();
let entities = self.block_objects(editor);
// The edited block's properties (the editor's definition, else the drawing's): the objects
// are placed for its base point, also when saved under another name (BSAVEAS).
let template = editor.block(&self.name).or_else(|| host.block(&self.name));
let mut b = match template {
Some(b) => (**b).clone(),
None => cadcraft_doc::Block::new(name),
};
// Block names are case-insensitive: an existing block keeps its name's spelling.
let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned().unwrap_or_else(|| name.to_string());
if !b.name.eq_ignore_ascii_case(name) {
b.name = key.clone();
}
b.base.x = self.base.x;
b.base.y = self.base.y;
b.entities = entities;
d.blocks.insert(key, Arc::new(b));
Ok(d)
}
}
impl DocState {
/// The drawing as a file saves it: outside the Block Editor's changes while it is open.
pub fn drawing(&self) -> &Arc<Drawing> {
match &self.block_edit {
Some(be) => &be.host.doc,
None => &self.doc,
}
}
/// [`DocState::drawing`], to change it (a save's file version).
pub fn drawing_arc_mut(&mut self) -> &mut Arc<Drawing> {
match &mut self.block_edit {
Some(be) => &mut be.host.doc,
None => &mut self.doc,
}
}
/// The block the Block Editor is editing, when it is open.
pub fn block_editor(&self) -> Option<&str> {
self.block_edit.as_ref().map(|b| b.name.as_str())
}
/// The Block Editor has changes not yet saved into the block.
pub fn block_unsaved(&self) -> bool {
self.block_edit.as_ref().is_some_and(|b| !Arc::ptr_eq(&b.saved, &self.doc))
}
/// The drawing to keep for recovery (autosave): with the Block Editor's unsaved changes in the
/// block, so a crash doesn't lose them.
pub fn recovery_drawing(&self) -> Arc<Drawing> {
match &self.block_edit {
Some(be) if self.block_unsaved() => be.compose(&self.doc, &be.name).map(Arc::new).unwrap_or_else(|_| be.host.doc.clone()),
Some(be) => be.host.doc.clone(),
None => self.doc.clone(),
}
}
/// Open the Block Editor on block `name` (BEDIT).
/// With `create`, a name no block has yet starts a new, empty block, which BSAVE creates.
pub fn open_block_editor(&mut self, name: &str, create: bool) -> Result<()> {
if let Some(open) = self.block_editor() {
return Err(EngineError::Other(format!("The Block Editor is already open on \"{open}\"; close it first (BCLOSE).")));
}
if name.trim().eq_ignore_ascii_case(CURRENT_DRAWING) {
let host = Box::new(self.clone());
let editor = self.doc.clone();
self.enter_block_editor(BlockEdit {
name: CURRENT_DRAWING.into(),
host,
saved: editor,
original: EntityStore::new(),
base: Vec2::ZERO,
current: true,
});
return Ok(());
}
let block = match self.doc.block(name) {
None if create => Arc::new(cadcraft_doc::Block::new(name)),
_ => {
if let Some(why) = refusal(&self.doc, name) {
return Err(EngineError::Other(why));
}
self.doc.block(name).cloned().ok_or_else(|| EngineError::Other(format!("Block \"{name}\" not found.")))?
}
};
let base = block.base.xy();
let mut d = (*self.doc).clone();
d.model = if base == Vec2::ZERO { block.entities.clone() } else { moved(&block.entities, &Mat3::translate(-base)) };
// The drawing's own groups, constraints and hidden objects stay with it.
d.groups.clear();
d.constraints.clear();
d.hidden_objects.clear();
let host = Box::new(self.clone());
let editor = Arc::new(d);
self.doc = editor.clone();
self.enter_block_editor(BlockEdit { name: block.name.clone(), host, saved: editor, original: block.entities.clone(), base, current: false });
Ok(())
}
/// Start editing in the Block Editor `be` (the drawing is already the editor's): a fresh
/// undo history, nothing selected, model space.
fn enter_block_editor(&mut self, be: BlockEdit) {
self.undo.clear();
self.redo.clear();
self.undo_ctl = Default::default();
self.selection.clear();
self.previous_selection.clear();
self.space = cadcraft_doc::Space::Model;
self.mspace = None;
self.tiles = Default::default();
self.views.clear();
self.view_history.clear();
self.block_edit = Some(be);
self.revision += 1;
}
/// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name`
/// (BSAVEAS), which the editor then edits. One undo step in the drawing.
pub fn save_block_editor(&mut self, as_name: Option<&str>) -> Result<()> {
let Some(be) = &self.block_edit else { return Err(EngineError::Other("The Block Editor is not open.".into())) };
let name = as_name.unwrap_or(&be.name).to_string();
let d = be.compose(&self.doc, &name)?;
let original = d.block(&name).map(|b| b.entities.clone()).unwrap_or_default();
let name = d.block(&name).map(|b| b.name.clone()).unwrap_or(name);
let editor = self.doc.clone();
let Some(be) = &mut self.block_edit else { return Ok(()) };
let before = be.host.doc.clone();
let selection = be.host.selection.clone();
be.host.push_undo(Snapshot { label: UNDO_LABEL.into(), doc: before, selection });
be.host.doc = Arc::new(d);
be.host.revision += 1;
be.original = original;
be.saved = editor;
be.name = name;
self.revision += 1;
Ok(())
}
/// Close the Block Editor (BCLOSE), saving its changes into the block first when `save`.
pub fn close_block_editor(&mut self, save: bool) -> Result<()> {
if self.block_edit.is_none() {
return Err(EngineError::Other("The Block Editor is not open.".into()));
}
if save && self.block_unsaved() {
self.save_block_editor(None)?;
}
let Some(be) = self.block_edit.take() else { return Ok(()) };
let host = *be.host;
self.doc = host.doc;
self.undo = host.undo;
self.redo = host.redo;
self.undo_ctl = host.undo_ctl;
// The drawing comes back with nothing selected; Previous is what was selected before.
self.selection.clear();
self.previous_selection = if host.selection.is_empty() { host.previous_selection } else { host.selection };
self.space = host.space;
self.mspace = host.mspace;
self.tiles = host.tiles;
self.views = host.views;
self.view_history = host.view_history;
self.revision += 1;
Ok(())
}
}
+84
View File
@@ -0,0 +1,84 @@
//! Bounded reads of local files.
//!
//! Reading a path with [`std::fs::read`] buffers until EOF, so a path naming an endless readable
//! device (for example `/dev/urandom` or a FIFO) exhausts process memory before any size check
//! runs (CWE-400). [`read_capped`] opens the path once, refuses anything that is not a regular
//! file, and reads through a reader limited to `max + 1` bytes so oversized input is rejected
//! before it is fully buffered.
#![cfg(not(target_arch = "wasm32"))]
use std::fs::OpenOptions;
use std::io::{self, Read};
use std::path::Path;
/// Read at most `max` bytes from the regular file at `path`.
///
/// Returns an error if the path is not a regular file, cannot be opened, or holds more than `max`
/// bytes. At most `max + 1` bytes are ever buffered, so an endless device cannot exhaust memory.
pub fn read_capped(path: &Path, max: usize) -> io::Result<Vec<u8>> {
let mut options = OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NONBLOCK);
}
let file = options.open(path)?;
let meta = file.metadata()?;
if !meta.is_file() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file"));
}
// Read one byte past the limit so we can tell "exactly max" from "too big" without trusting
// the metadata length (which a device may misreport).
let mut buf = Vec::new();
let cap = (max as u64).saturating_add(1);
let read = file.take(cap).read_to_end(&mut buf)?;
if read as u64 > max as u64 {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("file is larger than the {max}-byte limit")));
}
Ok(buf)
}
#[cfg(test)]
mod tests {
use super::*;
/// Regular-file reads accept the byte boundary and reject any larger payload.
#[test]
fn reads_within_limit_and_rejects_oversize() {
let dir = std::env::temp_dir().join(format!("cadcraft-cr-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("f.bin");
std::fs::write(&p, vec![7u8; 100]).unwrap();
assert_eq!(read_capped(&p, 100).unwrap().len(), 100);
assert_eq!(read_capped(&p, 200).unwrap().len(), 100);
assert!(read_capped(&p, 99).is_err());
assert_eq!(read_capped(&p, usize::MAX).unwrap().len(), 100);
std::fs::remove_dir_all(&dir).ok();
}
/// An endless device is rejected before its contents can be buffered.
#[cfg(unix)]
#[test]
fn rejects_non_regular_file() {
// /dev/zero is an endless readable device; it must be rejected, not buffered.
let p = Path::new("/dev/zero");
if p.exists() {
assert!(read_capped(p, 8 << 20).is_err());
}
}
/// Opening a FIFO without a writer returns an error without waiting for a peer.
#[cfg(unix)]
#[test]
fn rejects_fifo_without_a_writer() {
let dir = std::env::temp_dir().join(format!("cadcraft-cr-fifo-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let fifo = dir.join("pipe");
assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
let started = std::time::Instant::now();
assert_eq!(read_capped(&fifo, 1024).unwrap_err().kind(), io::ErrorKind::InvalidInput);
assert!(started.elapsed() < std::time::Duration::from_secs(2));
std::fs::remove_dir_all(dir).unwrap();
}
}
+589
View File
@@ -0,0 +1,589 @@
//! Annotative scaling: the drawing's scale list (SCALELISTEDIT), the scales annotative objects
//! support (OBJECTSCALE, Add/Delete Current Scale, ANNORESET, ANNOUPDATE), which annotative
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
//! ANNOAUTOSCALE).
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
use serde_json::{Value, json};
use super::machines::{SelOutcome, SelectPhase, SelectRun};
use super::*;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("scalelistedit", "Scale List...", run_scalelistedit)
.menu(&["Format", "Scale List..."])
.alias(&["-scalelistedit"])
.params(
"{add?: {name, ratio: \"paper:drawing\" (e.g. \"1:50\") | paperUnits + drawingUnits}, delete?: name | [names], reset?: true | \"metric\" | \"imperial\"} → scales, current (no parameters: list only)",
)
.interactive(|_| Ok(Box::new(ScaleListM::default()))),
CommandSpec::new("objectscale", "Add/Delete Scales...", run_objectscale)
.menu(&["Modify", "Annotative Object Scale", "Add/Delete Scales..."])
.alias(&["-objectscale"])
.params("{handles?, add?: name | [names], delete?: name | [names]} (scales of the drawing's list; an object keeps at least one) → changed, objects")
.interactive(|_| Ok(Box::new(ObjectScaleM::default()))),
CommandSpec::new("aiobjectscaleadd", "Add Current Scale", run_add_current)
.menu(&["Modify", "Annotative Object Scale", "Add Current Scale"])
.params("{handles?} (adds the current annotation scale to the annotative objects)")
.interactive(|_| Ok(Box::new(SelectRun::new("aiobjectscaleadd", "AIOBJECTSCALEADD")))),
CommandSpec::new("aiobjectscaleremove", "Delete Current Scale", run_remove_current)
.menu(&["Modify", "Annotative Object Scale", "Delete Current Scale"])
.params("{handles?} (removes the current annotation scale from the annotative objects; an object keeps at least one)")
.interactive(|_| Ok(Box::new(SelectRun::new("aiobjectscaleremove", "AIOBJECTSCALEREMOVE")))),
CommandSpec::new("annoreset", "Synchronize Multiple-scale Positions", run_annoreset)
.menu(&["Modify", "Annotative Object Scale", "Synchronize Multiple-scale Positions"])
.params("{handles?} (every scale of an annotative object shares one position)")
.interactive(|_| Ok(Box::new(SelectRun::new("annoreset", "ANNORESET")))),
CommandSpec::new("annoupdate", "Annotative Update", run_annoupdate)
.params("{handles?} (makes text, dimensions, multileaders and block references annotative or not as their style or block is)")
.interactive(|_| Ok(Box::new(SelectRun::new("annoupdate", "ANNOUPDATE")))),
CommandSpec::new("annovisible.current", "Current Scale Only", |s, _| set_all_visible(s, Some(false)))
.menu(&["View", "Show Annotative Objects", "Current Scale Only"])
.params("{} (ANNOALLVISIBLE 0: annotative objects show only at scales they support)"),
CommandSpec::new("annovisible.all", "All Scales", |s, _| set_all_visible(s, Some(true)))
.menu(&["View", "Show Annotative Objects", "All Scales"])
.params("{} (ANNOALLVISIBLE 1: every annotative object shows)"),
CommandSpec::new("annovisible.toggle", "Annotation Visibility", |s, _| set_all_visible(s, None)).params("{} (toggles ANNOALLVISIBLE)"),
]
}
/// The most objects one command call reports scales for.
const MAX_REPORTED: usize = 1000;
fn scale_json(sc: &AnnoScale) -> Value {
json!({ "name": sc.name, "paperUnits": sc.paper_units, "drawingUnits": sc.drawing_units })
}
fn list_json(d: &Drawing) -> Value {
json!({ "scales": d.scales.iter().map(scale_json).collect::<Vec<_>>(), "current": d.current_anno_scale().name })
}
/// Scale names given as one string or an array of strings.
fn names(cmd: &str, v: Option<&Value>) -> Result<Vec<String>> {
match v {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::String(s)) => Ok(vec![s.trim().to_string()]),
Some(Value::Array(a)) if a.len() <= MAX_SCALES => {
a.iter().map(|v| v.as_str().map(|s| s.trim().to_string()).ok_or_else(|| bad(cmd, "scale names must be strings"))).collect()
}
Some(_) => Err(bad(cmd, "expected a scale name or an array of scale names")),
}
}
fn find_scale(d: &Drawing, cmd: &str, name: &str) -> Result<AnnoScale> {
d.anno_scale(name).cloned().ok_or_else(|| bad(cmd, format!("`{name}` is not in the scale list")))
}
/// A scale ratio typed as `paper:drawing` or `paper=drawing`, each side a number or distance
/// (`1:50`, `2:1`, `1/4":1'`).
pub(crate) fn parse_ratio(t: &str) -> Option<(f64, f64)> {
let (a, b) = t.split_once(':').or_else(|| t.split_once('='))?;
let ok = |v: f64| v.is_finite() && v > 0.0;
let a = crate::units::parse_distance(a).filter(|v| ok(*v))?;
let b = crate::units::parse_distance(b).filter(|v| ok(*v))?;
Some((a, b))
}
/// Make `name` the current annotation scale (CANNOSCALE). With ANNOAUTOSCALE on, the annotative
/// objects of model space on layers that are on, thawed and unlocked get the scale too.
pub(crate) fn set_current(s: &mut Session, name: &str) -> Result<()> {
let sc = find_scale(s.doc()?, "setvar", name)?;
let auto = s.settings.annoautoscale;
let d = s.doc_mut()?;
d.header.set_str("CANNOSCALE", &sc.name);
if auto {
let usable = |e: &cadcraft_doc::Entity| d.layer(&e.common.layer).is_none_or(|l| l.visible() && !l.locked);
let hs: Vec<Handle> = d.model.iter().filter(|e| is_annotative(e) && usable(e)).map(|e| e.handle).collect();
for h in hs {
add_scale(d, h, &sc);
}
}
Ok(())
}
/// Add `sc` to annotative object `h`; whether it changed.
fn add_scale(d: &mut Drawing, h: Handle, sc: &AnnoScale) -> bool {
let mut changed = false;
let _ = d.modify_entity(h, |e| {
if is_annotative(e) && !e.common.supports_scale(&sc.name) && e.common.anno_scales.len() < MAX_SCALES {
e.common.anno_scales.push(sc.clone());
changed = true;
}
});
changed
}
/// What removing a scale from an object did.
#[derive(PartialEq)]
enum Removed {
Yes,
/// It is the object's only scale.
Last,
No,
}
fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
let mut r = Removed::No;
let _ = d.modify_entity(h, |e| {
if !is_annotative(e) || !e.common.supports_scale(name) {
return;
}
if e.common.anno_scales.len() < 2 {
r = Removed::Last;
return;
}
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
r = Removed::Yes;
});
r
}
/// The annotative objects among the targets (an error when nothing is selected).
fn annotative_targets(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<Handle>, usize)> {
let hs = targets(s, p)?;
if hs.is_empty() {
return Err(bad(cmd, "nothing selected"));
}
let d = s.doc()?;
let total = hs.len();
let anno: Vec<Handle> = hs.into_iter().filter(|h| d.entity(*h).is_some_and(|e| is_annotative(e))).collect();
Ok((anno, total))
}
fn objects_json(d: &Drawing, hs: &[Handle]) -> Value {
json!(
hs.iter()
.take(MAX_REPORTED)
.filter_map(|h| d.entity(*h))
.map(|e| json!({ "handle": e.handle.hex(), "scales": e.common.anno_scales.iter().map(|s| s.name.clone()).collect::<Vec<_>>() }))
.collect::<Vec<_>>()
)
}
fn run_objectscale(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "objectscale";
let (hs, total) = annotative_targets(s, p, CMD)?;
let d = s.doc()?;
let add = names(CMD, p.get("add"))?.iter().map(|n| find_scale(d, CMD, n)).collect::<Result<Vec<_>>>()?;
let del = names(CMD, p.get("delete"))?;
let d = s.doc_mut()?;
let (mut changed, mut last) = (0usize, 0usize);
for h in &hs {
let mut any = false;
for sc in &add {
any |= add_scale(d, *h, sc);
}
for n in &del {
match remove_scale(d, *h, n) {
Removed::Yes => any = true,
Removed::Last => last += 1,
Removed::No => {}
}
}
changed += usize::from(any);
}
let mut msg = format!("{changed} of {total} object(s) changed");
if hs.len() < total {
msg.push_str(&format!(", {} not annotative", total - hs.len()));
}
if last > 0 {
msg.push_str(&format!(", {last} scale(s) kept as an object's only scale"));
}
Ok(json!({ "changed": changed, "annotative": hs.len(), "objects": objects_json(d, &hs), "message": msg }))
}
fn run_add_current(s: &mut Session, p: &Value) -> Result<Value> {
let cur = s.doc()?.current_anno_scale();
run_objectscale(s, &with_handles(s, p, json!({ "add": cur.name })))
}
fn run_remove_current(s: &mut Session, p: &Value) -> Result<Value> {
let cur = s.doc()?.current_anno_scale();
run_objectscale(s, &with_handles(s, p, json!({ "delete": cur.name })))
}
/// `extra` with the targets of `p` as `handles`.
fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
let hs = targets(s, p).unwrap_or_default();
if let Some(o) = extra.as_object_mut() {
o.insert("handles".into(), json!(hs.iter().map(|h| h.hex()).collect::<Vec<_>>()));
}
extra
}
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
let (hs, _) = annotative_targets(s, p, "annoreset")?;
// One position serves every scale of an object, so they are always in step.
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
}
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.is_empty() {
return Err(bad("annoupdate", "nothing selected"));
}
let d = s.doc()?;
let cur = d.current_anno_scale();
// Hatches have no style: HPANNOTATIVE only sets new ones.
let plan: Vec<(Handle, bool)> = hs
.iter()
.filter_map(|h| d.entity(*h))
.filter(|e| cadcraft_doc::can_be_annotative(&e.kind) && !matches!(e.kind, EntityKind::Hatch(_)))
.map(|e| (e.handle, d.annotative_by_style(&e.kind)))
.filter(|(h, want)| d.entity(*h).is_some_and(|e| is_annotative(e) != *want))
.collect();
let d = s.doc_mut()?;
for (h, want) in &plan {
d.modify_entity(*h, |e| cadcraft_doc::set_annotative(e, *want, &cur))?;
}
Ok(json!({ "updated": plan.len(), "message": format!("{} object(s) updated", plan.len()) }))
}
fn set_all_visible(s: &mut Session, on: Option<bool>) -> Result<Value> {
let d = s.doc_mut()?;
let on = on.unwrap_or(!d.anno_all_visible());
d.header.set_i64("ANNOALLVISIBLE", i64::from(on));
Ok(json!({ "annoallvisible": i64::from(on) }))
}
// ---------------- the scale list ----------------
/// Scales objects use, and the current one: they stay when the list is reset and can't be
/// deleted.
fn in_use(d: &Drawing) -> Vec<AnnoScale> {
let mut v = vec![d.current_anno_scale()];
let ents = d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter()));
for e in ents.filter(|e| is_annotative(e)) {
for sc in &e.common.anno_scales {
if v.len() < MAX_SCALES && !v.iter().any(|u| u.name.eq_ignore_ascii_case(&sc.name)) {
v.push(sc.clone());
}
}
}
v
}
fn add_to_list(d: &mut Drawing, sc: AnnoScale) -> Result<()> {
const CMD: &str = "scalelistedit";
let name = sc.name.trim();
if name.is_empty() || name.chars().count() > 255 {
return Err(bad(CMD, "a scale name has 1 to 255 characters"));
}
if !sc.is_valid() {
return Err(bad(CMD, "paper and drawing units must be positive"));
}
if d.anno_scale(name).is_some() {
return Err(bad(CMD, format!("a scale named `{name}` already exists")));
}
if d.scales.len() >= MAX_SCALES {
return Err(bad(CMD, "the scale list is full"));
}
d.scales.push(AnnoScale { name: name.to_string(), ..sc });
Ok(())
}
fn delete_from_list(d: &mut Drawing, name: &str) -> Result<()> {
const CMD: &str = "scalelistedit";
let sc = find_scale(d, CMD, name)?;
if d.current_anno_scale().name.eq_ignore_ascii_case(&sc.name) {
return Err(bad(CMD, format!("`{}` is the current annotation scale", sc.name)));
}
if in_use(d).iter().any(|u| u.name.eq_ignore_ascii_case(&sc.name)) {
return Err(bad(CMD, format!("`{}` is used by annotative objects", sc.name)));
}
d.scales.retain(|s| !s.name.eq_ignore_ascii_case(&sc.name));
Ok(())
}
/// Replace the list with the default metric or imperial one, keeping scales in use.
fn reset_list(d: &mut Drawing, metric: bool) {
let keep = in_use(d);
let mut list = if metric { cadcraft_doc::metric_scales() } else { cadcraft_doc::imperial_scales() };
for sc in keep {
if !list.iter().any(|l| l.name.eq_ignore_ascii_case(&sc.name)) {
list.push(sc);
}
}
d.scales = list;
}
fn run_scalelistedit(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "scalelistedit";
let metric = s.doc()?.header.i64("MEASUREMENT", 0) == 1;
let reset = match p.get("reset") {
None | Some(Value::Null) | Some(Value::Bool(false)) => None,
Some(Value::Bool(true)) => Some(metric),
Some(Value::String(t)) if t.eq_ignore_ascii_case("metric") => Some(true),
Some(Value::String(t)) if t.eq_ignore_ascii_case("imperial") => Some(false),
Some(_) => return Err(bad(CMD, "`reset` is true, \"metric\" or \"imperial\"")),
};
let del = names(CMD, p.get("delete"))?;
let add = match p.get("add") {
None | Some(Value::Null) => None,
Some(a) => {
let name = a.get("name").and_then(Value::as_str).ok_or_else(|| bad(CMD, "`add.name` is required"))?;
let (pu, du) = match a.get("ratio").and_then(Value::as_str) {
Some(r) => parse_ratio(r).ok_or_else(|| bad(CMD, format!("`{r}` is not a ratio such as 1:50")))?,
None => (f64_req(CMD, a, "paperUnits")?, f64_req(CMD, a, "drawingUnits")?),
};
Some(AnnoScale::new(name, pu, du))
}
};
let d = s.doc_mut()?;
if let Some(m) = reset {
reset_list(d, m);
}
for n in &del {
delete_from_list(d, n)?;
}
if let Some(sc) = add {
add_to_list(d, sc)?;
}
Ok(list_json(d))
}
fn echo_list(s: &mut Session) {
let lines: Vec<String> = s
.doc()
.map(|d| {
d.scales
.iter()
.map(|sc| format!(" {} ({} paper = {} drawing)", sc.name, fmt_units(sc.paper_units), fmt_units(sc.drawing_units)))
.collect()
})
.unwrap_or_default();
for l in lines {
s.echo(l);
}
}
fn fmt_units(v: f64) -> String {
let r = (v * 1e6).round() / 1e6;
if r.fract() == 0.0 { format!("{r:.0}") } else { format!("{r}") }
}
#[derive(Default)]
enum ListStage {
#[default]
Option,
AddName,
AddRatio(String),
Delete,
Reset,
}
/// -SCALELISTEDIT: "Enter option [?/Add/Delete/Reset/Exit]", repeated until Exit or Enter.
#[derive(Default)]
struct ScaleListM {
stage: ListStage,
}
impl Interactive for ScaleListM {
fn name(&self) -> &'static str {
"SCALELISTEDIT"
}
fn prompt(&self, _s: &Session) -> Prompt {
match &self.stage {
ListStage::Option => Prompt::new("Enter option", Accept::TEXT).kw(&["?", "Add", "Delete", "Reset", "Exit"]).default("Exit"),
ListStage::AddName => Prompt::new("Enter name for new scale", Accept::TEXT),
ListStage::AddRatio(_) => Prompt::new("Enter scale ratio (paper units:drawing units)", Accept::TEXT).default("1:1"),
ListStage::Delete => Prompt::new("Enter name of scale to delete", Accept::TEXT).kw(&["?"]),
ListStage::Reset => Prompt::new("Reset the scale list to the defaults?", Accept::TEXT).kw(&["Yes", "No"]).default("No"),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let text = match i {
Input::Cancel => return Ok(Step::Cancel),
Input::Enter => String::new(),
Input::Text(t) | Input::Keyword(t) => t.trim().to_string(),
_ => return Ok(Step::Continue),
};
let stage = std::mem::take(&mut self.stage);
let result = match stage {
ListStage::Option => match text.to_ascii_lowercase().as_str() {
"" | "e" | "exit" => return Ok(Step::Done),
"?" => {
echo_list(s);
Ok(())
}
"a" | "add" => {
self.stage = ListStage::AddName;
Ok(())
}
"d" | "delete" => {
self.stage = ListStage::Delete;
Ok(())
}
"r" | "reset" => {
self.stage = ListStage::Reset;
Ok(())
}
_ => {
s.echo("Invalid option keyword.");
Ok(())
}
},
ListStage::AddName if text.is_empty() => Ok(()),
ListStage::AddName => {
if s.doc()?.anno_scale(&text).is_some() {
s.echo(format!("A scale named \"{text}\" already exists."));
} else {
self.stage = ListStage::AddRatio(text);
}
Ok(())
}
ListStage::AddRatio(name) => {
let t = if text.is_empty() { "1:1" } else { text.as_str() };
match parse_ratio(t) {
Some((pu, du)) => add_to_list(s.doc_mut()?, AnnoScale::new(&name, pu, du)),
None => {
s.echo("Enter a ratio such as 1:50.");
self.stage = ListStage::AddRatio(name);
Ok(())
}
}
}
ListStage::Delete => match text.as_str() {
"" => Ok(()),
"?" => {
echo_list(s);
self.stage = ListStage::Delete;
Ok(())
}
n => delete_from_list(s.doc_mut()?, n),
},
ListStage::Reset => {
if matches!(text.to_ascii_lowercase().as_str(), "y" | "yes") {
let metric = s.doc()?.header.i64("MEASUREMENT", 0) == 1;
reset_list(s.doc_mut()?, metric);
}
Ok(())
}
};
if let Err(e) = result {
s.echo(e.to_string());
}
Ok(Step::Continue)
}
}
#[derive(Default, Clone, Copy, PartialEq)]
enum ObjStage {
#[default]
Select,
Option,
Add,
Delete,
}
/// -OBJECTSCALE: select annotative objects, then add or delete scales by name until Enter.
#[derive(Default)]
struct ObjectScaleM {
sel: SelectPhase,
stage: ObjStage,
hs: Vec<Handle>,
}
impl ObjectScaleM {
/// Keep the annotative objects of the selection; false when there are none.
fn take(&mut self, s: &mut Session, picked: Vec<Handle>) -> Result<bool> {
let d = s.doc()?;
self.hs = picked.into_iter().filter(|h| d.entity(*h).is_some_and(|e| is_annotative(e))).collect();
if self.hs.is_empty() {
s.echo("No annotative objects selected.");
return Ok(false);
}
self.stage = ObjStage::Option;
Ok(true)
}
fn apply(&self, s: &mut Session, key: &str, name: &str) {
let mut p = json!({ "handles": self.hs.iter().map(|h| h.hex()).collect::<Vec<_>>() });
if let Some(o) = p.as_object_mut() {
o.insert(key.to_string(), json!(name));
}
match run_objectscale(s, &p) {
Ok(r) => {
if let Some(m) = r.get("message").and_then(Value::as_str) {
s.echo(m.to_string());
}
}
Err(e) => s.echo(e.to_string()),
}
}
fn echo_supported(&self, s: &mut Session) {
let Ok(d) = s.doc() else { return };
let mut names: Vec<String> = Vec::new();
for e in self.hs.iter().filter_map(|h| d.entity(*h)) {
for sc in &e.common.anno_scales {
if names.len() < MAX_SCALES && !names.iter().any(|n| n.eq_ignore_ascii_case(&sc.name)) {
names.push(sc.name.clone());
}
}
}
s.echo(format!("Scales of the selected objects: {}", names.join(", ")));
}
}
impl Interactive for ObjectScaleM {
fn name(&self) -> &'static str {
"OBJECTSCALE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.sel = SelectPhase::begin(s);
if self.sel.done {
let picked = self.sel.picked.clone();
if !self.take(s, picked)? {
return Ok(Step::Done);
}
}
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
let cur = s.doc().map(|d| d.current_anno_scale().name).unwrap_or_else(|_| "1:1".into());
match self.stage {
ObjStage::Select => Prompt::new(if self.sel.removing { "Remove objects" } else { "Select annotative objects" }, Accept::SELECT),
ObjStage::Option => Prompt::new("Enter an option", Accept::TEXT).kw(&["Add", "Delete", "?"]),
ObjStage::Add => Prompt::new("Enter named scale to add", Accept::TEXT).kw(&["?"]).default(cur),
ObjStage::Delete => Prompt::new("Enter named scale to delete", Accept::TEXT).kw(&["?"]).default(cur),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if i == Input::Cancel {
return Ok(Step::Cancel);
}
if self.stage == ObjStage::Select {
return match self.sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => Ok(if self.take(s, hs)? { Step::Continue } else { Step::Done }),
};
}
let text = match i {
Input::Enter => String::new(),
Input::Text(t) | Input::Keyword(t) => t.trim().to_string(),
_ => return Ok(Step::Continue),
};
match self.stage {
ObjStage::Option => match text.to_ascii_lowercase().as_str() {
"" => return Ok(Step::Done),
"a" | "add" => self.stage = ObjStage::Add,
"d" | "delete" => self.stage = ObjStage::Delete,
"?" => self.echo_supported(s),
_ => s.echo("Invalid option keyword."),
},
stage @ (ObjStage::Add | ObjStage::Delete) => {
if text == "?" {
echo_list(s);
return Ok(Step::Continue);
}
let name = if text.is_empty() { s.doc()?.current_anno_scale().name } else { text };
self.apply(s, if stage == ObjStage::Add { "add" } else { "delete" }, &name);
self.stage = ObjStage::Option;
}
ObjStage::Select => {}
}
Ok(Step::Continue)
}
}
+224 -85
View File
@@ -1,13 +1,14 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE.
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
use cadcraft_doc::{AssocSnap, DimAssoc, DimKind, Dimension, EntityKind, Handle, MLeader, MText, Prim};
use cadcraft_geom::{Segment, Vec2, Vec3};
use serde_json::{Value, json};
use super::helpers::v3;
use super::machines::SelectRun;
use super::machines::{SelOutcome, SelectPhase, SelectRun};
use super::*;
use crate::{Accept, EngineError, Input, Interactive, LeaderOrder, MLeaderOptions, Prompt, Result, Session, Step};
@@ -58,9 +59,10 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["dba", "dimbase"])
.params("{points: [[x,y]...]} (baseline from the last linear dimension)")
.interactive(|s| Ok(Box::new(ChainM::new(s, true)))),
CommandSpec::new("qdim", "Quick Dimension", run_qdim)
CommandSpec::new("qdim", "Quick Dimension", qdim::run)
.menu(&["Dimension", "Quick Dimension"])
.params("{handles?, at: [x,y], vertical?: bool}"),
.params(qdim::PARAMS)
.interactive(|_| Ok(Box::new(qdim::QDimM::new()))),
CommandSpec::new("dim", "Dimension", run_linear)
.menu(&["Dimension", "Dimension"])
.params("{p1, p2, at}")
@@ -68,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("mleader", "Multileader", run_mleader)
.menu(&["Dimension", "Multileader"])
.alias(&["mld"])
.params("{points: [[arrow], ..., [landing]], text}")
.params("{points: [[arrow], ..., [landing]] ([location] with leaderType none), text?, leaderType?: straight|spline|none, block?: name, blockAttach?: center|insertion}")
.interactive(|s| Ok(Box::new(MLeaderM::new(s)))),
CommandSpec::new("leader", "Leader", run_leader).alias(&["lead"]).params("{points: [[x,y]...], text?}"),
CommandSpec::new("dimstyle.update", "Update", run_update)
@@ -92,7 +94,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("dimtedit.home", "Home", |s, p| run_tedit(s, p, "home")).menu(&["Dimension", "Align Text", "Home"]).params("{handles?}"),
CommandSpec::new("dimtedit.angle", "Angle", |s, p| run_tedit(s, p, "angle"))
.menu(&["Dimension", "Align Text", "Angle"])
.params("{handles?, angle: degrees}"),
.params("{handles?, angle: degrees}")
.interactive(|_| Ok(Box::new(tedit::TEditM::angle()))),
CommandSpec::new("dimtedit.left", "Left", |s, p| run_tedit(s, p, "left")).menu(&["Dimension", "Align Text", "Left"]).params("{handles?}"),
CommandSpec::new("dimtedit.center", "Center", |s, p| run_tedit(s, p, "center"))
.menu(&["Dimension", "Align Text", "Center"])
@@ -104,8 +107,12 @@ pub fn specs() -> Vec<CommandSpec> {
.interactive(|_| Ok(Box::new(tedit::TEditM::default()))),
CommandSpec::new("dimspace", "Dimension Space", run_dimspace)
.menu(&["Dimension", "Dimension Space"])
.params("{base: hex, handles: [hex], spacing?: number (default DIMDLI)}"),
.params("{base: hex, handles: [hex], spacing?: number (default DIMDLI)}")
.interactive(|_| Ok(Box::new(DimSpaceM::default()))),
]
.into_iter()
.chain(dimedit::specs())
.collect()
}
fn style(s: &Session) -> String {
@@ -129,6 +136,7 @@ fn dim(s: &Session, kind: DimKind, defpt: Vec2, p13: Vec2, p14: Vec2, p15: Vec2,
block: None,
overrides: s.doc().map(|d| d.dim_overrides()).unwrap_or_default(),
assoc: Vec::new(),
marks: Default::default(),
})
}
@@ -252,18 +260,16 @@ fn radial(s: &mut Session, p: &Value, diameter: bool) -> Result<Value> {
dim(s, DimKind::Radius, c, Vec2::ZERO, Vec2::ZERO, pt, Vec2::ZERO, "")
};
let k = match at {
Some(at) => text_inside(k, c, c.dist(pt), at),
Some(at) => text_at(k, at),
None => k,
};
Ok(json!({ "handle": add_dim(s, k)?.hex() }))
}
/// A radius/diameter dimension line location picked inside the circle puts the text there, on
/// the dimension line (outside, the text keeps its default place beyond the arrowhead).
fn text_inside(mut k: EntityKind, c: Vec2, r: f64, at: Vec2) -> EntityKind {
if let EntityKind::Dimension(d) = &mut k
&& at.dist(c) < r
{
/// The dimension line location of a radius/diameter dimension puts the text there, inside or
/// outside the circle, as a user-positioned text (DXF flag 70 bit 128), like AutoCAD.
fn text_at(mut k: EntityKind, at: Vec2) -> EntityKind {
if let EntityKind::Dimension(d) = &mut k {
d.text_mid = v3(at);
d.user_text_pos = true;
}
@@ -371,6 +377,7 @@ fn chained(s: &Session, prev: &Dimension, next: Vec2, baseline: bool) -> EntityK
text: String::new(),
block: None,
assoc: Vec::new(),
marks: Default::default(),
user_text_pos: false,
..prev.clone()
})
@@ -410,55 +417,9 @@ fn run_baseline(s: &mut Session, p: &Value) -> Result<Value> {
chain_run(s, p, true)
}
/// QDIM: continuous dimensions across the endpoints of the selected objects.
fn run_qdim(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.len() > MAX_CHAIN {
return Err(bad("qdim", format!("at most {MAX_CHAIN} objects per call")));
}
let at = point_req("qdim", p, "at")?;
let vertical = bool_or(p, "vertical", false);
let d = s.doc()?;
let mut pts: Vec<Vec2> = Vec::new();
for h in &hs {
if let Some(e) = d.entity(*h) {
for pr in e.kind.prims() {
match pr {
Prim::Seg(seg) => pts.extend([seg.start(), seg.end()]),
Prim::Circle(c) => pts.push(c.center),
Prim::Point(q) => pts.push(q),
_ => {}
}
}
}
}
let key = |q: &Vec2| if vertical { q.y } else { q.x };
pts.sort_by(|a, b| key(a).total_cmp(&key(b)));
pts.dedup_by(|a, b| (key(a) - key(b)).abs() < 1e-9);
if pts.len() < 2 {
return Err(bad("qdim", "select objects with at least two distinct points"));
}
if pts.len() > MAX_CHAIN {
return Err(bad("qdim", format!("at most {MAX_CHAIN} distinct points per call")));
}
let rot = if vertical { std::f64::consts::FRAC_PI_2 } else { 0.0 };
// One snap index for all the dimensions, as DIMCONTINUE does: looking up each dimension's
// objects by scanning the drawing made QDIM quadratic (the added dimensions are no snap targets).
let snaps = if assoc_enabled(s) { Some(crate::assoc::SnapIndex::new(s.doc()?, &s.space())) } else { None };
let mut out = Vec::new();
for w in pts.windows(2) {
if let [a, b] = w {
let mut k = dim(s, DimKind::Linear { rotation: rot }, at, *a, *b, Vec2::ZERO, Vec2::ZERO, "");
if let (Some(ix), EntityKind::Dimension(dm)) = (&snaps, &mut k) {
dm.assoc = ix.auto_assoc(&[("p13", dm.p13.xy()), ("p14", dm.p14.xy())]);
}
let h = s.add_entity(k)?;
s.last_dim = Some(h);
out.push(h.hex());
}
}
Ok(json!({ "handles": out }))
}
/// QDIM: its modes and prompts.
#[path = "annotate_qdim.rs"]
mod qdim;
/// A multileader from arrowhead to landing; `landing` false leaves out the landing line (dogleg).
fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option<EntityKind> {
@@ -466,12 +427,13 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option<
let d = s.doc().ok()?;
let cur = d.header.str("CMLEADERSTYLE", "Standard");
let st = d.mleader_styles.iter().find(|m| m.name.eq_ignore_ascii_case(&cur)).or(d.mleader_styles.first()).cloned().unwrap_or_default();
let k = d.header.f64("DIMSCALE", 1.0);
let th = st.text_height * k;
// The style's sizes are the drawn sizes: a multileader style has no scale of its own and
// DIMSCALE (a dimension-style setting) does not apply, as in AutoCAD.
let th = st.text_height;
let dir = if arrow_pts.first().is_some_and(|a| a.x > landing_pt.x) { -1.0 } else { 1.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
let dogleg = if landing { st.dogleg * k } else { 0.0 };
let tpos = *landing_pt + Vec2::new((dogleg + st.landing_gap * k) * dir, 0.0);
let dogleg = if landing { st.dogleg } else { 0.0 };
let tpos = *landing_pt + Vec2::new((dogleg + st.landing_gap) * dir, 0.0);
Some(EntityKind::MLeader(MLeader {
leaders: vec![arrow_pts.iter().map(|p| v3(*p)).collect()],
landing: v3(*landing_pt),
@@ -485,18 +447,25 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option<
style: st.text_style.clone(),
contents: text.replace('\n', "\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}),
style: st.name.clone(),
arrow_size: st.arrow_size * k,
arrow_size: st.arrow_size,
spline: false,
block: None,
}))
}
fn run_mleader(s: &mut Session, p: &Value) -> Result<Value> {
let pts = points_param(p, "points").ok_or_else(|| bad("mleader", "`points` (arrow … landing) is required"))?;
if pts.len() < 2 {
let content = super::mleader_content::json_content(s, p)?;
// Leader type None places the content at the one point given.
if pts.len() < 2 && !(content.leader == crate::LeaderType::None && pts.len() == 1) {
return Err(bad("mleader", "need an arrowhead and a landing point"));
}
let k = mleader_kind(s, &pts, str_param(p, "text").unwrap_or(""), true).ok_or_else(|| bad("mleader", "bad points"))?;
let k = super::mleader_content::apply(s, k, &content)?;
Ok(json!({ "handle": s.add_entity(k)?.hex() }))
}
@@ -525,6 +494,8 @@ fn run_leader(s: &mut Session, p: &Value) -> Result<Value> {
style: "Standard".into(),
contents: t.into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?
.hex(),
);
@@ -662,13 +633,20 @@ fn run_dimtedit(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("dimtedit", "`angle` (degrees) is required"));
}
let d = s.doc_mut()?;
let dimscale = d.header.f64("DIMSCALE", 1.0);
for h in &hs {
let st = match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Dimension(dm)) => d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides),
_ => continue,
};
d.modify_entity(*h, |e| {
let EntityKind::Dimension(dm) = &mut e.kind else { return };
dm.block = None;
if let Some(q) = at {
dm.text_mid = v3(q);
dm.user_text_pos = true;
// DIMTMOVE 0: the dimension line moves with the text.
st.follow_text(dm, dimscale);
}
match mode.as_str() {
"home" => {
@@ -741,6 +719,90 @@ fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "spaced": others.len() }))
}
/// DIMSPACE at the command line: select the base dimension, select the dimensions to space, then
/// the spacing (Enter or Auto takes the DIMDLI-based default).
#[derive(Default)]
struct DimSpaceM {
base: Option<Handle>,
sel: SelectPhase,
spacing_phase: bool,
}
impl DimSpaceM {
fn apply(&self, s: &mut Session, base: Handle, spacing: Option<f64>) -> Result<Step> {
let mut p = serde_json::Map::new();
p.insert("base".into(), json!(base.hex()));
p.insert("handles".into(), json!(self.sel.picked.iter().map(|h| h.hex()).collect::<Vec<_>>()));
if let Some(v) = spacing {
p.insert("spacing".into(), json!(v));
}
let r = run_dimspace(s, &Value::Object(p))?;
s.set_selection(Vec::new());
s.echo(format!("{} dimension(s) spaced.", r.get("spaced").and_then(Value::as_u64).unwrap_or(0)));
Ok(Step::Done)
}
}
impl Interactive for DimSpaceM {
fn name(&self) -> &'static str {
"DIMSPACE"
}
fn begin(&mut self, _s: &mut Session) -> Result<Step> {
self.sel = SelectPhase::single();
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
if self.spacing_phase {
return Prompt::new("Enter value", Accept::NUMBER).kw(&["Auto"]).default("Auto");
}
if self.base.is_none() {
return Prompt::new("Select base dimension", Accept::SELECT);
}
Prompt::new("Select dimensions to space", Accept::SELECT)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if self.spacing_phase {
let Some(base) = self.base else { return Ok(Step::Cancel) };
return match i {
Input::Enter => self.apply(s, base, None),
Input::Keyword(k) | Input::Text(k) if k.trim().eq_ignore_ascii_case("a") || k.trim().eq_ignore_ascii_case("auto") => {
self.apply(s, base, None)
}
Input::Text(t) => match super::machines::number(&t).filter(|v| v.is_finite() && *v >= 0.0) {
Some(v) => self.apply(s, base, Some(v)),
None => {
s.echo("Requires a non-negative number or Auto.");
Ok(Step::Continue)
}
},
_ => Ok(Step::Continue),
};
}
match self.sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => {
if self.base.is_none() {
match hs.first().copied().filter(|h| !dims_of(s, &[*h]).is_empty()) {
Some(b) => {
self.base = Some(b);
self.sel = SelectPhase::default();
}
None => {
s.echo("Select a dimension.");
self.sel = SelectPhase::single();
}
}
} else {
self.sel.picked = hs;
self.spacing_phase = true;
}
Ok(Step::Continue)
}
}
}
}
/// DIMOVERRIDE at the command line: variable, value (repeat), Enter, then select dimensions.
struct OverrideM {
vars: serde_json::Map<String, Value>,
@@ -1042,7 +1104,7 @@ impl RadialM {
} else {
dim(s, DimKind::Radius, c, Vec2::ZERO, Vec2::ZERO, pt, Vec2::ZERO, "")
});
text_inside(k, c, r, at)
text_at(k, at)
}
}
@@ -1465,6 +1527,8 @@ enum LeaderOpt {
MaxPoints,
FirstAngle,
SecondAngle,
BlockName,
BlockAttach,
}
/// Upper bound for MLEADER Maxpoints.
@@ -1484,6 +1548,11 @@ struct MLeaderM {
angles: [f64; 2],
landing: bool,
content: bool,
leader_type: crate::LeaderType,
/// Block content: the block (`block_name`) instead of text.
block: bool,
block_name: String,
block_center: bool,
}
impl MLeaderM {
@@ -1501,12 +1570,37 @@ impl MLeaderM {
angles: o.angles,
landing: o.landing,
content: o.content,
leader_type: o.leader_type,
// Block content needs a block that still exists.
block: o.block && s.doc().is_ok_and(|d| d.block(&s.last_used.mleader_block).is_some()),
block_name: s.last_used.mleader_block.clone(),
block_center: o.block_center,
}
}
/// Keep the order and Options for the next MLEADER.
fn remember(&self, s: &mut Session) {
s.last_used.mleader =
MLeaderOptions { order: self.order, max_points: self.max_points, angles: self.angles, landing: self.landing, content: self.content };
s.last_used.mleader = MLeaderOptions {
order: self.order,
max_points: self.max_points,
angles: self.angles,
landing: self.landing,
content: self.content,
leader_type: self.leader_type,
block: self.block,
block_center: self.block_center,
};
s.last_used.mleader_block = self.block_name.clone();
}
/// The leader type and block content for `mleader_content::apply`.
fn content_spec(&self) -> super::mleader_content::Content {
super::mleader_content::Content {
leader: self.leader_type,
block: (self.content && self.block).then(|| (self.block_name.clone(), self.block_center)),
}
}
/// Leader type None: the one point placed is the content location.
fn no_leader(&self) -> bool {
self.leader_type == crate::LeaderType::None
}
/// The leader from arrowhead to landing, with `extra` placed next.
fn leader(&self, extra: Option<Vec2>) -> Vec<Vec2> {
@@ -1529,11 +1623,19 @@ impl MLeaderM {
}
/// The text is asked now: right after the content location (Content first) or after the leader.
fn wants_text(&self) -> bool {
self.content && self.text.is_none() && (self.leader_done || (self.order == LeaderOrder::Content && self.pts.len() == 1))
self.content
&& !self.block
&& self.text.is_none()
&& (self.leader_done || (self.order == LeaderOrder::Content && self.pts.len() == 1 && !self.no_leader()))
}
fn finish(&self, s: &mut Session) -> Result<Step> {
if self.no_leader() && !self.content {
s.echo("A multileader needs a leader line or content; nothing was drawn.");
return Ok(Step::Cancel);
}
let text = self.text.clone().unwrap_or_default();
let k = mleader_kind(s, &self.leader(None), &text, self.landing).ok_or_else(|| EngineError::Other("bad leader".into()))?;
let k = super::mleader_content::apply(s, k, &self.content_spec())?;
s.add_entity(k)?;
Ok(Step::Done)
}
@@ -1549,6 +1651,10 @@ impl MLeaderM {
LeaderOpt::MaxPoints => Prompt::new("Enter the maximum points for leader line", Accept::NUMBER),
LeaderOpt::FirstAngle => Prompt::new("Enter first angle constraint", Accept::NUMBER),
LeaderOpt::SecondAngle => Prompt::new("Enter second angle constraint", Accept::NUMBER),
LeaderOpt::BlockName => Prompt::new("Enter block name", kw),
LeaderOpt::BlockAttach => {
Prompt::new("Specify block attachment", kw).kw(&["Center extents", "Insertion point"]).default("Center extents")
}
}
}
/// One answer at the Options prompts; Enter keeps the current value.
@@ -1566,11 +1672,11 @@ impl MLeaderM {
},
(Menu, Input::Enter) => None,
(LeaderType, Input::Keyword(k)) => {
match k.as_str() {
"sPline" => s.echo("Spline leaders are not available yet; the leader stays straight."),
"None" => s.echo("Multileaders without a leader line are not available yet."),
_ => {}
}
self.leader_type = match k.as_str() {
"sPline" => crate::LeaderType::Spline,
"None" => crate::LeaderType::None,
_ => crate::LeaderType::Straight,
};
Some(Menu)
}
(Landing, Input::Keyword(k)) => {
@@ -1578,11 +1684,34 @@ impl MLeaderM {
Some(Menu)
}
(ContentType, Input::Keyword(k)) => {
match k.as_str() {
"Block" => s.echo("Block content is not available yet; the content stays multiline text."),
"None" => self.content = false,
_ => self.content = true,
self.content = k != "None";
self.block = false;
// Block content asks which block, then how it attaches.
if k == "Block" { Some(BlockName) } else { Some(Menu) }
}
(BlockName, Input::Text(t)) => match super::mleader_content::block_name(s, &t) {
Ok(n) => {
self.block_name = n;
self.block = true;
Some(BlockAttach)
}
Err(e) => {
s.echo(e.to_string());
Some(BlockName)
}
},
(BlockName, Input::Enter) => {
// Enter keeps the block chosen before, if there is one.
if super::mleader_content::block_name(s, &self.block_name).is_ok() {
self.block = true;
Some(BlockAttach)
} else {
s.echo("Requires the name of a block defined in the drawing.");
Some(BlockName)
}
}
(BlockAttach, Input::Keyword(k)) => {
self.block_center = k == "Center extents";
Some(Menu)
}
(MaxPoints, Input::Text(t)) => match t.trim().parse::<usize>() {
@@ -1605,7 +1734,7 @@ impl MLeaderM {
Some(o)
}
},
(Menu | LeaderType | Landing | ContentType, Input::Text(_)) => {
(Menu | LeaderType | Landing | ContentType | BlockAttach, Input::Text(_)) => {
s.echo("Invalid option keyword.");
Some(o)
}
@@ -1626,6 +1755,10 @@ impl Interactive for MLeaderM {
if self.wants_text() {
return Prompt::new("Enter leader text", Accept::TEXT);
}
if self.no_leader() && self.pts.is_empty() {
let what = if self.content && self.block { "Specify location of the block" } else { "Specify location of the text" };
return Prompt::new(what, Accept::POINT).kw(&["Options"]).default("Options");
}
let last = self.pts.len() + 1 >= self.max_points;
match (self.pts.last(), self.order) {
(None, LeaderOrder::Arrowhead) => Prompt::new("Specify leader arrowhead location", Accept::POINT)
@@ -1656,7 +1789,7 @@ impl Interactive for MLeaderM {
Input::Point(p) => {
let p = self.constrained(p);
self.pts.push(p);
if self.pts.len() >= self.max_points {
if self.pts.len() >= self.max_points || self.no_leader() {
self.leader_done = true;
}
}
@@ -1682,13 +1815,19 @@ impl Interactive for MLeaderM {
return Vec::new();
}
let text = self.text.as_deref().unwrap_or("");
mleader_kind(s, &self.leader(Some(self.constrained(c))), text, self.landing).into_iter().collect()
mleader_kind(s, &self.leader(Some(self.constrained(c))), text, self.landing)
.and_then(|k| super::mleader_content::apply(s, k, &self.content_spec()).ok())
.into_iter()
.collect()
}
}
#[path = "annotate_tedit.rs"]
mod tedit;
#[path = "annotate_dimedit.rs"]
mod dimedit;
#[cfg(test)]
#[path = "annotate_tests.rs"]
mod tests;
+778
View File
@@ -0,0 +1,778 @@
//! Dimension edits: DIMEDIT (Home/New/Rotate/Oblique), DIMJOGGED, DIMJOGLINE, DIMBREAK and
//! DIMINSPECT. Each has a JSON form; the prompt sequences run the same JSON form.
use cadcraft_doc::{DimBreak, DimKind, Dimension, EntityKind, Handle, Inspection, JoggedRadius, Prim};
use cadcraft_geom::{Segment, Vec2};
use serde_json::{Value, json};
use super::machines::{SelOutcome, SelectPhase};
use super::*;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// Most objects DIMBREAK Auto looks at, and most breaks it adds to one dimension.
const MAX_BREAK_OBJECTS: usize = 20_000;
const MAX_AUTO_BREAKS: usize = 1000;
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("dimedit", "Dimension Edit", run_dimedit)
.alias(&["ded", "dimed"])
.params("{handles?, mode?: home|new|rotate|oblique (default home), text? (new: \"\" or \"<>\" = the measurement), angle?: degrees (rotate: text angle; oblique: extension line angle, absent = none)}")
.interactive(|_| Ok(Box::new(DimEditM::new(None)))),
CommandSpec::new("dimedit.oblique", "Oblique", |s, p| run_dimedit(s, &with_mode(p, "oblique")))
.menu(&["Dimension", "Oblique"])
.params("{handles?, angle?: degrees}")
.interactive(|_| Ok(Box::new(DimEditM::new(Some(Mode::Oblique))))),
CommandSpec::new("dimjogged", "Jogged", run_jogged)
.menu(&["Dimension", "Jogged"])
.alias(&["djo", "jog"])
.params("{handle (arc or circle), centerOverride: [x,y], at: [x,y] (dimension line location), jog?: [x,y], text?}")
.interactive(|_| Ok(Box::new(JoggedM::default()))),
CommandSpec::new("dimjogline", "Jogged Linear", run_jogline)
.menu(&["Dimension", "Jogged Linear"])
.alias(&["djl"])
.params("{handle (linear or aligned dimension), at?: [x,y] (jog location; default between the text and the first extension line), remove?: bool}")
.interactive(|_| Ok(Box::new(JogLineM::default()))),
CommandSpec::new("dimbreak", "Dimension Break", run_dimbreak)
.menu(&["Dimension", "Dimension Break"])
.params("{handles?, mode?: auto|manual|remove (default auto), objects?: [hex] (auto: the objects that break; default all crossing objects), first?/second?: [x,y] (manual), size?: number (default 0.125 × DIMSCALE)}")
.interactive(|_| Ok(Box::new(DimBreakM::default()))),
CommandSpec::new("diminspect", "Inspection", run_diminspect)
.menu(&["Dimension", "Inspection"])
.params("{handles?, shape?: round|angular|none (default round), label?: string, rate?: string (default \"100%\"), remove?: bool}")
.interactive(|_| Ok(Box::new(InspectM::default()))),
]
}
fn with_mode(p: &Value, mode: &str) -> Value {
let mut p = p.clone();
if let Some(o) = p.as_object_mut() {
o.insert("mode".into(), json!(mode));
}
p
}
fn handles_json(hs: &[Handle]) -> Value {
json!(hs.iter().map(|h| h.hex()).collect::<Vec<_>>())
}
/// Change each dimension of `hs` with `f` (its block regenerated); returns how many changed.
fn edit_dims(s: &mut Session, hs: &[Handle], f: &dyn Fn(&mut Dimension) -> bool) -> Result<usize> {
let d = s.doc_mut()?;
let mut n = 0;
for h in hs {
let mut changed = false;
d.modify_entity(*h, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind
&& f(dm)
{
dm.block = None;
changed = true;
}
})?;
n += usize::from(changed);
}
Ok(n)
}
fn is_linear(dm: &Dimension) -> bool {
matches!(dm.kind, DimKind::Linear { .. } | DimKind::Aligned)
}
// ---------------- DIMEDIT ----------------
#[derive(Clone, Copy, Debug, PartialEq)]
enum Mode {
Home,
New,
Rotate,
Oblique,
}
fn run_dimedit(s: &mut Session, p: &Value) -> Result<Value> {
let hs = dims_of(s, &targets(s, p)?);
if hs.is_empty() {
return Err(bad("dimedit", "select dimensions"));
}
let mode = str_param(p, "mode").unwrap_or("home").to_ascii_lowercase();
let angle = match p.get("angle") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad("dimedit", "`angle` must be a number (degrees)"))?.to_radians()),
};
let n = match mode.as_str() {
"home" => edit_dims(s, &hs, &|dm| {
dm.user_text_pos = false;
dm.text_rotation = 0.0;
dm.overrides.remove("textJust");
true
})?,
"new" => {
let t = str_param(p, "text").unwrap_or("").to_string();
// "<>" alone is the measurement, which is what no override text means.
let t = if t.trim() == "<>" { String::new() } else { t };
edit_dims(s, &hs, &|dm| {
dm.text = t.clone();
true
})?
}
"rotate" => {
let a = angle.ok_or_else(|| bad("dimedit", "`angle` (degrees) is required"))?;
edit_dims(s, &hs, &|dm| {
dm.text_rotation = cadcraft_geom::norm_angle(a);
true
})?
}
"oblique" => edit_dims(s, &hs, &|dm| {
if !is_linear(dm) {
return false;
}
dm.marks.oblique = angle.map(cadcraft_geom::norm_angle);
true
})?,
other => return Err(bad("dimedit", format!("unknown mode `{other}` (home, new, rotate, oblique)"))),
};
Ok(json!({ "changed": n }))
}
/// DIMEDIT at the command line: the kind of edit, then (New) the text or (Rotate) the angle,
/// the dimensions, and (Oblique) the extension line angle.
struct DimEditM {
mode: Option<Mode>,
text: Option<String>,
angle: Option<f64>,
selecting: Option<SelectPhase>,
picked: Vec<Handle>,
}
impl DimEditM {
fn new(mode: Option<Mode>) -> Self {
DimEditM { mode, text: None, angle: None, selecting: None, picked: Vec::new() }
}
/// "Select objects", or the pickfirst selection at once.
fn select(&mut self, s: &mut Session) -> Result<Step> {
let ph = SelectPhase::begin(s);
if ph.done {
return self.after_selection(s, ph.picked);
}
self.selecting = Some(ph);
Ok(Step::Continue)
}
fn run(&self, s: &mut Session, hs: &[Handle], angle: Option<f64>) -> Result<Step> {
let (mode, extra) = match self.mode {
Some(Mode::New) => ("new", json!({ "text": self.text.clone().unwrap_or_default() })),
Some(Mode::Rotate) => ("rotate", json!({ "angle": angle.unwrap_or(0.0).to_degrees() })),
Some(Mode::Oblique) => ("oblique", json!({ "angle": angle.map(f64::to_degrees) })),
_ => ("home", json!({})),
};
let mut p = extra;
if let Some(o) = p.as_object_mut() {
o.insert("handles".into(), handles_json(hs));
o.insert("mode".into(), json!(mode));
}
let r = run_dimedit(s, &p)?;
s.echo(format!("{} dimension(s) changed.", r.get("changed").and_then(Value::as_u64).unwrap_or(0)));
s.set_selection(Vec::new());
Ok(Step::Done)
}
fn after_selection(&mut self, s: &mut Session, hs: Vec<Handle>) -> Result<Step> {
let hs = dims_of(s, &hs);
if hs.is_empty() {
s.echo("No dimensions selected.");
return Ok(Step::Done);
}
if self.mode == Some(Mode::Oblique) {
self.picked = hs;
return Ok(Step::Continue);
}
self.run(s, &hs, self.angle)
}
}
impl Interactive for DimEditM {
fn name(&self) -> &'static str {
"DIMEDIT"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
// Dimension ▸ Oblique asks for the dimensions first.
if self.mode == Some(Mode::Oblique) {
return self.select(s);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
if let Some(sel) = &self.selecting {
return sel.prompt();
}
match self.mode {
None => Prompt::new("Enter type of dimension editing", Accept::TEXT).kw(&["Home", "New", "Rotate", "Oblique"]).default("Home"),
Some(Mode::New) => Prompt::new("Enter new dimension text", Accept::TEXT).default("<>"),
Some(Mode::Rotate) => Prompt::new("Specify angle for dimension text", Accept::NUMBER),
_ => Prompt::new("Enter obliquing angle (press ENTER for none)", Accept::NUMBER),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some(sel) = &mut self.selecting {
return match sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => {
self.selecting = None;
self.after_selection(s, hs)
}
};
}
match (self.mode, i) {
(None, Input::Keyword(k)) => {
self.mode = match k.as_str() {
"New" => Some(Mode::New),
"Rotate" => Some(Mode::Rotate),
"Oblique" => Some(Mode::Oblique),
_ => Some(Mode::Home),
};
if matches!(self.mode, Some(Mode::Home | Mode::Oblique)) {
return self.select(s);
}
}
(None, Input::Enter) => {
self.mode = Some(Mode::Home);
return self.select(s);
}
(None, Input::Text(_)) => s.echo("Invalid option keyword."),
(Some(Mode::New), Input::Text(t)) if self.text.is_none() => {
self.text = Some(t);
return self.select(s);
}
(Some(Mode::New), Input::Enter) if self.text.is_none() => {
self.text = Some(String::new());
return self.select(s);
}
(Some(Mode::Rotate), Input::Text(t)) if self.angle.is_none() => match s.angle_settings().direction(&t) {
Some(a) => {
self.angle = Some(a);
return self.select(s);
}
None => s.echo("Requires a valid angle."),
},
(Some(Mode::Oblique), Input::Text(t)) if !self.picked.is_empty() => match s.angle_settings().direction(&t) {
Some(a) => return self.run(s, &self.picked.clone(), Some(a)),
None => s.echo("Requires a valid angle."),
},
(Some(Mode::Oblique), Input::Enter) if !self.picked.is_empty() => return self.run(s, &self.picked.clone(), None),
(_, Input::Cancel) => return Ok(Step::Cancel),
(Some(_), Input::Enter) => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
fn preview(&self, _s: &Session, _c: Vec2) -> Vec<EntityKind> {
Vec::new()
}
}
// ---------------- DIMJOGGED ----------------
/// A jogged radius dimension of the circle (`c`, `r`): the arrow where the direction of `at`
/// meets it, the line from `center` (the override) with a jog at `jog` (default halfway).
fn jogged_kind(s: &Session, c: Vec2, r: f64, center: Vec2, at: Vec2, jog: Option<Vec2>, text: &str) -> Option<EntityKind> {
let dir = (at - c).normalized();
if dir == Vec2::ZERO || !dir.is_finite() || r.is_nan() || r <= 0.0 {
return None;
}
let tip = c + dir * r;
let jog = jog.unwrap_or_else(|| center.mid(tip));
let mut k = dim(s, DimKind::Radius, c, Vec2::ZERO, Vec2::ZERO, tip, Vec2::ZERO, text);
if let EntityKind::Dimension(dm) = &mut k {
dm.marks.jogged = Some(JoggedRadius { center: v3(center), jog: v3(jog) });
if at.dist(c) > r + 1e-9 {
dm.text_mid = v3(at);
dm.user_text_pos = true;
}
}
Some(k)
}
fn run_jogged(s: &mut Session, p: &Value) -> Result<Value> {
let h = targets(s, p)?.first().copied().ok_or_else(|| bad("dimjogged", "`handle` of an arc or circle is required"))?;
let (c, r) = circle_of(s, h).ok_or_else(|| bad("dimjogged", "object is not a circle or arc"))?;
let center = point_req("dimjogged", p, "centerOverride")?;
let at = point_req("dimjogged", p, "at")?;
let k = jogged_kind(s, c, r, center, at, point_param(p, "jog"), str_param(p, "text").unwrap_or(""))
.ok_or_else(|| bad("dimjogged", "`at` must differ from the centre"))?;
Ok(json!({ "handle": add_dim(s, k)?.hex() }))
}
#[derive(Default)]
struct JoggedM {
circle: Option<(Vec2, f64)>,
center: Option<Vec2>,
at: Option<Vec2>,
text: DimText,
}
impl Interactive for JoggedM {
fn name(&self) -> &'static str {
"DIMJOGGED"
}
fn prompt(&self, _s: &Session) -> Prompt {
if let Some(p) = self.text.prompt() {
return p;
}
match (self.circle, self.center, self.at) {
(None, ..) => Prompt::new("Select arc or circle", Accept::POINT),
(Some((c, _)), None, _) => Prompt::new("Specify center location override", Accept::POINT).base(c),
(Some(_), Some(o), None) => Prompt::new("Specify dimension line location", Accept::POINT).kw(&["Mtext", "Text", "Angle"]).base(o),
(Some(_), Some(o), Some(_)) => Prompt::new("Specify jog location", Accept::POINT).base(o),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if self.text.answer(s, &i) {
return Ok(Step::Continue);
}
match (self.circle, self.center, self.at, i) {
(None, _, _, Input::Point(p)) => match pick_at(s, p).and_then(|h| circle_of(s, h)) {
Some(t) => self.circle = Some(t),
None => s.echo("Object selected is not a circle or arc."),
},
(Some(_), None, _, Input::Point(p)) => self.center = Some(p),
(Some(_), Some(_), None, Input::Keyword(k)) => {
self.text.keyword(&k);
}
(Some(_), Some(_), None, Input::Point(p)) => self.at = Some(p),
(Some((c, r)), Some(o), Some(at), Input::Point(j)) => {
if let Some(k) = jogged_kind(s, c, r, o, at, Some(j), "") {
add_dim(s, self.text.apply(k))?;
}
return Ok(Step::Done);
}
(_, _, _, Input::Enter | Input::Cancel) => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
fn preview(&self, s: &Session, p: Vec2) -> Vec<EntityKind> {
let Some((c, r)) = self.circle else { return Vec::new() };
let (o, at, jog) = match (self.center, self.at) {
(Some(o), None) => (o, p, None),
(Some(o), Some(at)) => (o, at, Some(p)),
_ => return Vec::new(),
};
jogged_kind(s, c, r, o, at, jog, "").map(|k| vec![self.text.apply(k)]).unwrap_or_default()
}
}
// ---------------- DIMJOGLINE ----------------
/// Where a dimension line meets the first extension line, and the dimension line direction.
fn first_foot(dm: &Dimension) -> Option<(Vec2, Vec2)> {
let dir = match dm.kind {
DimKind::Linear { rotation } => Vec2::from_angle(rotation),
DimKind::Aligned => (dm.p14.xy() - dm.p13.xy()).normalized(),
_ => return None,
};
if dir == Vec2::ZERO || !dir.is_finite() {
return None;
}
let on = dm.defpt.xy();
Some((on + dir * (dm.p13.xy() - on).dot(dir), dir))
}
fn run_jogline(s: &mut Session, p: &Value) -> Result<Value> {
let hs = dims_of(s, &targets(s, p)?);
let h = *hs.first().ok_or_else(|| bad("dimjogline", "`handle` of a linear or aligned dimension is required"))?;
let d = s.doc()?;
let Some(EntityKind::Dimension(dm)) = d.entity(h).map(|e| &e.kind) else { return Err(bad("dimjogline", "not a dimension")) };
let (f1, dir) = first_foot(dm).ok_or_else(|| bad("dimjogline", "only linear and aligned dimensions take a jog"))?;
let remove = bool_or(p, "remove", false);
let at = match point_param(p, "at") {
Some(at) => at,
None => {
// Halfway between the text and the first extension line.
let t = cadcraft_render::dimension_in(d, dm).text_pos;
f1.mid(f1 + dir * (t - f1).dot(dir))
}
};
edit_dims(s, &[h], &|dm| {
dm.marks.jog_line = if remove { None } else { Some(v3(at)) };
true
})?;
Ok(json!({ "handle": h.hex() }))
}
#[derive(Default)]
struct JogLineM {
dim: Option<Handle>,
removing: bool,
}
impl Interactive for JogLineM {
fn name(&self) -> &'static str {
"DIMJOGLINE"
}
fn prompt(&self, _s: &Session) -> Prompt {
match (self.dim, self.removing) {
(None, false) => Prompt::new("Select dimension to add jog", Accept::SELECT).kw(&["Remove"]),
(None, true) => Prompt::new("Select jog to remove", Accept::SELECT),
(Some(_), _) => Prompt::new("Specify jog location (or press ENTER)", Accept::POINT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (self.dim, i) {
(None, Input::Keyword(k)) if k == "Remove" => self.removing = true,
(None, Input::Pick(hs)) => {
let lin = |s: &Session, h: Handle| {
s.doc().ok().and_then(|d| d.entity(h)).is_some_and(|e| matches!(&e.kind, EntityKind::Dimension(dm) if is_linear(dm)))
};
match dims_of(s, &hs).into_iter().find(|h| lin(s, *h)) {
Some(h) if self.removing => {
run_jogline(s, &json!({ "handle": h.hex(), "remove": true }))?;
return Ok(Step::Done);
}
Some(h) => self.dim = Some(h),
None if hs.is_empty() => {}
None => s.echo("Select a linear or aligned dimension."),
}
}
(Some(h), Input::Point(at)) => {
run_jogline(s, &json!({ "handle": h.hex(), "at": [at.x, at.y] }))?;
return Ok(Step::Done);
}
(Some(h), Input::Enter) => {
run_jogline(s, &json!({ "handle": h.hex() }))?;
return Ok(Step::Done);
}
(_, Input::Enter | Input::Cancel) => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
fn preview(&self, _s: &Session, _c: Vec2) -> Vec<EntityKind> {
Vec::new()
}
}
// ---------------- DIMBREAK ----------------
/// Where the dimension's drawn lines cross the objects: (point, direction of the line there).
fn crossings(dm_lines: &[Vec<Vec2>], prims: &[Prim]) -> Vec<Vec2> {
let mut out = Vec::new();
for l in dm_lines {
for w in l.windows(2) {
let seg = Segment::Line(cadcraft_geom::Line::new(w[0], w[1]));
for p in prims {
let pts = match p {
Prim::Seg(o) => cadcraft_geom::intersect_segments(&seg, o),
Prim::Circle(c) => cadcraft_geom::line_circle(&cadcraft_geom::Line::new(w[0], w[1]), c)
.into_iter()
.filter(|(_, t)| (-1e-9..=1.0 + 1e-9).contains(t))
.map(|(q, _)| q)
.collect(),
Prim::Infinite { base, dir, ray } => cadcraft_geom::line_line_infinite(w[0], w[1], *base, *base + *dir)
.filter(|(_, t, u)| (-1e-9..=1.0 + 1e-9).contains(t) && (!ray || *u >= -1e-9))
.map(|(q, _, _)| vec![q])
.unwrap_or_default(),
_ => Vec::new(),
};
for q in pts {
if out.len() >= MAX_AUTO_BREAKS {
return out;
}
if !out.iter().any(|o: &Vec2| o.dist(q) < 1e-9) {
out.push(q);
}
}
}
}
}
out
}
fn run_dimbreak(s: &mut Session, p: &Value) -> Result<Value> {
let hs = dims_of(s, &targets(s, p)?);
if hs.is_empty() {
return Err(bad("dimbreak", "select dimensions"));
}
let mode = str_param(p, "mode").unwrap_or("auto").to_ascii_lowercase();
let d = s.doc()?;
let size = match size_param("dimbreak", p, "size", false)? {
Some(x) => x,
None => 0.125 * Some(d.header.f64("DIMSCALE", 1.0)).filter(|k| *k > 0.0 && *k < 1e12).unwrap_or(1.0),
};
match mode.as_str() {
"remove" => {
let n = edit_dims(s, &hs, &|dm| {
let had = !dm.marks.breaks.is_empty();
dm.marks.breaks.clear();
had
})?;
Ok(json!({ "changed": n }))
}
"manual" => {
let (a, b) = (point_req("dimbreak", p, "first")?, point_req("dimbreak", p, "second")?);
if a.near(b, 1e-12) {
return Err(bad("dimbreak", "`first` and `second` must differ"));
}
let br = DimBreak { at: v3(a.mid(b)), size: a.dist(b), auto: false };
let n = edit_dims(s, &hs[..1], &|dm| {
dm.marks.breaks.push(br.clone());
true
})?;
Ok(json!({ "changed": n }))
}
"auto" => {
// The breaking objects: those given, else every object (not a dimension or text).
let given: Option<Vec<Handle>> = match p.get("objects") {
None | Some(Value::Null) => None,
Some(_) => Some(targets(s, &json!({ "handles": p.get("objects") }))?),
};
let space = s.space();
let store = d.space(&space).ok_or_else(|| bad("dimbreak", "no current space"))?;
let others: Vec<(Handle, Vec<Prim>)> = store
.iter()
.filter(|e| match &given {
Some(g) => g.contains(&e.handle),
None => !matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Text(_) | EntityKind::MText(_)),
})
.take(MAX_BREAK_OBJECTS)
.map(|e| (e.handle, e.kind.prims()))
.collect();
let mut plan = Vec::new();
for h in &hs {
let Some(EntityKind::Dimension(dm)) = d.entity(*h).map(|e| &e.kind) else { continue };
let mut plain = dm.clone();
plain.marks.breaks.clear();
let g = cadcraft_render::dimension_in(d, &plain);
let prims: Vec<Prim> = others.iter().filter(|(o, _)| o != h).flat_map(|(_, p)| p.iter().cloned()).collect();
plan.push((*h, crossings(&g.lines, &prims)));
}
let mut n = 0;
for (h, pts) in plan {
n += edit_dims(s, &[h], &|dm| {
dm.marks.breaks.retain(|b| !b.auto);
dm.marks.breaks.extend(pts.iter().map(|q| DimBreak { at: v3(*q), size, auto: true }));
true
})?;
}
Ok(json!({ "changed": n }))
}
other => Err(bad("dimbreak", format!("unknown mode `{other}` (auto, manual, remove)"))),
}
}
#[derive(Default)]
struct DimBreakM {
dims: Vec<Handle>,
multiple: Option<SelectPhase>,
objects: Vec<Handle>,
manual: Vec<Vec2>,
manual_mode: bool,
}
impl DimBreakM {
fn run(&self, s: &mut Session, mut p: Value) -> Result<Step> {
if let Some(o) = p.as_object_mut() {
o.insert("handles".into(), handles_json(&self.dims));
}
let r = run_dimbreak(s, &p)?;
s.echo(format!("{} dimension(s) changed.", r.get("changed").and_then(Value::as_u64).unwrap_or(0)));
s.set_selection(Vec::new());
Ok(Step::Done)
}
}
impl Interactive for DimBreakM {
fn name(&self) -> &'static str {
"DIMBREAK"
}
fn prompt(&self, _s: &Session) -> Prompt {
if let Some(sel) = &self.multiple {
return sel.prompt();
}
if self.dims.is_empty() {
return Prompt::new("Select dimension to add/remove break", Accept::SELECT).kw(&["Multiple"]);
}
if self.manual_mode {
return Prompt::new(if self.manual.is_empty() { "Specify first break point" } else { "Specify second break point" }, Accept::POINT)
.base_opt(self.manual.first().copied());
}
if self.objects.is_empty() {
let kws: &[&str] = if self.dims.len() == 1 { &["Auto", "Manual", "Remove"] } else { &["Auto", "Remove"] };
Prompt::new("Select object to break dimension", Accept::SELECT).kw(kws).default("Auto")
} else {
Prompt::new("Select object to break dimension", Accept::SELECT)
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some(sel) = &mut self.multiple {
return match sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => {
self.multiple = None;
self.dims = dims_of(s, &hs);
Ok(if self.dims.is_empty() { Step::Done } else { Step::Continue })
}
};
}
if self.dims.is_empty() {
match i {
Input::Keyword(k) if k == "Multiple" => self.multiple = Some(SelectPhase::default()),
Input::Pick(hs) => match dims_of(s, &hs).first() {
Some(h) => self.dims = vec![*h],
None if hs.is_empty() => {}
None => s.echo("Object selected is not a dimension."),
},
Input::Enter | Input::Cancel => return Ok(Step::Cancel),
_ => {}
}
return Ok(Step::Continue);
}
if self.manual_mode {
return match i {
Input::Point(p) if self.manual.is_empty() => {
self.manual.push(p);
Ok(Step::Continue)
}
Input::Point(p) => {
let a = self.manual.first().copied().unwrap_or(p);
self.run(s, json!({ "mode": "manual", "first": [a.x, a.y], "second": [p.x, p.y] }))
}
Input::Enter | Input::Cancel => Ok(Step::Cancel),
_ => Ok(Step::Continue),
};
}
match i {
Input::Keyword(k) if k == "Auto" => return self.run(s, json!({ "mode": "auto" })),
Input::Keyword(k) if k == "Remove" => return self.run(s, json!({ "mode": "remove" })),
Input::Keyword(k) if k == "Manual" => self.manual_mode = true,
Input::Pick(hs) => {
for h in hs {
if !self.dims.contains(&h) && !self.objects.contains(&h) {
self.objects.push(h);
}
}
}
Input::Enter if self.objects.is_empty() => return self.run(s, json!({ "mode": "auto" })),
Input::Enter => return self.run(s, json!({ "mode": "auto", "objects": handles_json(&self.objects) })),
Input::Cancel => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
fn preview(&self, _s: &Session, _c: Vec2) -> Vec<EntityKind> {
Vec::new()
}
}
// ---------------- DIMINSPECT ----------------
fn run_diminspect(s: &mut Session, p: &Value) -> Result<Value> {
let hs = dims_of(s, &targets(s, p)?);
if hs.is_empty() {
return Err(bad("diminspect", "select dimensions"));
}
if bool_or(p, "remove", false) {
let n = edit_dims(s, &hs, &|dm| dm.marks.inspect.take().is_some())?;
return Ok(json!({ "changed": n }));
}
let shape = match str_param(p, "shape").unwrap_or("round").to_ascii_lowercase().as_str() {
"round" => 0,
"angular" => 1,
"none" => 2,
other => return Err(bad("diminspect", format!("unknown shape `{other}` (round, angular, none)"))),
};
let cap = |t: &str| t.chars().take(256).collect::<String>();
let ins = Inspection { shape, label: cap(str_param(p, "label").unwrap_or("")), rate: cap(str_param(p, "rate").unwrap_or("100%")) };
let n = edit_dims(s, &hs, &|dm| {
dm.marks.inspect = Some(ins.clone());
true
})?;
Ok(json!({ "changed": n }))
}
/// DIMINSPECT at the command line: the dimensions, then shape (or Remove), label and rate.
#[derive(Default)]
struct InspectM {
selecting: Option<SelectPhase>,
dims: Vec<Handle>,
shape: Option<&'static str>,
label: Option<String>,
}
impl Interactive for InspectM {
fn name(&self) -> &'static str {
"DIMINSPECT"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let ph = SelectPhase::begin(s);
if ph.done {
self.dims = dims_of(s, &ph.picked);
if self.dims.is_empty() {
return Ok(Step::Done);
}
} else {
self.selecting = Some(ph);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
if let Some(sel) = &self.selecting {
return sel.prompt();
}
match (self.shape, &self.label) {
(None, _) => Prompt::new("Enter inspection shape", Accept::TEXT).kw(&["Round", "Angular", "None", "Remove"]).default("Round"),
(Some(_), None) => Prompt::new("Enter label (press ENTER for none)", Accept::TEXT),
(Some(_), Some(_)) => Prompt::new("Enter inspection rate", Accept::TEXT).default("100%"),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some(sel) = &mut self.selecting {
return match sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => {
self.selecting = None;
self.dims = dims_of(s, &hs);
if self.dims.is_empty() {
s.echo("No dimensions selected.");
return Ok(Step::Done);
}
Ok(Step::Continue)
}
};
}
let handles = handles_json(&self.dims);
match (self.shape, self.label.clone(), i) {
(None, _, Input::Keyword(k)) if k == "Remove" => {
run_diminspect(s, &json!({ "handles": handles, "remove": true }))?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
(None, _, Input::Keyword(k)) => {
self.shape = Some(match k.as_str() {
"Angular" => "angular",
"None" => "none",
_ => "round",
})
}
(None, _, Input::Enter) => self.shape = Some("round"),
(Some(_), None, Input::Text(t)) => self.label = Some(t),
(Some(_), None, Input::Enter) => self.label = Some(String::new()),
(Some(shape), Some(label), Input::Text(t)) => {
run_diminspect(s, &json!({ "handles": handles, "shape": shape, "label": label, "rate": t }))?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
(Some(shape), Some(label), Input::Enter) => {
run_diminspect(s, &json!({ "handles": handles, "shape": shape, "label": label }))?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
(_, _, Input::Cancel) => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
fn preview(&self, _s: &Session, _c: Vec2) -> Vec<EntityKind> {
Vec::new()
}
}
+364
View File
@@ -0,0 +1,364 @@
//! QDIM: quick dimensions of the selected geometry. Continuous, Staggered, Baseline, Ordinate,
//! Radius and Diameter, a datum point for Baseline and Ordinate, and Edit (add or remove
//! dimension points). The prompt sequence runs the JSON form.
use cadcraft_doc::{DimKind, EntityKind, Handle, Prim};
use cadcraft_geom::{Segment, Vec2};
use serde_json::{Value, json};
use super::machines::{SelOutcome, SelectPhase};
use super::*;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(super) const PARAMS: &str = "{handles?, at: [x,y] (dimension line position), mode?: continuous|staggered|baseline|ordinate|radius|diameter (default continuous), vertical?: bool (default: from `at`), datum?: [x,y] (baseline and ordinate; default the first point, or the origin for ordinate), add?: [[x,y]], remove?: [[x,y]] (dimension points; removes those within `tolerance`)}";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Continuous,
Staggered,
Baseline,
Ordinate,
Radius,
Diameter,
}
impl Mode {
fn parse(s: &str) -> Option<Mode> {
Some(match s.trim().to_ascii_lowercase().as_str() {
"continuous" | "c" => Mode::Continuous,
"staggered" | "s" => Mode::Staggered,
"baseline" | "b" => Mode::Baseline,
"ordinate" | "o" => Mode::Ordinate,
"radius" | "r" => Mode::Radius,
"diameter" | "d" => Mode::Diameter,
_ => return None,
})
}
fn name(self) -> &'static str {
match self {
Mode::Continuous => "Continuous",
Mode::Staggered => "Staggered",
Mode::Baseline => "Baseline",
Mode::Ordinate => "Ordinate",
Mode::Radius => "Radius",
Mode::Diameter => "Diameter",
}
}
}
/// The dimension points (segment ends, circle centres, points) and the circles and arcs of the
/// objects.
fn geometry(s: &Session, hs: &[Handle]) -> Result<(Vec<Vec2>, Vec<(Vec2, f64)>)> {
let d = s.doc()?;
let mut pts = Vec::new();
let mut circles = Vec::new();
for h in hs {
let Some(e) = d.entity(*h) else { continue };
for pr in e.kind.prims() {
match pr {
Prim::Seg(seg) => {
pts.extend([seg.start(), seg.end()]);
if let Segment::Arc { arc, .. } = seg {
circles.push((arc.center, arc.radius));
}
}
Prim::Circle(c) => {
pts.push(c.center);
circles.push((c.center, c.radius));
}
Prim::Point(q) => pts.push(q),
_ => {}
}
if pts.len() > MAX_CHAIN * 2 {
return Err(bad("qdim", format!("at most {MAX_CHAIN} distinct points per call")));
}
}
}
Ok((pts, circles))
}
/// The quick dimensions, without adding them. `pts` are the dimension points (unsorted).
fn plan(
s: &Session,
pts: &[Vec2],
circles: &[(Vec2, f64)],
mode: Mode,
at: Vec2,
vertical: Option<bool>,
datum: Option<Vec2>,
) -> Result<Vec<EntityKind>> {
if matches!(mode, Mode::Radius | Mode::Diameter) {
let mut out = Vec::new();
for (c, r) in circles.iter().take(MAX_CHAIN) {
let dir = (at - *c).normalized();
let dir = if dir == Vec2::ZERO || !dir.is_finite() { Vec2::from_angle(std::f64::consts::FRAC_PI_4) } else { dir };
let p = *c + dir * *r;
out.push(if mode == Mode::Diameter {
dim(s, DimKind::Diameter, *c - dir * *r, Vec2::ZERO, Vec2::ZERO, p, Vec2::ZERO, "")
} else {
dim(s, DimKind::Radius, *c, Vec2::ZERO, Vec2::ZERO, p, Vec2::ZERO, "")
});
}
if out.is_empty() {
return Err(bad("qdim", "select circles or arcs for radius or diameter dimensions"));
}
return Ok(out);
}
// Horizontal dimensions measure along x; vertical ones along y. Without a choice: vertical
// when the line position is beside the geometry, as with DIMLINEAR.
let bounds = cadcraft_geom::Bounds2::from_points(pts.iter().copied());
let vertical = vertical.unwrap_or_else(|| {
let beside = at.x < bounds.min.x || at.x > bounds.max.x;
let within = at.y >= bounds.min.y && at.y <= bounds.max.y;
beside && within
});
let key = |q: &Vec2| if vertical { q.y } else { q.x };
let mut pts = pts.to_vec();
pts.sort_by(|a, b| key(a).total_cmp(&key(b)));
pts.dedup_by(|a, b| (key(a) - key(b)).abs() < 1e-9);
if pts.len() > MAX_CHAIN {
return Err(bad("qdim", format!("at most {MAX_CHAIN} distinct points per call")));
}
if mode == Mode::Ordinate {
if pts.is_empty() {
return Err(bad("qdim", "select objects with points to dimension"));
}
let origin = datum.unwrap_or(Vec2::ZERO);
// X datum (horizontal): leaders run to the line position's y; Y datum: to its x.
return Ok(pts
.iter()
.map(|p| {
let end = if vertical { Vec2::new(at.x, p.y) } else { Vec2::new(p.x, at.y) };
dim(s, DimKind::Ordinate { x_type: !vertical }, origin, *p, end, Vec2::ZERO, Vec2::ZERO, "")
})
.collect());
}
if pts.len() < 2 {
return Err(bad("qdim", "select objects with at least two distinct points"));
}
let rot = if vertical { std::f64::consts::FRAC_PI_2 } else { 0.0 };
let d = s.doc()?;
let st = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default().with_overrides(&d.dim_overrides());
let step = st.baseline_spacing * st.effective_scale(d.header.f64("DIMSCALE", 1.0));
let step = if step.is_finite() && step > 0.0 { step } else { 0.38 };
// Away from the geometry: stacked dimensions go further out from the line position.
let mid = bounds.center();
let out_dir =
if vertical { Vec2::new(if at.x >= mid.x { 1.0 } else { -1.0 }, 0.0) } else { Vec2::new(0.0, if at.y >= mid.y { 1.0 } else { -1.0 }) };
let lin =
|a: Vec2, b: Vec2, k: usize| dim(s, DimKind::Linear { rotation: rot }, at + out_dir * (step * k as f64), a, b, Vec2::ZERO, Vec2::ZERO, "");
Ok(match mode {
Mode::Baseline => {
// From the datum (the point nearest it, by default the first) to every other point.
let base = match datum {
Some(dp) => pts.iter().copied().min_by(|a, b| a.dist(dp).total_cmp(&b.dist(dp))).unwrap_or(dp),
None => pts.first().copied().unwrap_or_default(),
};
let mut others: Vec<Vec2> = pts.iter().copied().filter(|p| (key(p) - key(&base)).abs() > 1e-9).collect();
others.sort_by(|a, b| (key(a) - key(&base)).abs().total_cmp(&(key(b) - key(&base)).abs()));
others.iter().enumerate().map(|(k, p)| lin(base, *p, k)).collect()
}
Mode::Staggered => {
// Symmetric pairs nested from the middle out; the innermost at the line position.
let n = pts.len();
let pairs = n / 2;
(0..pairs).rev().enumerate().filter_map(|(k, i)| Some(lin(*pts.get(i)?, *pts.get(n - 1 - i)?, k))).collect()
}
_ => pts.windows(2).filter_map(|w| Some(lin(*w.first()?, *w.get(1)?, 0))).collect(),
})
}
/// The nearest point of `pts` to `q` within `tol`, by index.
fn nearest(pts: &[Vec2], q: Vec2, tol: f64) -> Option<usize> {
pts.iter().enumerate().filter(|(_, p)| p.dist(q) <= tol).min_by(|a, b| a.1.dist(q).total_cmp(&b.1.dist(q))).map(|(i, _)| i)
}
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.len() > MAX_CHAIN {
return Err(bad("qdim", format!("at most {MAX_CHAIN} objects per call")));
}
let at = point_req("qdim", p, "at")?;
let mode = match str_param(p, "mode") {
None => Mode::Continuous,
Some(m) => {
Mode::parse(m).ok_or_else(|| bad("qdim", format!("unknown mode `{m}` (continuous, staggered, baseline, ordinate, radius, diameter)")))?
}
};
let vertical = p.get("vertical").and_then(Value::as_bool);
let datum = point_param(p, "datum");
let (mut pts, circles) = geometry(s, &hs)?;
// Edit: points to add and to remove (the nearest within a small distance).
for q in points_param(p, "add").unwrap_or_default().into_iter().take(MAX_CHAIN) {
pts.push(q);
}
let tol = p.get("tolerance").and_then(Value::as_f64).filter(|t| t.is_finite() && *t >= 0.0).unwrap_or(1e-6 * (1.0 + at.len()));
for q in points_param(p, "remove").unwrap_or_default().into_iter().take(MAX_CHAIN) {
while let Some(i) = nearest(&pts, q, tol) {
pts.swap_remove(i);
}
}
let kinds = plan(s, &pts, &circles, mode, at, vertical, datum)?;
// One snap index for all the dimensions, as DIMCONTINUE does: looking up each dimension's
// objects by scanning the drawing made QDIM quadratic (the added dimensions are no snap targets).
let snaps = if assoc_enabled(s) { Some(crate::assoc::SnapIndex::new(s.doc()?, &s.space())) } else { None };
let mut out = Vec::new();
for mut k in kinds {
if let (Some(ix), EntityKind::Dimension(dm)) = (&snaps, &mut k) {
dm.assoc = match dm.kind {
DimKind::Radius | DimKind::Diameter => ix.auto_assoc(&[("p15", dm.p15.xy())]),
DimKind::Ordinate { .. } => ix.auto_assoc(&[("p13", dm.p13.xy())]),
_ => ix.auto_assoc(&[("p13", dm.p13.xy()), ("p14", dm.p14.xy())]),
};
}
let h = s.add_entity(k)?;
s.last_dim = Some(h);
out.push(h.hex());
}
Ok(json!({ "handles": out }))
}
/// What the QDIM prompt is asking.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Ask {
#[default]
Position,
Datum,
Remove,
Add,
Settings,
}
/// QDIM at the command line: "Select geometry to dimension", then the dimension line position
/// or a mode, datumPoint, Edit (Remove/Add points) or seTtings.
pub(super) struct QDimM {
sel: SelectPhase,
objs: Vec<Handle>,
mode: Mode,
datum: Option<Vec2>,
add: Vec<Vec2>,
remove: Vec<Vec2>,
/// How near a picked point must be to the dimension point it removes (the pick box).
tol: f64,
ask: Ask,
}
impl QDimM {
pub(super) fn new() -> Self {
QDimM {
sel: SelectPhase::default(),
objs: Vec::new(),
mode: Mode::Continuous,
datum: None,
add: Vec::new(),
remove: Vec::new(),
tol: 1e-6,
ask: Ask::Position,
}
}
fn params(&self, at: Vec2) -> Value {
let pts = |v: &[Vec2]| v.iter().map(|q| json!([q.x, q.y])).collect::<Vec<_>>();
let mut p = json!({
"handles": self.objs.iter().map(|h| h.hex()).collect::<Vec<_>>(),
"at": [at.x, at.y],
"mode": self.mode.name().to_ascii_lowercase(),
"add": pts(&self.add),
"remove": pts(&self.remove),
"tolerance": self.tol,
});
if let (Some(dp), Some(o)) = (self.datum, p.as_object_mut()) {
o.insert("datum".into(), json!([dp.x, dp.y]));
}
p
}
}
impl Interactive for QDimM {
fn name(&self) -> &'static str {
"QDIM"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.sel = SelectPhase::begin(s);
if self.sel.done {
self.objs = self.sel.picked.clone();
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
if !self.sel.done {
return Prompt::new(if self.sel.removing { "Remove objects" } else { "Select geometry to dimension" }, Accept::SELECT);
}
match self.ask {
Ask::Position => Prompt::new("Specify dimension line position", Accept::POINT)
.kw(&["Continuous", "Staggered", "Baseline", "Ordinate", "Radius", "Diameter", "datumPoint", "Edit", "seTtings"])
.default(self.mode.name()),
Ask::Datum => Prompt::new("Select new datum point", Accept::POINT),
Ask::Remove => Prompt::new("Indicate dimension point to remove", Accept::POINT).kw(&["Add", "eXit"]).default("eXit"),
Ask::Add => Prompt::new("Indicate dimension point to add", Accept::POINT).kw(&["Remove", "eXit"]).default("eXit"),
Ask::Settings => Prompt::new("Associative dimension priority", Accept::TEXT).kw(&["Endpoint", "Intersection"]).default("Endpoint"),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if !self.sel.done {
return match self.sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => {
self.objs = hs;
Ok(Step::Continue)
}
};
}
match (self.ask, i) {
(Ask::Position, Input::Point(at)) => {
let r = run(s, &self.params(at))?;
let n = r.get("handles").and_then(Value::as_array).map_or(0, Vec::len);
s.echo(format!("{n} dimension(s) created."));
s.set_selection(Vec::new());
return Ok(Step::Done);
}
(Ask::Position, Input::Keyword(k)) => match k.as_str() {
"datumPoint" => self.ask = Ask::Datum,
"Edit" => self.ask = Ask::Remove,
"seTtings" => self.ask = Ask::Settings,
m => {
if let Some(m) = Mode::parse(m) {
self.mode = m;
}
}
},
(Ask::Datum, Input::Point(p)) => {
self.datum = Some(p);
self.ask = Ask::Position;
}
(Ask::Remove, Input::Point(p)) => {
self.tol = self.tol.max(s.pixel_size() * s.settings.pickbox.max(1.0));
self.remove.push(p);
}
(Ask::Add, Input::Point(p)) => self.add.push(p),
(Ask::Remove, Input::Keyword(k)) if k == "Add" => self.ask = Ask::Add,
(Ask::Add, Input::Keyword(k)) if k == "Remove" => self.ask = Ask::Remove,
(Ask::Remove | Ask::Add | Ask::Settings, Input::Keyword(_) | Input::Enter) => self.ask = Ask::Position,
(Ask::Settings, Input::Text(_)) => self.ask = Ask::Position,
(_, Input::Enter | Input::Cancel) => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if !self.sel.done || self.ask != Ask::Position || self.objs.len() > 1000 {
return Vec::new();
}
let Ok((mut pts, circles)) = geometry(s, &self.objs) else { return Vec::new() };
if pts.len() > 2000 {
return Vec::new();
}
pts.extend(&self.add);
for q in &self.remove {
while let Some(i) = nearest(&pts, *q, self.tol) {
pts.swap_remove(i);
}
}
plan(s, &pts, &circles, self.mode, c, None, self.datum).unwrap_or_default()
}
}
+9
View File
@@ -15,6 +15,11 @@ pub(super) struct TEditM {
}
impl TEditM {
/// Align Text > Angle: select the dimension (or use the preselected one), then ask for the angle.
pub(super) fn angle() -> Self {
Self { dim: None, asking_angle: true }
}
fn run(&self, s: &mut Session, mut p: Value) -> Result<Step> {
let Some(h) = self.dim else { return Ok(Step::Cancel) };
if let Some(o) = p.as_object_mut() {
@@ -94,6 +99,10 @@ impl Interactive for TEditM {
let Some(EntityKind::Dimension(mut d)) = self.dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) else { return Vec::new() };
d.text_mid = v3(c);
d.user_text_pos = true;
if let Ok(doc) = s.doc() {
let st = doc.dim_style(&d.style).cloned().unwrap_or_default().with_overrides(&d.overrides);
st.follow_text(&mut d, doc.header.f64("DIMSCALE", 1.0));
}
d.block = None;
vec![EntityKind::Dimension(d)]
}

Some files were not shown because too many files have changed in this diff Show More