Compare commits

..
Author SHA1 Message Date
skylartaylor 823627bfb6 nightly: enforce the signing guard and fix the review findings
- `nightly_compile_gui` calls `nightly_refuse_signing_env` before cargo, so an exported signing key
  cannot reach the compiler or a dependency build script.
- The candidate-workflow check reads the whole `push:` mapping by indentation, so a `paths` filter
  after a blank line is rejected; a negative fixture covers it.
- `profile_root::overlaps` keeps a non-UTF-8 component's exact bytes instead of folding it through
  `to_string_lossy`, and `private_subdirectory` refuses a regular file where a folder belongs.
- The Arch launcher passes a Launcher's `--profile-root` through, like `--launch-profile`.
- Packaging lint runs for `.github/nightly-signing-policy.json` changes.
- Windows: `nightly.ps1` builds into the `-TargetDir` it then reads; the signing fixture restores
  the caller's environment and drops its `cargo`/`git`/`Invoke-WebRequest` mocks.
- A start that created no window passes `false` for `unclean_notice_shown`, so an unclean record
  survives for the next launch to report instead of being deleted.
2026-11-25 00:59:23 +01:00
skylartaylor 809479c1d6 fix(nightly): keep Cargo.lock in cargo's order for the app's winsafe dependency
The nightly port added winsafe to the cadcraft app's dependency list by hand
and put it before winit, so the gate's `git diff --exit-code -- Cargo.lock`
failed after cargo rewrote the list in its sorted order. Move winsafe after
winresource, which is where cargo writes it.
2026-11-25 00:30:36 +01:00
skylartaylor 6c8118aa68 nightly: fix the batch 2A review findings (fmt, version line, assets, fence)
The Opus batch 2A review of nightly/cadcraft-flavor found five items; all are
fixed here, with tests, and nothing outside this channel changes.

1. rustfmt: `cargo fmt --all` (main.rs, nightly_session.rs, process_identity.rs,
   profile_root.rs, ui-egui chrome.rs/lib.rs), so the first `cargo xtask ci`
   step passes; `cargo fmt --all -- --check` is clean with rustfmt
   1.10.0-stable, the version hosted CI uses.
2. Version line: stable's `version_string()` is back to the exact clap form
   (`cadcraft <workspace version>`), so `launch_args::version_stops_parsing`
   passes again and the stable log line is unchanged. The Nightly identity moved
   to `nightly_version_line()` = `CADCraft <prepared> (nightly-v1)`, used by
   `prepare_launch`'s query (plain and Launcher forms) and, through
   `reported_version`, by the log. A unit test pins the kit's form and that the
   app name never gains a "Nightly".
3. `cargo xtask assets`: ATTRIBUTION.md rows for the six new files under
   `assets/app-icon/` (README, the nightly mark and its 1024 master, the .ico,
   the .icns and the provenance JSON). The rule was reproduced locally and
   reports no missing asset.
4. Deleted the dormant duplicates beside Dylan's enabled pair:
   `.github/workflows/nightly-dispatch.yml` and
   `docs/nightly-signing-policy.example.json`; `docs/releasing.md` now says
   there is no automatic transport yet. His `nightly.yml`, `nightly-sign.yml`
   and `.github/nightly-signing-policy.json` are untouched (no schedule, the
   five release managers).
5. `forbidden_roots()` now also fences stable's eframe storage folder per OS
   (`$XDG_DATA_HOME/ai.storyteller.cadcraft`,
   `~/Library/Application Support/ai.storyteller.cadcraft`,
   `%APPDATA%\ai.storyteller.cadcraft`), where stable's `app.ron` lives, with
   one assertion per OS in the existing fence tests.

Kit standards applied: the flat tar uses the standard layout -- `cadcraft` is
the launcher and `cadcraft-bin` the GUI (archive policy, archive tests and
launcher tests updated; a stub-`cargo` render of `nightly.sh` and the extracted
launcher were checked). The launcher passes `--launch-profile`,
`--profile-root`, `--version` and `-V` through once, and refuses a missing or
aliased `cadcraft-bin` instead of exec'ing it. The version line is
`<App> <version> (nightly-v1)`. The tar also ships
`assets/app-icon/cadcraft-nightly.png` rather than copying the stable 256 px
icon.

Optional nits taken: `nightly.ps1` drops the unread CADCRAFT_OVERRIDE_VERSION;
`nightly-signing-tests.ps1` gives its clean-build case the fixture's
CADCRAFT_BUILD_SHA/DATE and a `git` stub, so it reaches the mocked compiler
boundary instead of failing the source preflight; the no-build lint job also
renders the Arch handoff (`nightly-arch-tar-test.sh`).

Tests run here: `python3 packaging/nightly-tests.py` 77 tests OK,
`bash packaging/linux/nightly-arch-tar-test.sh` PASS, `bash -n` over the nine
launcher/packaging scripts, `cargo fmt --all -- --check` clean, and
`cargo check --locked -p cadcraft -p cadcraft-ui-egui --tests` plus
`cargo clippy --locked` (same crates, --all-targets) both clean at the QA-211
gate. pwsh, shellcheck and actionlint are not installed on this host, so the
PowerShell suites and the two linters were not re-run here.
2026-11-25 00:05:28 +01:00
skylartaylor 865ddf2a15 packaging(linux): start every nightly format with the flavor's launch profile
The Nightly flavor refuses to start without `--launch-profile nightly-v1
--profile-root <dir> -- <files>`, but every Linux nightly launcher still only
exported CADCRAFT_CONFIG_DIR and ran the binary bare, so an installed, AppImage,
Arch or Flatpak nightly could not start at all -- and the nightly tar had no
launcher, so an unpacked copy shared stable's settings folder and app.ron.

Every format now starts the GUI the flavor's way: the deb/rpm wrapper, the
AppImage AppRun (still a script, not a symlink), the Arch launcher, the Flatpak
wrapper, and a new launcher shipped inside the flat tar. The profile is
$XDG_DATA_HOME/cadcraft-nightly (inside the Flatpak's own sandbox folder), which
passes the fence. A plain version query and the Launcher's own query form are
passed through once, never doubled, so `--version` still answers without a
profile. The window identity the flavor selects is now the StartupWMClass every
nightly desktop entry names.

Also: isolate the renamed nightly CLI, which still read stable's settings folder;
let the flavor accept its own nightly Flatpak instance (FLATPAK_ID is set inside
the sandbox, so the blanket refusal made the bundle unusable) while keeping every
other instance refused; and make nightly-common.sh compare the exact
`CADCraft <version> (nightly-v1)` line and also run the Launcher's query form,
which must not create the root. The build now passes CADCRAFT_BUILD_CHANNEL and
CADCRAFT_VERSION explicitly (build.rs reads those, not the override).

Tests: new packaging/nightly-launcher-tests.py, wired into nightly-tests.py,
runs every launcher against a recorder; the archive and Arch tests cover the new
tar member.

Also drops the unused `APP_ID` const in main.rs, which the branch's
`cargo clippy --workspace --all-targets -- -D warnings` gate rejects.
2026-11-24 23:18:36 +01:00
skylartaylor b462abfdff packaging: add the isolated CADCraft nightly for Windows and macOS
The app-side flavor and the Windows/macOS producers, on top of Dylan's
nightly-linux-packaging branch: the Linux producer, the shared nightly helpers,
the release-ref callers and the policy, and the eframe persistence fix are his
(9bbbfb49) and stay as he wrote them. This commit adds what was missing for a
nightly to be a separate, isolated app on all three platforms.

App side: the `CADCRAFT_BUILD_CHANNEL=nightly-v1` build channel with its own
icon, version identity, product name and Windows AUMID; the Launcher's
`--launch-profile nightly-v1 --profile-root <abs> --` protocol with the early
`--version` answer in both forms, before logging, identity, IPC or any window;
the profile fences (stable roots, portable layout, install boundary, aliases,
`FLATPAK_ID`, and `CADCRAFT_CONFIG_DIR` accepted only when it names the profile
itself, so a Launcher wrapper can export it); one data-root hook so the settings
folder *and* eframe's `app.ron` are the profile, with autosave/Drawing Recovery,
logs, reports and the single-instance socket inside it; the session lease and
unclean-exit record finished from `on_exit` (macOS Cmd+Q); updater, control
server and agent surfaces off in this channel; the channel name in the window
title, drawn caption and About.

Windows: `packaging/windows/nightly.ps1` with `package.ps1 -Nightly
-BuildOnly` and `sign.ps1 -Required/-CheckOnly/-CheckBuildEnvironment`.
macOS: `nightly.sh`, `nightly-lib.sh`, `nightly-sign.sh`, `nightly-verify.sh`
and `nightly_plist.py`.
Shared: the `nightly-tests.py` runner over Dylan's release contracts plus the
archive, plist and macOS signing suites; the no-build `nightly-source-contract`
lint job; the dormant `nightly-dispatch.yml` (no schedule); the stable Linux key
file his tests read; and the nightly icon set with its provenance.
2026-11-24 22:30:27 +01:00
Dylan M. Taylor 9bbbfb49e9 packaging(nightly): port Linux nightly archive scripts, isolate eframe persistence, and exclude packaging from Sonar coverage 2026-11-24 16:18:40 -05:00
Dylan M. Taylor 9442ba19a0 fix(packaging): fix actionlint concurrency key and nightly Linux packaging review issues 2026-11-24 14:21:39 -05:00
Dylan M. Taylorandskylartaylor 22ed6624e5 ci(nightly): enable nightly workflows for supervised manual runs
Port Skylar's (@skylartaylor) supervised manual nightly enablement from
storytold/photocraft#16594 into CADCraft:

- Add .github/nightly-signing-policy.json (v3 policy adapted for
  storytold/cadcraft, repository ID 1408289866, CI workflow 380135820,
  SonarCloud project storytold_cadcraft; producer_workflow_id pending
  main registration).
- Add .github/workflows/nightly.yml and .github/workflows/nightly-sign.yml
  pinned to craft-common-actions@605d58766e8f536564da8fc81d3676ac86816dea
  for supervised manual workflow_dispatch runs by the reviewed release
  managers.
- Add docs/nightly-release-preparation.md and
  packaging/nightly-release-tests.py contract tests.

Credit to @skylartaylor for the original implementation in
storytold/photocraft#16594.

Co-authored-by: skylartaylor <[email protected]>
2026-11-24 14:14:41 -05:00
Dylan M. Taylor 29d7e73817 packaging(linux): support co-installable nightly packages 2026-11-24 13:33:35 -05:00
429 changed files with 3466 additions and 45489 deletions
+5 -5
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": 429719786,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"release_branch": "nightly-signer",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
+7 -24
View File
@@ -1,8 +1,7 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
@@ -23,37 +22,21 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
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 }}
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 }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
# callee job may bind the existing release environment and export keys in its signing step.
+4 -5
View File
@@ -22,14 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
-20
View File
@@ -1,20 +0,0 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
-2
View File
@@ -72,8 +72,6 @@ Layout:
Checks for the crates you changed: `cargo test -p <crate>`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`, `cargo xtask parity` (regenerates `docs/parity-checklist.md`).
Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a covered menu item `headless: yes` because its command is in the engine registry that `cadcraft-cli` and the MCP server load. An uncovered item takes `no`/`partial` and a `reach` (`window`, `os`, `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs` (a path ending in ` > ` covers its submenu), or reads `unknown`. Never write `yes` there. A covered leaf is `yes` whatever its marks say, so a submenu mark stays while any leaf under it is uncovered; drop a mark only once commands cover every leaf it matches (the check then fails on it as stale).
Paths and conventions:
- No crate allows `unsafe` (`unsafe_code = "forbid"` in the workspace).
+1 -37
View File
@@ -87,41 +87,5 @@ Generated-in-code assets are original and have no file to list:
| `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); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
## PDF import
The CAD mapping and initial synthetic PDF tests are adapted from CADCraft contributor
@DuukDuul's [PR #2787](https://github.com/storytold/cadcraft/pull/2787), commit
`ec17f63f189d1dccf91357701f9bba243ca88dd5`, under MIT OR Apache-2.0. The mapping has
been changed for the current shared reader, bounded import, fill rules and diagnostics.
PDF test inputs in `crates/io/tests/it/pdf_import.rs`, `crates/io/src/pdf_read.rs`, and
`apps/cadcraft-cli/tests/it/pdf_import.rs` are generated from literal content streams or
CadCraft's own plotter. No customer documents are included.
Enabling `craft-pdf` interpretation uses the following unchanged dependency assets from
`craft-libs` revision `453b0da782ccef39be9a6dac8d27c80b553ef1cc`. Fonts remain in the
shared dependency. Their source and hashes are retained below; notices are in `NOTICE`.
| Asset | Author | Source | Licence | SHA-256 | Notes |
|---|---|---|---|---|---|
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
Generated
+86 -1398
View File
File diff suppressed because it is too large Load Diff
+28 -39
View File
@@ -14,11 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,19 +28,17 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -50,8 +48,6 @@ thiserror = "2"
same-file = "1"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] }
# Geometry types shared with the PDF interpreter.
kurbo = "0.13"
log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
@@ -74,12 +70,8 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -89,7 +81,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -121,23 +113,20 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
-189
View File
@@ -172,192 +172,3 @@ Original src/avx2/fdct.rs opening notice
* Based on the x86 SIMD extension for IJG JPEG library
* Copyright (C) 1999-2006, MIYASAKA Masaru.
*/
PDF import dependency notices
=============================
The PDF import mapping and synthetic tests derive from CADCraft PR #2787,
commit ec17f63f189d1dccf91357701f9bba243ca88dd5 (MIT OR Apache-2.0).
Local adaptations retain the project licences.
Standard PDF font programs (PDFium, BSD-3-Clause)
// Copyright 2014 PDFium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CMYK profile (CC0-1.0)
CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.
For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.
For more information, please see
http://creativecommons.org/publicdomain/zero/1.0/
PDF character maps: LICENSE.txt
Copyright 1990-2023 Adobe. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of Adobe nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+7 -19
View File
@@ -89,15 +89,9 @@
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
the way decades of drafting habit expect.
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
and save as 2000 through 2018. New drawings default to
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
drawings; drawings with a file keep their own version, subject to supported-version mapping
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
saves. Export to SVG and PNG today.
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
files (R13 through 2018) open and save through the open-source acadrust library. Export to SVG
and PNG today.
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
@@ -120,11 +114,11 @@ numbers):
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| Files | DXF read (R12–2018, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) |
| 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, 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), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული) and Tamil (தமிழ், with an installed Tamil font), 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), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski) and Georgian (ქართული), 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
@@ -350,9 +344,7 @@ See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of
|---|---|---|
| x64 (64-bit Intel/AMD) | `cadcraft-<ver>-windows-x64.msi` | `cadcraft-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `cadcraft-<ver>-windows-arm64.msi` | `cadcraft-<ver>-windows-arm64-portable.zip` |
For 32-bit Windows, [CADCraft v0.18.0](https://github.com/storytold/cadcraft/releases/tag/v0.18.0)
was the last release with both an x86 MSI and portable ZIP.
| x86 (32-bit) | `cadcraft-<ver>-windows-x86.msi` | `cadcraft-<ver>-windows-x86-portable.zip` |
Installers and executables are code-signed.
@@ -389,19 +381,15 @@ and web backend defaults are unchanged.
| Flatpak | `cadcraft-<ver>-linux-x86_64.flatpak` | `cadcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `cadcraft-<ver>-linux-x86_64.deb` | `cadcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `cadcraft-<ver>-linux-x86_64.rpm` | `cadcraft-<ver>-linux-aarch64.rpm` | |
| Arch Linux | `cadcraft-<ver>-linux-x86_64.pkg.tar.zst` | `cadcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
| Tarball | `cadcraft-<ver>-linux-x86_64.tar.gz` | `cadcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
RISC-V (riscv64): `cadcraft-<ver>-linux-riscv64.tar.gz`, cross-compiled; needs glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `cadcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 (ARM64) | `cadcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+3 -6
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-25 · **Change:** minor (Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
@@ -115,7 +115,7 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The open findings of the security audit (#1919–#1935): check each against the input limits that
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
overwrite existing ones (#1921) is fixed by #1276.
- A saved file that crashes AutoCAD 2021 (#3303); dimension text lost on save (#3299) was fixed on 2026-11-20.
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
@@ -131,7 +131,7 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The prompt options that still say "not available yet" (gaps F1).
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
#3308.
- 602 pull requests are open (2026-11-25; 661 on 2026-11-20). About 230 were mergeable, passed CI and were small; they are
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
reviewed and landed in this order, the longest-waiting authors first within a row.
**3. Lower priority: affects fewer people and nothing breaks without it.**
@@ -141,8 +141,6 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
but a file with 3D content must open safely (tier 1).
- Menu breadth against AutoCAD for Mac as a headline number.
Done from 2026-11-21 to 2026-11-25: PDFIMPORT, a PDF page as editable lines, polylines, solid hatches and text (#3375 in #3419); dynamic block references that rotate, flip, array, scale, stretch polar, align and look up, with their grips (#963, #993, #1030, #1098, #1699, #1723, #1752 in #3424; authoring is still open); the proxy graphics of other applications' objects drawn (#2697, #3435, #3437) and dimensions kept as read drawn from their `*D` block (#3439); saves that keep layout plot settings (#3233, #3386, #3390), DXF 2007+ table cell text (#3392), hatch boundary flags (#3389), fit text (#3391) and registered applications (#2918); the Array window for ARRAYRECT and ARRAYPOLAR (#3394); ATTDIA and the Edit Attributes dialog on INSERT (#3411) and constant attribute values drawn (#3462); Edit > Paste from the system clipboard (#3366, #3460, #3461; #3320 open); opening from Finder and quit prompts on macOS (#1347 in #3344, not yet run on a Mac); an already-open drawing selects its tab when opened from the interface (#899 in #3422; the control channel, MCP, scripts and LISP still open a second copy); Tab through every object snap candidate (#1673); the Write Block dialog for WBLOCK (#1778); Generate Boundary (#2804); mitred wide polylines (#3453; the extents leave out the mitre tip, #3443); DIMASSOC 1 (#2977); crossing selection of block references by what they draw (#3445); an option to turn off the update check (#3097).
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
@@ -172,7 +170,6 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | minor | Upcoming updated for the merges of 2026-11-21 to 2026-11-25 (PDF import, dynamic block reference actions, proxy graphics, what saves keep, Array window, ATTDIA, system clipboard paste, macOS opening from Finder, WBLOCK dialog, Generate Boundary); #3299 fixed; pull-request count 661 → 602; percentages and hours not re-scored |
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
+2 -2
View File
@@ -26,12 +26,12 @@ fn with_formats(cell: &'static std::sync::OnceLock<String>, before: &str, list:
/// The drawing an input argument names.
fn read_help() -> &'static str {
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
with_formats(&C, "The drawing to read ", Format::READ, ", or a PDF whose first page opens as editable vector content")
with_formats(&C, "The drawing to read ", Format::READ, "")
}
fn open_help() -> &'static str {
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
with_formats(&C, "Drawings to open ", Format::READ, ", or PDFs (their first page)")
with_formats(&C, "Drawings to open ", Format::READ, "")
}
fn write_help() -> &'static str {
-8
View File
@@ -45,17 +45,10 @@ fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).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())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
@@ -66,7 +59,6 @@ fn install_io() {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
+1 -12
View File
@@ -145,22 +145,15 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
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) {
io.errln(format_args!("{m}"));
}
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
io.errln(format_args!("{note}"));
}
}
Ok(())
}
@@ -178,10 +171,6 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) ->
ole = ole.saturating_add(1);
continue;
}
// One with proxy graphics draws them (#2697, #3438).
if !u.graphics.is_empty() {
continue;
}
let n = types.entry(u.dxf_type.as_str()).or_insert(0);
*n = n.saturating_add(1);
}
@@ -1,144 +0,0 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// The engine's commands that write an image say it too, on the command line and in the result's
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
/// `document.bytes`.
#[test]
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
let cmds = [
format!("export {{\"path\": {}}}", out("export.png")),
format!("plot {{\"path\": {}}}", out("plot.pdf")),
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
format!("saveas {{\"path\": {}}}", out("saved.svg")),
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
"plot {\"output\": \"svg\"}".to_string(),
"document.bytes {\"format\": \"pdf\"}".to_string(),
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
];
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
let input = dir.join(format!("line-{periods}.dxf"));
std::fs::write(&input, dashed_line(periods)).unwrap();
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
for c in &cmds {
args.extend(["--cmd".to_string(), c.clone()]);
}
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(results.len(), cmds.len(), "{results:?}");
for (c, r) in cmds.iter().zip(&results) {
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
}
// Said on the command line once for each command.
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
}
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1,41 +0,0 @@
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF with a 256-element linetype and a line drawn with it.
fn dxf() -> String {
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
for i in 0..256 {
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
}
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
s
}
#[test]
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("long.dxf");
std::fs::write(&source, dxf()).unwrap();
let source = source.to_str().unwrap();
let notes =
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
assert!(
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
let _ = std::fs::remove_dir_all(&dir);
}
-5
View File
@@ -1,12 +1,7 @@
mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
// DWG output needs craft-dwg's bridge.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_note;
mod mcp_connect;
mod pdf_import;
mod skipped_records;
mod undrawn_entities;
mod usage;
-116
View File
@@ -1,116 +0,0 @@
//! A PDF page converted on the command line keeps its geometry and its fill rules through a DXF
//! or DWG save and reopen.
use std::process::{Command, Output};
use serde_json::Value;
const MM_PER_PT: f64 = 25.4 / 72.0;
/// A line, a nonzero fill of two nested squares wound the same way (all of it filled), an
/// even-odd fill of the same squares (the inner one a hole) and a nonzero fill of two
/// overlapping squares (split into triangles).
const CONTENT: &str = "1 0 0 RG 2 w 10 10 m 100 10 l S\n\
0 0 1 rg 200 200 m 300 200 l 300 300 l 200 300 l h 220 220 m 280 220 l 280 280 l 220 280 l h f\n\
0 1 0 rg 400 400 m 500 400 l 500 500 l 400 500 l h 420 420 m 480 420 l 480 480 l 420 480 l h f*\n\
1 0 1 rg 50 600 m 150 600 l 150 700 l 50 700 l h 100 650 m 200 650 l 200 750 l 100 750 l h f\n";
fn page(content: &str) -> Vec<u8> {
format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R >> endobj\n\
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
trailer << /Root 1 0 R >>\n%%EOF\n",
content.len()
)
.into_bytes()
}
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The model space of `file` with each object's geometry.
fn inspect(file: &str) -> Value {
let out = cli(&["run", file, "--cmd", r#"drawing.inspect {"entities":true}"#]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{file}: {}", String::from_utf8_lossy(&out.stderr));
serde_json::from_str(stdout.lines().last().unwrap_or_default()).unwrap_or_else(|e| panic!("{file}: {e}: {stdout}"))
}
fn inside(ring: &[(f64, f64)], (x, y): (f64, f64)) -> bool {
let mut odd = false;
for (i, &(ax, ay)) in ring.iter().enumerate() {
let (bx, by) = ring[(i + 1) % ring.len()];
if (ay > y) != (by > y) && x < (bx - ax) * (y - ay) / (by - ay) + ax {
odd = !odd;
}
}
odd
}
/// Whether a hatch covers the page point `at` (in PDF points), by odd parity as hatches are drawn.
fn filled(drawing: &Value, at: (f64, f64)) -> bool {
let at = (at.0 * MM_PER_PT, at.1 * MM_PER_PT);
let entities = drawing["entities"].as_array().cloned().unwrap_or_default();
entities.iter().filter(|e| e["type"] == "Hatch").any(|hatch| {
let loops = hatch["geometry"]["loops"].as_array().cloned().unwrap_or_default();
let rings = loops.iter().map(|l| {
l["vertices"]
.as_array()
.into_iter()
.flatten()
.map(|v| (v["p"]["x"].as_f64().unwrap_or(0.0), v["p"]["y"].as_f64().unwrap_or(0.0)))
.collect()
});
rings.filter(|ring: &Vec<(f64, f64)>| inside(ring, at)).count() % 2 == 1
})
}
#[test]
fn a_pdf_page_keeps_its_fills_through_dxf_and_dwg() {
let scratch = Scratch::new("pdf-import");
let pdf = scratch.0.join("plan.pdf");
std::fs::write(&pdf, page(CONTENT)).unwrap();
let pdf = pdf.to_str().unwrap().to_string();
let mut files = vec![pdf.clone()];
for ext in ["dxf", "dwg"] {
let out = scratch.0.join(format!("plan.{ext}"));
let out = out.to_str().unwrap().to_string();
let run = cli(&["convert", &pdf, &out]);
assert!(run.status.success(), "convert to {ext}: {}", String::from_utf8_lossy(&run.stderr));
files.push(out);
}
for file in &files {
let d = inspect(file);
assert_eq!(d["counts"]["Line"], 1, "{file}: {}", d["counts"]);
assert_eq!(d["counts"]["Hatch"], 3, "{file}: {}", d["counts"]);
assert!(filled(&d, (251.3, 247.7)), "{file}: the nonzero fill keeps its centre");
assert!(filled(&d, (210.2, 205.9)), "{file}: the nonzero fill keeps its rim");
assert!(!filled(&d, (451.3, 447.7)), "{file}: the even-odd fill keeps its hole");
assert!(filled(&d, (410.2, 405.9)), "{file}: the even-odd fill keeps its rim");
assert!(!filled(&d, (350.4, 351.7)), "{file}: nothing is filled between the shapes");
assert!(filled(&d, (125.3, 675.2)), "{file}: the overlap of the crossing squares stays filled");
assert!(filled(&d, (60.4, 610.3)) && filled(&d, (190.2, 740.1)), "{file}: both crossing squares stay filled");
assert!(!filled(&d, (60.4, 740.1)), "{file}: the corner beside the crossing squares stays empty");
}
}
+1 -20
View File
@@ -818,8 +818,7 @@ fn non_unicode_arguments() {
assert!(err.starts_with("error: invalid UTF-8 was detected"), "{err}");
}
/// An output name that isn't valid Unicode reaches the filesystem unchanged: only its extension
/// picks the format. Filesystems that reject the name must report their write error.
/// An output name that isn't valid Unicode is written as given: only its extension picks the format.
#[cfg(unix)]
#[test]
fn non_unicode_output_names() {
@@ -837,18 +836,6 @@ fn non_unicode_output_names() {
let code = cadcraft_cli::run(args, &mut out, &mut err);
(code, String::from_utf8_lossy(&err).into_owned())
};
// APFS rejects invalid UTF-8 names (EILSEQ), although Unix paths can represent them.
// Probe this scratch filesystem rather than assuming every macOS volume behaves alike.
let probe = latin1("probe");
let rejected_name: Option<String> = match std::fs::write(&probe, b"") {
Ok(()) => {
std::fs::remove_file(&probe).expect("remove filename probe");
None
}
#[cfg(target_os = "macos")]
Err(e) if e.raw_os_error() == Some(92) => Some(e.to_string()), // Darwin EILSEQ
Err(e) => panic!("unexpected filename probe error: {e}"),
};
let b = s.0.join("b.dxf");
let cases: [(Vec<OsString>, std::path::PathBuf); 3] = [
(vec!["sample".into(), "bracket".into(), latin1("dxf").into()], latin1("dxf")),
@@ -857,12 +844,6 @@ fn non_unicode_output_names() {
];
for (args, path) in cases {
let (code, err) = run(args.clone());
if let Some(ref filesystem_error) = rejected_name {
assert_eq!(code, 1, "{args:?}: {err}");
assert!(err.contains(filesystem_error), "{args:?}: {err}");
assert!(!path.exists(), "{path:?}");
continue;
}
assert_eq!(code, 0, "{args:?}: {err}");
assert!(path.exists(), "{path:?}");
assert!(std::fs::metadata(&path).expect("stat output").len() > 0, "{path:?}");
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+2 -12
View File
@@ -54,12 +54,11 @@ mod web {
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
self.0.close_path(ctx);
}
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.0.before_input(ctx);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -120,17 +119,10 @@ mod web {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).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())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
@@ -141,7 +133,6 @@ mod web {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
@@ -174,7 +165,6 @@ mod web {
canvas,
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
+1 -1
View File
@@ -94,7 +94,7 @@ mod tests {
let mut ui = UiState::default();
let before = serde_json::to_value(&ui).unwrap();
let mut invalid = ui.clone();
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
invalid.docking.layout.root = None;
assert!(save(&invalid).is_err());
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
+1 -1
View File
@@ -18,7 +18,7 @@ use web_sys::js_sys;
/// The hidden file input (one at a time; a cancelled pick leaves it until the next one).
const INPUT_ID: &str = "cadcraft_open_input";
/// What the picker offers: the formats OPEN reads, and the SHX fonts drawings name.
const ACCEPT: &str = ".dxf,.dwg,.pdf,.shx";
const ACCEPT: &str = ".dxf,.dwg,.shx";
/// Most files taken from one pick.
const MAX_PICKED: u32 = 64;
+7 -3
View File
@@ -41,18 +41,22 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
craft-ui = { workspace = true, features = ["native-windows"] }
craft-update = { workspace = true }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
# controls and under floating panels.
craft-window = { workspace = true }
muda = { version = "0.21", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# 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"] }
# The same winit eframe uses (the storytold fork, patched in the workspace).
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
+4 -78
View File
@@ -4,9 +4,8 @@
//! 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 (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
//! ([`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, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
@@ -25,9 +24,6 @@ struct Limits {
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Longest request line until a request on the connection has carried the right token; a
/// longer one closes the connection (#1925).
preauth_line: usize,
/// Request-line bytes buffered at once across all connections; a request that would pass it
/// is refused with an error reply.
total_bytes: usize,
@@ -47,7 +43,6 @@ impl Default for Limits {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
@@ -349,21 +344,12 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
let mut authenticated = false;
loop {
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
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,
// Only an overlong line leaves more than `max` bytes buffered.
Err(_) if !authenticated && buf.len() > max => format!(
"request line longer than {max} bytes before a request with the control token on this connection; \
send a short request with the token (such as `ping`) first; closing the connection"
),
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
@@ -380,7 +366,6 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -514,12 +499,7 @@ mod tests {
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
serve_echo_with(Limits::default())
}
/// [`serve_echo`] under `limits`.
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
let (addr, rx) = serve_with(limits);
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}));
@@ -632,60 +612,6 @@ mod tests {
drop(first);
}
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
/// has shown the token, up to 100 000 after.
fn preauth() -> Limits {
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
}
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
fn long_req_line(id: i64, len: usize) -> String {
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
}
/// A peer without the token is refused once its line passes the pre-authentication bound,
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
/// at its end (#1925).
#[test]
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
let (addr, rx) = serve_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
c.write_all(unfinished.as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(&mut c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"], json!(false));
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A long request with the token is taken once a shorter request with the token has been
/// answered on the same connection; as a connection's first line it is refused, since its
/// token comes only at the end.
#[test]
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
let addr = serve_echo_with(preauth());
let long = long_req_line(2, 5000);
let first = exchange(addr, long.as_bytes());
assert_eq!(first.len(), 1, "{first:?}");
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(1, "ping"), (2, "long")] {
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["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
}
}
#[test]
fn the_budget_is_given_back_when_the_connection_ends() {
let budget = Budget::new(100);
+40 -71
View File
@@ -61,6 +61,9 @@ struct App {
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
#[cfg(target_os = "macos")]
menus_in_window: bool,
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
@@ -138,18 +141,17 @@ impl eframe::App for App {
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.cad.close_path(ctx);
}
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
/// runtime.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(ctx, raw);
self.cad.before_input(ctx);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.cad.guarded_ui(ui);
#[cfg(target_os = "macos")]
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
@@ -182,17 +184,10 @@ pub fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).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())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
@@ -203,7 +198,6 @@ pub fn install_io() {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
fn services() -> Services {
@@ -230,7 +224,6 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
Pick::Open => vec![
(i18n::t("Drawings (DWG, DXF)"), vec!["dwg", "dxf", "dwt"]),
(i18n::t("SVG drawings (SVG, SVGZ)"), vec!["svg", "svgz"]),
(i18n::t("PDF files (PDF)"), vec!["pdf"]),
(i18n::t("All files"), vec!["*"]),
],
Pick::Save(name) => filters_for_save(name).iter().map(|(label, ext)| (i18n::t(label), vec![*ext])).collect(),
@@ -307,15 +300,17 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_app_id(os_window::app_id());
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(os_window::app_id()),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -393,23 +388,14 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
@@ -556,9 +542,6 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
let persistence_path = vars
.portable_storage_file
.clone()
@@ -568,7 +551,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
..window_options(restores_window(persistence_path.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -591,12 +574,22 @@ fn main() -> eframe::Result {
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
// close request for the window instead, so it asks first, as the close button does.
#[cfg(target_os = "macos")]
{
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::macos::EventLoopBuilderExtMacOS;
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -609,7 +602,6 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
@@ -628,17 +620,6 @@ fn main() -> eframe::Result {
app.ui = ui;
}
app.set_system_cursor_default(vars.system_cursor == Switch::On);
// Native Wayland answers a clipboard request asynchronously; every other backend in the
// next frame (egui-winit).
#[cfg(all(unix, not(target_os = "macos")))]
{
use eframe::egui_wgpu::wgpu::rwh::{HasDisplayHandle, RawDisplayHandle};
if let Ok(display) = cc.display_handle() {
app.set_clipboard_late_answers(matches!(display.as_raw(), RawDisplayHandle::Wayland(_)));
}
}
#[cfg(any(not(unix), target_os = "macos"))]
app.set_clipboard_late_answers(false);
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
#[cfg(target_os = "macos")]
app.set_native_menus(vars.no_native_menu != Switch::On);
@@ -672,7 +653,7 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
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));
}
@@ -723,6 +704,8 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
@@ -760,7 +743,7 @@ mod tests {
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
#[test]
fn the_first_launch_opens_centred() {
let o = window_options(false, STENCIL_BITS, None);
let o = window_options(false, STENCIL_BITS);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -768,7 +751,7 @@ mod tests {
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
#[test]
fn a_saved_window_reopens_where_it_was() {
let o = window_options(true, STENCIL_BITS, None);
let o = window_options(true, STENCIL_BITS);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
@@ -793,8 +776,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).stencil_buffer, bits);
}
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
@@ -848,17 +831,3 @@ mod tests {
assert_eq!(raw.system_theme, None);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+3 -12
View File
@@ -15,9 +15,6 @@ pub struct NativeMenu {
items: HashMap<String, (String, String, MenuItem)>,
submenus: Vec<(String, Submenu)>,
predefined: Vec<(&'static str, PredefinedMenuItem)>,
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
/// muda's predefined Quit ends the process through `terminate:` without asking.
quit: MenuItem,
language: &'static str,
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
@@ -61,6 +58,7 @@ impl NativeMenu {
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
// 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"));
@@ -71,8 +69,6 @@ impl NativeMenu {
let _ = app_menu.append(&PredefinedMenuItem::separator());
}
}
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
let _ = app_menu.append(&quit);
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));
@@ -89,7 +85,6 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -119,9 +114,7 @@ impl NativeMenu {
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
ctx.request_repaint();
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if cmd == "ui.discord" {
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
} else {
@@ -140,7 +133,6 @@ impl NativeMenu {
for (label, item) in &self.predefined {
item.set_text(i18n::tr(language, label));
}
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr_menu(language, label));
}
@@ -156,8 +148,7 @@ impl NativeMenu {
if cmd == menus::RECENT_CLEAR {
continue;
}
let en = (typing && menus::edits_text(cmd))
|| cadcraft_engine::find_command(cmd).is_none_or(|c| cadcraft_ui_egui::clipboard::offered(&app.session, c));
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
item.set_enabled(en);
}
}
+1 -73
View File
@@ -185,56 +185,11 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
@@ -335,8 +290,6 @@ const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
const PROFILE_FOLDERS: [&str; 6] = [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"];
#[cfg(test)]
mod tests {
use super::*;
@@ -521,31 +474,6 @@ mod tests {
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
for name in [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"] {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
+5 -5
View File
@@ -252,7 +252,7 @@ mod tests {
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
@@ -263,9 +263,9 @@ mod tests {
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
assert!(!reloaded.show_toolsets);
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
fs::remove_dir_all(directory).unwrap();
}
@@ -293,8 +293,8 @@ mod tests {
assert_eq!(ui.toolset_tab, "Modeling");
assert_eq!(ui.history_lines, 4);
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
assert_eq!(ui.docking.layout(), default_workspace().layout());
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
assert_eq!(ui.docking.layout, default_workspace().layout);
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
fs::remove_dir_all(directory).unwrap();
}
+3
View File
@@ -2,4 +2,7 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
-3
View File
@@ -138,6 +138,3 @@ real_name = "Tyrel Haveman"
real_name = "Sladrian Pedroso"
display_name = "Sladrian Pedroso"
sync_github_name = false
[people.iHateStupidPeople]
sync_github_name = true
+3 -4
View File
@@ -238,9 +238,8 @@ mod tests {
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
}
// An unclamped spline has no ends: one whose control points wrap round.
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
assert!(closed.wraps() && spline_end(&closed, false).is_none());
// 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());
}
}
+47 -246
View File
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
mod apply;
mod grips;
mod reference;
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
pub use apply::{drag_grip, set_property};
pub use grips::{DynGrip, GripPart, GripShape, grips};
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
@@ -52,13 +52,6 @@ pub struct DynamicBlock {
/// the grips shown in them by object).
#[serde(skip)]
pub grip_objects: Vec<(i32, Handle)>,
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
/// reflection line).
#[serde(skip)]
pub grip_points: Vec<(i32, Vec3)>,
/// The block's base point (where a base point parameter is in the block).
#[serde(skip)]
pub base: Vec3,
}
/// One parameter: a property a reference to the block can change.
@@ -94,41 +87,16 @@ pub enum ParameterKind {
/// 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 (Distance1, Angle1): the end point's distance
/// from the base and its direction (counterclockwise from the X axis of the block).
Polar {
base: Vec3,
end: Vec3,
label: String,
description: String,
angle_label: String,
angle_description: String,
values: ValueSet,
angle_values: ValueSet,
},
/// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far
/// the end point is from the base along the block's X and Y axes.
Xy {
base: Vec3,
end: Vec3,
x_label: String,
y_label: String,
x_description: String,
y_description: String,
x_values: ValueSet,
y_values: ValueSet,
},
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
/// measured from the direction the dynamic block has from base to end.
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
/// Aligns the reference with nearby geometry: dragged next to an object, its base point lands
/// on the object and the direction from base to end runs along it. `perpendicular` is the
/// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in
/// every case measured.
Alignment { base: Vec3, end: Vec3, perpendicular: bool },
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
/// of its two states, not flipped and flipped.
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
/// 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.
@@ -142,9 +110,7 @@ pub enum ParameterKind {
},
/// A named value chosen from a lookup table.
Lookup { at: Vec3, label: String, description: String },
/// The block's base point: the reference's insertion point is here, and an action that moves
/// it moves the reference's insertion point. `at` is where the block editor showed it; the
/// block itself has it at its base point (AutoCAD moves the block's objects to put it there).
/// Moves the block's base point.
BasePoint { at: Vec3 },
/// A parameter type not modelled yet.
Other { dxf_type: String },
@@ -156,23 +122,11 @@ impl ParameterKind {
match self {
ParameterKind::Linear { label, .. }
| ParameterKind::Point { label, .. }
| ParameterKind::Rotation { label, .. }
| ParameterKind::Flip { label, .. }
| ParameterKind::Visibility { label, .. }
| ParameterKind::Lookup { label, .. } => Some(label),
_ => None,
}
}
/// Every property name a reference shows for the parameter: a polar parameter's distance
/// and angle, an XY parameter's two distances, else its one label.
pub fn labels(&self) -> Vec<&str> {
match self {
ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label],
ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label],
other => other.label().into_iter().collect(),
}
}
}
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
@@ -251,46 +205,24 @@ pub enum ActionKind {
angle_offset: f64,
},
/// A table: each row sets the listed parameter values together.
Lookup { columns: Vec<LookupColumn>, rows: Vec<Vec<String>> },
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 },
/// Scales the objects about its base point by how much the distance it follows grew (a linear
/// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each
/// reads ("Scale", "XScale", "YScale").
Scale { base: ActionBase },
/// Turns the objects about its base point by the change of a rotation parameter's angle.
Rotate { base: ActionBase },
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
Flip,
/// Repeats the objects as far as the parameter it follows reaches: along a distance (linear
/// or polar parameter) every `column` units, or in a grid of columns and rows across an XY
/// parameter's distances. The objects follow the parameter's base point.
Array { column: f64, row: f64 },
/// Follows a polar parameter: turns its objects about the parameter's base point by the change
/// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object
/// not listed) along the parameter's new direction by the change of its distance. The
/// `rotate_only` objects (outside the selection) only turn.
PolarStretch {
frame: Vec<Vec2>,
#[serde(serialize_with = "hex_vertices")]
vertices: Vec<(Handle, Vec<i32>)>,
#[serde(serialize_with = "hexes")]
rotate_only: Vec<Handle>,
Move {
multiplier: f64,
angle_offset: f64,
},
Scale,
Rotate,
Flip,
Array,
PolarStretch,
/// An action type not modelled yet.
Other { dxf_type: String },
}
/// Where an action that turns or scales its objects has its base point.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionBase {
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
pub dependent: bool,
pub offset: Vec3,
pub at: Vec3,
Other {
dxf_type: String,
},
}
/// A lookup table column: the parameter value it reads or sets.
@@ -451,7 +383,7 @@ pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -
/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built.
pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option<DynamicBlock> {
let xdict = block_xdict(d, name)?;
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
let mut out = DynamicBlock::default();
for o in graph_members(&objects.0, xdict)? {
let secs = sections(&o.tags);
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
@@ -466,7 +398,6 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
} else {
if kind.ends_with("GRIP") {
out.grip_objects.push((node, o.handle));
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
}
out.other.push(o.kind.clone());
}
@@ -475,21 +406,15 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
}
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end
/// X); after a one-point parameter's point, its grip (93).
/// 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(4);
let mut ids: Vec<i32> = (0..n).map(|_| c.int(91)).collect();
// Corner grips only an XY parameter has (the others write 0 for them).
while ids.len() > 2 && ids.last() == Some(&0) {
ids.pop();
}
return ids;
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);
@@ -521,49 +446,15 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
// the value set.
"BLOCKROTATIONPARAMETER" => {
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
let (label, description) = (c.string(305), c.string(306));
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
}
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
"BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
let (label, description) = (c.string(305), c.string(306));
let states = [c.string(307), c.string(308)];
ParameterKind::Flip { base, end, label, description, states }
}
// The distance's name and description (305, 306), the angle's (307, 308), the label
// offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's
// (410, 97, 145–148, 176).
"BLOCKPOLARPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter"));
let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let values = value_set_at(&mut c, [309, 96, 141, 175]);
let angle_values = value_set_at(&mut c, [410, 97, 145, 176]);
ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values }
}
// The vertical distance's name (305) before the horizontal's (306), then their
// descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97,
// 146–149, 176) and the horizontal one (410, 96, 142–145, 175).
"BLOCKXYPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter"));
let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let y_values = value_set_at(&mut c, [309, 97, 146, 176]);
let x_values = value_set_at(&mut c, [410, 96, 142, 175]);
ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values }
}
// Its type (280): 1 perpendicular, 0 tangent.
"BLOCKALIGNMENTPARAMETER" => {
let (base, end) = two();
let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0;
ParameterKind::Alignment { base, end, perpendicular }
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() },
}
@@ -572,17 +463,11 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
/// 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 {
value_set_at(c, [307, 96, 141, 175])
}
/// A value set written with codes `[description, flags, minimum, count]`: the maximum and
/// increment follow the minimum's code, each listed value is the code after the increment's.
fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet {
c.next(description);
let flags = c.int(flags);
let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2));
let n = c.count(count);
let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
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 }
}
@@ -622,56 +507,16 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
let (multiplier, angle_offset) = (c.real(140), c.real(141));
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
}
// The base point's two connections (as a rotate action's), then the scale's three: the
// parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale").
"BLOCKSCALEACTION" => {
let with_base = section(secs, "AcDbBlockActionWithBasePt");
let mut connections = two_connections(with_base);
let tags = section(secs, "AcDbBlockScaleAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i))));
(connections, ActionKind::Scale { base: action_base(with_base) })
}
"BLOCKROTATEACTION" => {
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
connections.push((c.int(94), c.string(303)));
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
}
// Its four connections: the parameter (92-95) and the values it reads (301-304).
"BLOCKFLIPACTION" => {
let tags = section(secs, "AcDbBlockFlipAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
(connections, ActionKind::Flip)
}
// Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and
// column (141) offsets.
"BLOCKARRAYACTION" => {
let tags = section(secs, "AcDbBlockArrayAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let (row, column) = (c.real(140), c.real(141));
(connections, ActionKind::Array { column, row })
}
"BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")),
"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 }
}
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
/// point it stays at when it doesn't (1012).
fn action_base(tags: &[RawTag]) -> ActionBase {
let mut c = Cursor::new(tags);
c.next(302);
let offset = c.point(1011);
let dependent = c.int(280) != 0;
ActionBase { dependent, offset, at: c.point(1012) }
}
/// 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)> {
@@ -706,42 +551,6 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
}
/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count,
/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it
/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78
/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle
/// offset (140).
fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let n = c.count(73);
let frame = (0..n)
.map(|_| {
let x = c.real(1011);
Vec2::new(x, c.real(1021))
})
.collect();
let n = c.count(72);
let rotate_only = c.handles(331, n);
let objects = c.count(74);
let vertices = (0..objects)
.filter_map(|_| {
let h = c.handle(332)?;
let n = c.count(75);
Some((h, (0..n).map(|_| c.int(76)).collect()))
})
.collect();
for _ in 0..c.count(78) {
c.next(98);
for _ in 0..c.count(79) {
c.next(76);
}
}
let (multiplier, angle_offset) = (c.real(141), c.real(140));
(connections, ActionKind::PolarStretch { frame, vertices, rotate_only, 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).
@@ -789,13 +598,5 @@ mod tests {
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}");
let mut tags = vec![tag(74, &n.to_string())];
tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())]));
tags.push(tag(78, &n.to_string()));
tags.extend((0..n).map(|_| tag(79, &n.to_string())));
let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
}
}
File diff suppressed because it is too large Load Diff
+3 -151
View File
@@ -1,11 +1,7 @@
//! 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),
//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line
//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a
//! pentagon pointing across the alignment direction at an alignment's base point (alignment
//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]).
//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a
//! list grip offers its property's choices.
//! 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.
@@ -30,13 +26,6 @@ pub enum GripPart {
End,
/// A one-point parameter's point (a position, a visibility or lookup grip).
At,
/// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip`
/// takes it, as [`GripPart::name`] names it).
#[serde(rename = "basex-endy")]
BaseXEndY,
/// An XY parameter's corner at the end's X and the base's Y.
#[serde(rename = "basey-endx")]
BaseYEndX,
}
impl GripPart {
@@ -45,8 +34,6 @@ impl GripPart {
GripPart::Base => "base",
GripPart::End => "end",
GripPart::At => "at",
GripPart::BaseXEndY => "basex-endy",
GripPart::BaseYEndX => "basey-endx",
}
}
pub fn from_name(s: &str) -> Option<GripPart> {
@@ -54,28 +41,11 @@ impl GripPart {
"base" => Some(GripPart::Base),
"end" => Some(GripPart::End),
"at" => Some(GripPart::At),
"basex-endy" => Some(GripPart::BaseXEndY),
"basey-endx" => Some(GripPart::BaseYEndX),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::GripPart;
/// A grip is listed with the part name `blocks.reference.grip` takes back.
#[test]
fn listed_part_names_are_the_names_a_drag_takes() {
for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] {
let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
assert_eq!(listed, p.name());
assert_eq!(GripPart::from_name(&listed), Some(p));
}
}
}
/// How a grip looks and what it does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -86,13 +56,6 @@ pub enum GripShape {
Point,
/// A down-pointing triangle: click it for the property's choices.
List,
/// A circle at the end of an angle: drag it to turn the angle.
Rotation,
/// An arrow across a reflection line: click it to flip (its choices are the two states).
Flip,
/// A pentagon pointing to the left of an alignment's direction: drag it next to an object to
/// align the reference with it.
Alignment,
}
/// One grip of a dynamic block reference.
@@ -139,15 +102,6 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
used
}
/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the
/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and
/// across the line as it turns, moves or stretches. `home` and `now` aren't zero.
fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 {
let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len()));
let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x);
base + now * along + u.perp() * across
}
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
[p.x, p.y].serialize(s)
}
@@ -166,7 +120,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
};
// 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 points: HashMap<i32, Vec3> = m.grip_points.iter().copied().collect();
let mut shown_in_state: Option<HashSet<Handle>> = None;
let mut visibility_node = None;
for p in &m.parameters {
@@ -218,87 +171,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
}
}
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let id = grip(1);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place (AutoCAD draws the circle there, not at the radius'
// end), turned and moved with the radius.
let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now);
let at = Vec3::new(at.x, at.y, b.z);
let u = at - b;
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
let (at, dir) = (world(at), toward(at, u));
out.push(DynGrip {
node: p.node,
part: GripPart::End,
shape: GripShape::Rotation,
at,
dir,
property: label.clone(),
choices: Vec::new(),
});
}
}
ParameterKind::Flip { base: hb, end: he, label, states, .. } => {
let (b, e, flipped) = match r.values.get(&p.node) {
Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped),
_ => (*hb, *he, false),
};
let id = grip(0);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place, kept along and across the reflection line as the
// line turns or moves with other actions.
let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy();
let at = carried(g, home, b.xy(), now);
let u = now * (1.0 / now.len());
let across_dir = if flipped { -u.perp() } else { u.perp() };
let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Flip,
at: world(at3),
dir,
property: label.clone(),
choices: states.to_vec(),
});
}
}
// Squares at the base and the end (a polar parameter), and at the two other corners of
// the rectangle they span (an XY parameter), for the grips the parameter has; an end
// no action follows has none.
ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]);
let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])];
if matches!(p.kind, ParameterKind::Xy { .. }) {
let both = used[0] && used[1];
corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both));
corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both));
}
for (i, part, at, used) in corners {
if used && shown(p.node, grip(i)) {
out.push(DynGrip {
node: p.node,
part,
shape: GripShape::Point,
at: world(at),
dir: Vec2::ZERO,
property: label.clone(),
choices: Vec::new(),
});
}
}
}
ParameterKind::Point { at, label, .. } => {
let at = match r.values.get(&p.node) {
Some(Value::Point { at }) => *at,
@@ -317,26 +189,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
});
}
}
// At the base point, pointing to the left of the direction (as AutoCAD draws it).
ParameterKind::Alignment { base, end, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let u = (e - b).xy();
if shown(p.node, grip(0)) && u.len() > 1e-12 {
let (at, dir) = (world(b), toward(b, u.perp().to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Alignment,
at,
dir,
property: String::new(),
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)) {
+29 -106
View File
@@ -29,8 +29,6 @@ pub enum Value {
Point { at: Vec3 },
/// A two-point parameter's points.
Points { base: Vec3, end: Vec3 },
/// A flip parameter's reflection line and whether it is flipped.
Flip { base: Vec3, end: Vec3, flipped: bool },
}
/// A dynamic block reference.
@@ -53,8 +51,8 @@ pub struct CustomProperty {
/// 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, an angle,
/// a position, a flip state, or a lookup whose tables set only those.
/// 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,
}
@@ -93,9 +91,7 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
/// come before them).
/// 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() });
@@ -104,10 +100,7 @@ fn value(o: &ForeignObject) -> Option<Value> {
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)));
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
match (point(0), point(1)) {
(Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }),
(Some(base), Some(end)) => Some(Value::Points { base, end }),
(Some(at), None) => Some(Value::Point { at }),
_ => None,
@@ -129,52 +122,17 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
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();
let m = dynamic_block(d, &definition)?;
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))) {
// The record's groups alone can't tell a flip from another two-point parameter (a stray
// 70, or a flip without its state): the parameter it belongs to decides.
let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. }));
let v = match (flip, v) {
(false, Value::Flip { base, end, .. }) => Value::Points { base, end },
(true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false },
(_, v) => v,
};
values.insert(node, v);
}
}
Some(Reference { definition, values })
}
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from
/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured
/// clockwise from north, and 0.5 rad as 61.35).
pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base };
shown.rem_euclid(std::f64::consts::TAU)
}
/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of
/// [`angle_shown`].
pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base };
a.rem_euclid(std::f64::consts::TAU)
}
fn angle_text(d: &Drawing, a: f64) -> String {
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
// Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360.
let step = 10f64.powi(i32::try_from(prec).unwrap_or(0));
let shown = (angle_shown(d, a).to_degrees() * step).round() / step;
let shown = if shown >= 360.0 { shown - 360.0 } else { shown };
format!("{:.prec$}", shown + 0.0)
}
/// 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);
@@ -198,7 +156,26 @@ struct Current<'a> {
impl Current<'_> {
/// Parameter `node`'s value of property `property`, as table cells write it.
fn property(&self, node: i32, property: &str) -> Option<String> {
super::apply::property_text(self.m, self.values, node, property)
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
@@ -262,27 +239,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
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 });
}
// The distance from the base to the end, and the end's direction (AutoCAD measures it
// from the block's X axis, not from where the dynamic block has it).
ParameterKind::Polar { base: b, end: e, label, angle_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 });
let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
// How far the end is from the base along X and along Y.
ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Point { at, label, .. } => {
let at = match v {
Some(Value::Point { at }) => *at,
@@ -291,21 +247,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
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::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let now = (e - b).xy();
let zero = (*he - *hb).xy();
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
ParameterKind::Flip { label, states, .. } => {
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
let value = states[usize::from(flipped)].clone();
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), 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 });
@@ -322,8 +263,7 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
}
/// Whether every lookup table that sets lookup parameter `node` sets only what
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
/// flip states.
/// [`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 {
@@ -332,29 +272,12 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
continue;
}
any = true;
let settable = |c: &super::LookupColumn| {
m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some())
};
if !columns.iter().all(settable) {
if !columns
.iter()
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
{
return false;
}
}
any
}
#[cfg(test)]
mod tests {
use super::angle_text;
use crate::Drawing;
#[test]
fn an_angle_just_short_of_a_full_turn_shows_as_zero() {
let mut d = Drawing::new_imperial();
d.header.set_i64("AUPREC", 0);
assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0");
assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359");
d.header.set_i64("AUPREC", 2);
assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00");
assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00");
}
}
+5 -9
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
@@ -271,10 +271,8 @@ impl EntityKind {
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
// What its proxy graphics draw, so a proxy can be picked and snapped to. A filled
// shape's hatch is left out: its outline is drawn too, and the hatch's sides (72 for an
// ellipse) would offer snaps inside it.
EntityKind::Unknown(u) => u.graphics.iter().filter(|g| !matches!(g.kind, EntityKind::Hatch(_))).flat_map(|g| g.kind.prims()).collect(),
// What its proxy graphics draw, so a proxy can be picked and snapped to.
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
}
}
@@ -399,9 +397,7 @@ impl EntityKind {
t3(p);
}
if let DimKind::Linear { rotation } = &mut d.kind {
// A mirror reflects the dimension line's direction about the mirror line:
// `rot` is twice the mirror line's angle, so `a` lands at `rot - a`.
*rotation = cadcraft_geom::norm_angle(if mirror { rot - *rotation } else { *rotation + rot });
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
}
d.marks.transform(&t3, rot, s, mirror);
d.block = None;
@@ -629,7 +625,7 @@ impl EntityKind {
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.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(),
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(),
-73
View File
@@ -1,6 +1,3 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -145,43 +142,6 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -231,12 +191,6 @@ fn one_u() -> u32 {
}
impl Insert {
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
}
/// Block-to-world transform (2D part).
pub fn transform(&self, base: Vec2) -> Mat3 {
Mat3::translate(self.insert.xy())
@@ -244,31 +198,4 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+1 -3
View File
@@ -100,9 +100,7 @@ impl DimMarks {
/// Transform the points and angles (part of [`super::EntityKind::transform`]).
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
if let Some(a) = &mut self.oblique {
// A mirror reflects a direction about the mirror line: `rot` is the transformed X
// axis (twice the mirror line's angle), so a direction `a` lands at `rot - a`.
*a = cadcraft_geom::norm_angle(if mirror { rot - *a } else { *a + rot });
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
}
if let Some(j) = &mut self.jog_line {
t3(j);
+59 -753
View File
@@ -9,8 +9,7 @@
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
//! polylines, materials) are skipped.
use super::{Arc, Circle, Common, Ellipse, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use crate::RawTag;
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use cadcraft_color::{Color, Rgb};
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
@@ -36,20 +35,16 @@ pub struct ProxyTables {
}
impl Unknown {
/// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in
/// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size
/// group is the first after the `AcDbProxyEntity` subclass marker (from the start in a record
/// without one), so a 92 or 160 among the entity's own groups before it isn't taken for it.
/// An entity of another type CADCraft keeps as read holds them in its `AcDbEntity` part when
/// it was saved with a picture of itself (a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION, or an
/// object of another application; #3438). Empty for an entity without graphics and for one
/// whose data isn't hex.
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
/// without graphics and for one whose data isn't hex.
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
let Some((at, size)) = self.graphics_size_group() else { return Vec::new() };
// Reserve what the 310 groups hold, not what the size claims: a size far past the data
// would otherwise reserve up to MAX_BYTES for nothing.
let held: usize = self.tags.iter().skip(at + 1).take_while(|t| t.code == 310).map(|t| t.value.trim().len() / 2).sum();
let mut out = Vec::with_capacity(size.min(held));
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return Vec::new();
}
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
let mut out = Vec::with_capacity(size);
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
// Damaged data draws nothing rather than a picture cut at a guess.
if !push_hex(&mut out, &t.value) {
@@ -64,232 +59,6 @@ impl Unknown {
}
}
impl Unknown {
/// The `*D` block a dimension CADCraft keeps as read names (group 2 of its `AcDbDimension`
/// part): a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION. AutoCAD draws a dimension from that
/// block, so CADCraft draws it from there too, and saving keeps it (#3438, #1161). `None`
/// for other records.
pub fn dimension_block(&self) -> Option<&str> {
let m = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbDimension")?;
self.tags[m + 1..].iter().take_while(|t| t.code != 100).find(|t| t.code == 2).map(|t| t.value.trim()).filter(|n| !n.is_empty())
}
/// Where the proxy graphics size group (92, or 160 in newer files) is, and the size it gives
/// (at most [`MAX_BYTES`]): in an ACAD_PROXY_ENTITY the first after the `AcDbProxyEntity`
/// marker, in another kept entity the one in its `AcDbEntity` part.
fn graphics_size_group(&self) -> Option<(usize, usize)> {
let at = if self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
let from = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbProxyEntity").map_or(0, |m| m + 1);
self.tags.iter().skip(from).position(|t| t.code == 92 || t.code == 160).map(|i| from + i)
} else {
// The groups of the AcDbEntity subclass, up to the entity's own subclass marker.
self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbEntity").and_then(|m| {
let own = &self.tags[m + 1..];
own.iter().take_while(|t| t.code != 100).position(|t| t.code == 92 || t.code == 160).map(|i| m + 1 + i)
})
}?;
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
Some((at, size))
}
/// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned
/// into the written LAYER table `written`, by name; everything else as read. The name of an
/// index is the one the record's own decoded graphics draw on after it (so a proxy copied from
/// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no
/// drawn entity follows takes the name from the file's table `read` (see
/// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own
/// layer, as in a block); an index past the table, or one of a record without a name, stays
/// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups
/// that hold the declared size are read and rewritten. `None` when no index changes, or the
/// graphics aren't readable.
pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option<Vec<RawTag>> {
// Only a proxy entity's own graphics: a kept dimension draws from its block instead.
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return None;
}
let (at, size) = self.graphics_size_group()?;
let (mut bytes, mut groups) = (Vec::new(), Vec::new());
for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) {
if bytes.len() >= size {
break;
}
let before = bytes.len();
if !push_hex(&mut bytes, &self.tags[i].value) {
return None;
}
groups.push((i, bytes.len() - before));
}
let end = size.min(bytes.len());
// The ATTRIBUTE_LAYER chunks: where each index sits.
let mut refs: Vec<(usize, u32)> = Vec::new();
let mut chunk = 8usize;
while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) {
let len = len as usize;
if len < 8 || chunk.saturating_add(len) > end {
break;
}
if kind == 16
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
{
refs.push((chunk + 8, i));
}
chunk += len;
}
if refs.is_empty() {
return None;
}
let indices: Vec<u32> = refs.iter().map(|r| r.1).collect();
let learned = self.layers_by_index(&bytes[..end], &indices);
if read.is_empty() && learned.is_empty() {
return None;
}
// Each written name's first place, found once.
let mut place: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for (p, n) in written.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
}
let zero = place.get("0").copied();
let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX));
let mut resolved: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
let mut changed = false;
for (offset, i) in refs {
let j = *resolved.entry(i).or_insert_with(|| {
let name = match learned.get(&i) {
Some(name) => name.as_deref(),
None => read.get(i as usize).map(String::as_str),
};
match name.filter(|n| !n.is_empty()) {
Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
None if i >= past => i,
None => past,
}
});
if j != i {
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
changed = true;
}
}
if !changed {
return None;
}
let mut tags = self.tags.clone();
let mut from = 0;
for (g, n) in groups {
tags[g].value = bytes[from..from + n].iter().map(|b| format!("{b:02X}")).collect();
from += n;
}
Some(tags)
}
/// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in
/// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the
/// same entities in the same order, so each one's marker meets its real layer. `None` for an
/// index after which the graphics stay on the layer before (one past the table it was read
/// with). An index above 65,535 isn't named here (it resolves through the file's table, like
/// one no entity follows). Empty when the graphics don't match
/// (not decoded from these bytes); an index whose entities disagree is left out.
fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap<u32, Option<String>> {
/// What the entities after an index say about it.
enum Seen {
/// They are on this layer, and the ones before them weren't.
Named(String),
/// They are on the same layer as the ones before them: the index keeps that layer,
/// or names it.
Kept(String),
/// It keeps the layer before (two kept observations on different layers).
Keeps,
}
const MAX: u32 = 65_535;
let mut out: std::collections::HashMap<u32, Option<String>> = std::collections::HashMap::new();
if self.graphics.is_empty() {
return out;
}
let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0);
let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() };
let marked = proxy_entities(bytes, &markers, Handle(0));
if marked.len() != self.graphics.len() {
return out;
}
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
let mut seen: std::collections::HashMap<u32, Seen> = std::collections::HashMap::new();
let mut conflict = std::collections::HashSet::new();
let mut before: Option<(&str, &str)> = None;
for (m, g) in marked.iter().zip(&self.graphics) {
let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str());
let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark);
let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real));
before = Some((mark, real));
let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok()) else { continue };
if !changed_here {
// The same marker on another real layer: an index in between (one past the table
// the marker decoding doesn't see as such) changed it, so this one can't be named.
if !kept {
conflict.insert(i);
}
continue;
}
let real = real.to_string();
let merged = match (seen.remove(&i), kept) {
(None, false) => Some(Seen::Named(real)),
(None, true) => Some(Seen::Kept(real)),
(Some(Seen::Named(a) | Seen::Kept(a)), false) | (Some(Seen::Named(a)), true) if same(&a, &real) => Some(Seen::Named(a)),
(Some(Seen::Kept(a)), true) => Some(if same(&a, &real) { Seen::Kept(a) } else { Seen::Keeps }),
(Some(Seen::Keeps), true) => Some(Seen::Keeps),
_ => None,
};
match merged {
Some(s) => {
seen.insert(i, s);
}
None => {
conflict.insert(i);
}
}
}
for (i, s) in seen {
if !conflict.contains(&i) {
out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None });
}
}
out
}
}
impl crate::Drawing {
/// Rename layer `old` to `new` where proxy graphics use it: in [`crate::Drawing::proxy_layers`],
/// so saving finds the layer under its new name, and in the decoded graphics, which draw on
/// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the
/// target, as its objects do) and LAYDEL with layer 0.
pub fn rename_proxy_layer(&mut self, old: &str, new: &str) {
for n in &mut self.proxy_layers {
if n.eq_ignore_ascii_case(old) {
*n = new.to_string();
}
}
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old)));
let fix = |e: &mut Entity| {
if let EntityKind::Unknown(u) = &mut e.kind {
for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) {
g.common.layer = new.to_string();
}
}
};
let mut stores: Vec<&mut crate::EntityStore> = vec![&mut self.model];
stores.extend(self.layouts.iter_mut().map(|l| &mut l.entities));
for b in self.blocks.values_mut() {
if b.entities.iter().any(|e| uses(e)) {
stores.push(&mut std::sync::Arc::make_mut(b).entities);
}
}
for store in stores {
let hs: Vec<Handle> = store.iter().filter(|e| uses(e)).map(|e| e.handle).collect();
for h in hs {
store.modify(h, fix);
}
}
}
}
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
let digits: Vec<u8> = s.trim().bytes().collect();
@@ -330,7 +99,6 @@ struct Decoder<'a> {
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
/// Whether polygons and circles that follow are filled (ATTRIBUTE_FILL).
fill: bool,
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
matrices: Vec<[f64; 12]>,
@@ -351,9 +119,9 @@ impl Decoder<'_> {
// CIRCLE_3P: three points on it.
3 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
&& let Some(fit) = Fit3::through(p1, p2, p3)
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
{
self.circle_in(fit.center, fit.radius, fit.e1, fit.e2);
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
}
}
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
@@ -365,12 +133,11 @@ impl Decoder<'_> {
// CIRCULAR_ARC_3P: start, a point on the arc, end.
5 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
self.arc_3p_local(p1, p2, p3);
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
}
}
// POLYLINE and POLYGON: a count, then the points; POLYLINE_WITH_NORMAL: a count, the
// points and a normal (the dimension lines of a LARGE_RADIAL_DIMENSION's picture).
6 | 7 | 32 => {
// POLYLINE and POLYGON: a count, then the points.
6 | 7 => {
let Some(n) = b.u32() else { return };
let n = (n as usize).min(MAX_VERTICES);
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
@@ -425,10 +192,9 @@ impl Decoder<'_> {
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
}
}
// ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record
// without a name, leaves the layer.
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
16 => {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
self.pen.layer = name.clone();
}
}
@@ -438,18 +204,12 @@ impl Decoder<'_> {
if let Some(i) = b.u32() {
self.pen.linetype = match i {
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
// ATTRIBUTE_FILL: a trait like the colour, in force until the next one: 1 fills the
// polygons and circles that follow, 2 (and anything else) doesn't (AcGiFillType
// kAcGiFillAlways, kAcGiFillNever).
20 => {
if let Some(f) = b.u32() {
self.fill = f == 1;
}
}
// ATTRIBUTE_FILL: the next polygon is filled.
20 => self.fill = b.u32().is_some_and(|f| f != 0),
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
22 => {
if let Some(v) = b.u32() {
@@ -517,60 +277,12 @@ impl Decoder<'_> {
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
}
/// Where the pushed matrices take `c` and the unit vectors `e1`, `e2` of a circle's plane: the
/// circle of radius 1 around `c` is drawn as `c' + u·cos a + v·sin a`. The vectors go through
/// the matrices' linear parts only, so a small scale isn't lost against a large translation.
fn axes(&self, c: Vec3, e1: Vec3, e2: Vec3) -> (Vec2, Vec2, Vec2) {
(self.xy(c), self.linear(e1), self.linear(e2))
}
/// Direction `v` through the pushed matrices' linear parts, innermost first, in the XY plane.
fn linear(&self, v: Vec3) -> Vec2 {
let mut v = v;
for m in self.matrices.iter().rev() {
v = Vec3::new(m[0] * v.x + m[1] * v.y + m[2] * v.z, m[4] * v.x + m[5] * v.y + m[6] * v.z, m[8] * v.x + m[9] * v.y + m[10] * v.z);
}
v.xy()
}
/// A full circle around `c`, through the pushed matrices: an ellipse when they scale its
/// plane unevenly or shear it. While ATTRIBUTE_FILL is on, a solid hatch under it: AutoCAD
/// draws a filled shape's outline too, with its lineweight.
/// A full circle around `c`, through the pushed matrices.
fn circle(&mut self, c: Vec3, r: f64) {
self.circle_in(c, r, X, Y);
}
/// The circle of radius `r` around `c` in the plane of the unit vectors `e1` and `e2`, as
/// `circle` draws one in the chunk's XY plane.
fn circle_in(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3) {
let (at, u, v) = self.axes(c, e1, e2);
if !(r.is_finite() && r > 0.0 && at.is_finite()) {
return;
}
match round(u * r, v * r) {
Some(r) => {
if self.fill {
// Two half-circle arcs (bulge 1).
let side = |p: Vec2| PolyVertex { p, bulge: 1.0, start_width: 0.0, end_width: 0.0 };
self.solid(vec![side(at + Vec2::new(r, 0.0)), side(at - Vec2::new(r, 0.0))]);
}
self.push(EntityKind::Circle(Circle { center: at.to3(0.0), radius: r }));
}
None => {
let Some(e) = ellipse(at, u * r, v * r, 0.0, std::f64::consts::TAU) else {
return self.edge_on(at, u * r, v * r, 0.0, std::f64::consts::TAU);
};
if self.fill {
// Bulges draw circular arcs only: the fill follows the ellipse in 72
// straight sides, finer than a plotted pixel at the sizes proxies use.
let side = |i: u32| {
let a = std::f64::consts::TAU * f64::from(i) / 72.0;
PolyVertex { p: at + u * (r * a.cos()) + v * (r * a.sin()), bulge: 0.0, start_width: 0.0, end_width: 0.0 }
};
self.solid((0..72).map(side).collect());
}
self.push(EntityKind::Ellipse(e));
}
let r = r * self.scale();
let c = self.xy(c);
if r.is_finite() && r > 0.0 && c.is_finite() {
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
}
}
@@ -584,62 +296,12 @@ impl Decoder<'_> {
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
let a0 = start.y.atan2(start.x);
let a1 = a0 + dir * sweep;
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
let mid = on((a0 + a1) / 2.0);
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
return self.circle(c, r);
}
self.arc_between(c, r, X, Y, a0, a1);
}
/// The arc of radius `r` around `c` from angle `a0` to `a1` (from `e1` towards `e2`, the unit
/// vectors of its plane), either way round, through the pushed matrices: an elliptical arc
/// when they don't keep it round.
fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) {
let (at, u, v) = self.axes(c, e1, e2);
let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin());
if round(u * r, v * r).is_some() {
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
}
match ellipse(at, u * r, v * r, a0.min(a1), a0.max(a1)) {
Some(e) => self.push(EntityKind::Ellipse(e)),
None => self.edge_on(at, u * r, v * r, a0.min(a1), a0.max(a1)),
}
}
/// A circle or arc `c + u·cos a + v·sin a` (`a` from `a0` to `a1`) seen edge-on: `u` and `v`
/// on one line, so it draws as the line between its two farthest points along it.
fn edge_on(&mut self, c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) {
use std::f64::consts::{PI, TAU};
let d = if u.len() >= v.len() { u } else { v };
if !(c.is_finite() && d.is_finite() && v.is_finite() && u.is_finite() && d.len() > 0.0) {
return;
}
let d = d * (1.0 / d.len());
// Along d the point is at R·cos(a − φ): farthest out at φ and φ + π, where the sweep has them.
let phi = v.dot(d).atan2(u.dot(d));
let inside = |a: f64| (a - a0).rem_euclid(TAU) <= a1 - a0;
let on = |a: f64| c + u * a.cos() + v * a.sin();
let mut ends = [a0, a1, phi, phi + PI].into_iter().filter(|&a| a == a0 || a == a1 || inside(a)).map(on).map(|p| (p - c).dot(d));
let first = ends.next().unwrap_or(0.0);
let (lo, hi) = ends.fold((first, first), |(lo, hi), t| (lo.min(t), hi.max(t)));
if hi > lo {
self.push(EntityKind::Line(Line { a: (c + d * lo).to3(0.0), b: (c + d * hi).to3(0.0) }));
}
}
/// The arc from `p1` through `p2` to `p3`, chunk coordinates: fitted in the plane of the
/// three points and drawn through the pushed matrices, which may make it elliptical.
fn arc_3p_local(&mut self, p1: Vec3, p2: Vec3, p3: Vec3) {
if self.matrices.is_empty() && p1.z == p2.z && p2.z == p3.z {
return self.arc_3p(p1.xy(), p2.xy(), p3.xy());
}
let Some(fit) = Fit3::through(p1, p2, p3) else {
return self.polyline(vec![self.xy(p1), self.xy(p3)], false);
};
let (a1, a2, a3) = (fit.angle(p1), fit.angle(p2), fit.angle(p3));
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
let (from, sweep) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, ccw(a1, a3)) } else { (a3, ccw(a3, a1)) };
self.arc_between(fit.center, fit.radius, fit.e1, fit.e2, from, from + sweep);
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
}
/// The arc from `p1` through `p2` to `p3`.
@@ -655,15 +317,29 @@ impl Decoder<'_> {
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
}
/// A polyline, or a closed polygon: on a solid hatch while ATTRIBUTE_FILL is on (the outline
/// is drawn too, as for a circle).
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
/// which applies to this one polygon only.
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
let fill = std::mem::take(&mut self.fill);
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
return;
}
if polygon && self.fill && pts.len() >= 3 {
if polygon && fill && pts.len() >= 3 {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
self.solid(vertices);
return self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
}
match pts.as_slice() {
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
@@ -674,29 +350,6 @@ impl Decoder<'_> {
}
}
/// A solid hatch with the one boundary `vertices`.
fn solid(&mut self, vertices: Vec<PolyVertex>) {
// At the cap the fill gives way to the outline that follows it: a shape left with only
// its fill couldn't be picked or snapped to.
if self.out.len() + 1 >= MAX_ENTITIES {
return;
}
self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
}
/// A single-line text, its style the first one whose font file the chunk names.
fn text(&mut self, t: TextChunk) {
let TextChunk { p, dir, height, width, oblique, value, font } = t;
@@ -754,90 +407,17 @@ struct TextChunk {
font: String,
}
/// The radius of the circle with conjugate radii `u` and `v` when they are one: as long as each
/// other and at right angles (a matrix that turns, mirrors and scales evenly).
fn round(u: Vec2, v: Vec2) -> Option<f64> {
let (lu, lv) = (u.len(), v.len());
let tol = 1e-9 * lu.max(lv);
((lu - lv).abs() <= tol && u.dot(v).abs() <= tol * lu.max(lv) && lu.is_finite() && lu > 0.0).then_some(lu)
}
/// The ellipse `c + u·cos a + v·sin a` for `a` from `a0` to `a1` (counter-clockwise in the
/// parameter): its axes from the conjugate radii `u` and `v`, the arc carried over to the
/// ellipse's own parameter (counter-clockwise from its major axis).
fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option<Ellipse> {
use std::f64::consts::{FRAC_PI_2, TAU};
// c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles.
let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2());
let p = u * t.cos() + v * t.sin();
let q = v * t.cos() - u * t.sin();
// The ellipse turns counter-clockwise with its parameter only when q is p turned left;
// a mirroring matrix reverses it.
let mirrored = p.cross(q) < 0.0;
let q = if mirrored { -q } else { q };
let (mut s0, mut s1) = if mirrored { (t - a1, t - a0) } else { (a0 - t, a1 - t) };
// The major axis is the longer of p and q.
let (major, minor) = if q.len() > p.len() {
s0 -= FRAC_PI_2;
s1 -= FRAC_PI_2;
(q, p.len())
} else {
(p, q.len())
};
let ratio = minor / major.len();
if !(c.is_finite() && major.is_finite() && major.len() > 0.0 && ratio.is_finite() && ratio > 0.0) {
return None;
}
let full = (a1 - a0) >= TAU - 1e-9;
let (start, end) = if full { (0.0, TAU) } else { (s0.rem_euclid(TAU), s1.rem_euclid(TAU)) };
Some(Ellipse { center: c.to3(0.0), major: major.to3(0.0), ratio, start, end })
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
cadcraft_geom::Circle::from_3_points(a, b, c).filter(|f| f.radius > 0.0).map(|f| (f.center, f.radius))
}
const X: Vec3 = Vec3 { x: 1.0, y: 0.0, z: 0.0 };
const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 };
/// The circle through three points in space: its centre, radius and the unit vectors `e1`, `e2`
/// of its plane. For points of equal `z` they are X and Y, so angles are the chunk's.
struct Fit3 {
center: Vec3,
radius: f64,
e1: Vec3,
e2: Vec3,
}
impl Fit3 {
/// The fit, if the points aren't on one line (relative to the triangle's size, so it holds at
/// any scale).
fn through(p1: Vec3, p2: Vec3, p3: Vec3) -> Option<Fit3> {
let (u, v) = (p2 - p1, p3 - p1);
let w = u.cross(v);
let w2 = w.dot(w);
if !(w2.is_finite() && w.len() > 1e-12 * (u.len() * v.len()) && w2 > 0.0) {
return None;
}
// The centre in point-relative coordinates: ((|u|² v − |v|² u) × w) / (2 |w|²).
let center = p1 + (v * u.dot(u) - u * v.dot(v)).cross(w) * (0.5 / w2);
let radius = (p1 - center).len();
// The plane's normal towards +Z (which way the arc turns comes from the middle point), and
// X (or Y) laid into the plane.
let up = if w.z < 0.0 { -1.0 } else { 1.0 };
let n = w * (up / w.len());
let along = |a: Vec3| a - n * a.dot(n);
let e1 = if along(X).len() > 1e-6 { along(X).normalized() } else { along(Y).normalized() };
let e2 = n.cross(e1);
(center.is_finite() && radius.is_finite() && radius > 0.0 && e2.is_finite()).then_some(Fit3 { center, radius, e1, e2 })
}
/// The angle of `p` around the centre, from `e1` towards `e2`.
fn angle(&self, p: Vec3) -> f64 {
let d = p - self.center;
d.dot(self.e2).atan2(d.dot(self.e1))
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
if !d.is_finite() || d.abs() < 1e-12 {
return None;
}
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
let center =
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
let r = (a - center).len();
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
}
/// The little-endian u32 at `at`, if `bytes` holds one there.
@@ -1011,160 +591,15 @@ mod tests {
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
}
/// ATTRIBUTE_FILL is a trait like the colour: 1 (kAcGiFillAlways) fills every polygon and
/// circle until a 2 (kAcGiFillNever) ends it, whatever is drawn in between. AutoCAD
/// Mechanical writes 2 before its balloons' circles and 1 before their arrowheads and dots.
#[test]
fn fill_is_a_trait_until_turned_off() {
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
let mut tri = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
tri.extend(pt(x, y));
}
let mut line = 2u32.to_le_bytes().to_vec();
line.extend(pt(0.0, 0.0));
line.extend(pt(1.0, 0.0));
let mut dot = pt(5.0, 5.0);
dot.extend(0.5f64.to_le_bytes());
dot.extend(pt(0.0, 0.0));
let (on, off) = (chunk(20, &1u32.to_le_bytes()), chunk(20, &2u32.to_le_bytes()));
let es = proxy_entities(
&graphics(&[on, chunk(6, &line), chunk(7, &tri), chunk(2, &dot), chunk(7, &tri), off, chunk(7, &tri), chunk(2, &dot)]),
&tables(),
Handle(1),
);
let kinds: Vec<&str> = es.iter().map(|e| e.kind.type_name()).collect();
// A filled shape is a solid hatch with its outline on top.
assert_eq!(kinds, ["Line", "Hatch", "Polyline", "Hatch", "Circle", "Hatch", "Polyline", "Polyline", "Circle"]);
assert!(matches!(&es[1].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[2].kind, EntityKind::LwPolyline(p) if p.closed));
// The filled circle: two half-circle arcs around its centre.
let disc: Vec<(Vec2, f64)> = match &es[3].kind {
EntityKind::Hatch(h) => h.loops[0].vertices.iter().map(|v| (v.p, v.bulge)).collect(),
other => panic!("{other:?}"),
};
assert_eq!(disc, [(Vec2::new(5.5, 5.0), 1.0), (Vec2::new(4.5, 5.0), 1.0)]);
assert!(matches!(&es[6].kind, EntityKind::LwPolyline(p) if p.closed));
}
/// A circle or arc under a matrix that scales its plane unevenly is an ellipse, measured
/// and snapped as one; one that scales evenly stays a circle or arc.
#[test]
fn circles_and_arcs_under_an_uneven_matrix_are_ellipses() {
use std::f64::consts::{FRAC_PI_2, PI, TAU};
let push = |sx: f64, sy: f64| {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3]) = (sx, sy, 1.0, 1.0, 10.0);
chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
};
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let quarter = {
let mut a = pt(0.0, 0.0);
a.extend(1.0f64.to_le_bytes());
a.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
a.extend(pt(1.0, 0.0));
a.extend(FRAC_PI_2.to_le_bytes());
a.extend(0u32.to_le_bytes());
a
};
// Three points of the same quarter arc, as CIRCULAR_ARC_3P gives them.
let h = std::f64::consts::FRAC_1_SQRT_2;
let quarter_3p: Vec<u8> = [pt(1.0, 0.0), pt(h, h), pt(0.0, 1.0)].concat();
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let ell = |e: &Entity| match &e.kind {
EntityKind::Ellipse(e) => (e.center, e.major, e.ratio, e.start, e.end),
other => panic!("{other:?}"),
};
let es = proxy_entities(&graphics(&[push(2.0, 1.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1));
let (c, major, ratio, start, end) = ell(&es[0]);
assert!(c == Vec3::new(10.0, 0.0, 0.0) && near(major.x.abs(), 2.0) && near(major.y, 0.0) && near(ratio, 0.5) && (start, end) == (0.0, TAU));
for e in &es[1..] {
let (_, major, ratio, start, end) = ell(e);
// The major axis may point either way along x; the arc runs from (12, 0) to (10, 1).
let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin());
assert!((at(start) - Vec2::new(12.0, 0.0)).len() < 1e-9 && (at(end) - Vec2::new(10.0, 1.0)).len() < 1e-9, "{start} {end}");
assert!(near((end - start).rem_euclid(TAU), FRAC_PI_2));
}
// Mirrored along x and stretched: the quarter arc runs from (10, 1) to (8, 0).
let es = proxy_entities(&graphics(&[push(-2.0, 1.0), chunk(4, &quarter)]), &tables(), Handle(1));
let (_, major, ratio, start, end) = ell(&es[0]);
let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin());
assert!((at(start) - Vec2::new(10.0, 1.0)).len() < 1e-9 && (at(end) - Vec2::new(8.0, 0.0)).len() < 1e-9, "{start} {end}");
// A filled circle under it: a solid hatch along the ellipse, under the ellipse.
let fill = chunk(20, &1u32.to_le_bytes());
let es = proxy_entities(&graphics(&[push(2.0, 1.0), fill, chunk(2, &circle)]), &tables(), Handle(1));
match (&es[0].kind, &es[1].kind) {
(EntityKind::Hatch(h), EntityKind::Ellipse(_)) => {
let xs = h.loops[0].vertices.iter().map(|v| v.p.x);
let (lo, hi) = xs.fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x)));
assert!(near(lo, 8.0) && near(hi, 12.0), "{lo} {hi}");
}
other => panic!("{other:?}"),
}
// Picked and snapped by the ellipse only, not the hatch's sides.
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: es };
let prims = EntityKind::Unknown(u).prims();
assert!(matches!(prims.as_slice(), [crate::entity::Prim::Ellipse(_)]), "{prims:?}");
// A tiny scale under a far translation keeps the circle: radius 1e8 at scale 1e-8 is 1.
let mut far = [0.0f64; 16];
(far[0], far[5], far[10], far[15], far[3], far[7]) = (1e-8, 1e-8, 1.0, 1.0, 1e9, 1e9);
let far = chunk(29, &far.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let mut big = pt(0.0, 0.0);
big.extend(1e8f64.to_le_bytes());
big.extend(pt(0.0, 0.0));
let es = proxy_entities(&graphics(&[far, chunk(2, &big)]), &tables(), Handle(1));
assert!(matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Circle(c) if (c.radius - 1.0).abs() < 1e-6)), "{es:?}");
// Even scaling, mirrored or not, keeps circles and arcs.
let es = proxy_entities(&graphics(&[push(-3.0, 3.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if near(c.radius, 3.0)));
for e in &es[1..] {
let angle = |a: f64, b: f64| near((a - b).rem_euclid(TAU).min((b - a).rem_euclid(TAU)), 0.0);
assert!(matches!(&e.kind, EntityKind::Arc(a) if near(a.radius, 3.0) && angle(a.start, FRAC_PI_2) && angle(a.end, PI)), "{e:?}");
}
}
/// Three-point chunks are fitted in the plane of their points, then mapped: a circle across XY
/// turned into it, points far smaller than the scale that enlarges them, and circles and arcs
/// seen edge-on.
#[test]
fn three_point_chunks_fit_in_their_own_plane() {
use std::f64::consts::TAU;
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let p3 = |p: [f64; 3]| p.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
let mat = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let turn = mat([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
let across = [p3([0.0, 1.0, 0.0]), p3([0.0, 0.0, 1.0]), p3([0.0, -1.0, 0.0])].concat();
let tiny = mat([1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1.0]);
let small = [p3([1e-7, 0.0, 0.0]), p3([0.0, 1e-7, 0.0]), p3([-1e-7, 0.0, 0.0])].concat();
// The arc's half is the one through the middle point.
for (m, pts, mid) in [(turn, across.clone(), Vec2::new(1.0, 0.0)), (tiny, small, Vec2::new(0.0, 1.0))] {
let es = proxy_entities(&graphics(&[m, chunk(3, &pts), chunk(5, &pts)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center.xy().len() < 1e-9 && near(c.radius, 1.0)), "{es:?}");
match &es[1].kind {
EntityKind::Arc(a) => {
let m = a.start + (a.end - a.start).rem_euclid(TAU) / 2.0;
assert!(near(a.radius, 1.0) && (Vec2::new(m.cos(), m.sin()) - mid).len() < 1e-9, "{a:?}");
}
other => panic!("{other:?}"),
}
}
// Seen edge-on (in a vertical plane, no matrix) a circle or arc is a line over all it
// covers in plan: for the arc through (0, 1) from (0, 0.6) to (0, 0.6), beyond its ends.
let edge = |pts: Vec<u8>, kind: u32| match proxy_entities(&graphics(&[chunk(kind, &pts)]), &tables(), Handle(1)).as_slice() {
[Entity { kind: EntityKind::Line(l), .. }] => {
let (lo, hi) = (l.a.y.min(l.b.y), l.a.y.max(l.b.y));
assert!(near(l.a.x, 0.0) && near(l.b.x, 0.0), "{l:?}");
(lo, hi)
}
other => panic!("{other:?}"),
};
let (lo, hi) = edge(across.clone(), 3);
assert!(near(lo, -1.0) && near(hi, 1.0));
let (lo, hi) = edge(across, 5);
assert!(near(lo, -1.0) && near(hi, 1.0));
let (lo, hi) = edge([p3([0.0, 0.6, 0.8]), p3([0.0, 1.0, 0.0]), p3([0.0, 0.6, -0.8])].concat(), 5);
assert!(near(lo, 0.6) && near(hi, 1.0), "{lo} {hi}");
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
}
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
@@ -1240,137 +675,8 @@ mod tests {
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
assert!(other.proxy_graphics_bytes().is_empty());
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u.clone() };
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
assert!(bad.proxy_graphics_bytes().is_empty());
// The size group is the first after the AcDbProxyEntity marker: a 160 or 92 before it
// belongs to the entity's common data.
let marked = Unknown {
tags: vec![
tag(100, "AcDbEntity"),
tag(160, "2"),
tag(310, "EEEE"),
tag(100, "AcDbProxyEntity"),
tag(90, "498"),
tag(92, "3"),
tag(310, "010203"),
],
..u.clone()
};
assert_eq!(marked.proxy_graphics_bytes(), [1, 2, 3]);
// A size far past the data gives the data there is.
let short = Unknown { tags: vec![tag(92, "16000000"), tag(310, "0102")], ..u };
assert_eq!(short.proxy_graphics_bytes(), [1, 2]);
}
/// Another entity saved with a picture of itself (a LARGE_RADIAL_DIMENSION) holds it in its
/// AcDbEntity part; a 92 among its own groups after that isn't taken for it. Its dimension
/// lines are POLYLINE_WITH_NORMAL chunks (type 32).
#[test]
fn a_kept_entity_draws_the_picture_in_its_acdbentity_part() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let mut line = 2u32.to_le_bytes().to_vec();
line.extend(pt(250.0, 150.0));
line.extend(pt(290.0, 190.0));
line.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
let g = graphics(&[chunk(32, &line)]);
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let size = g.len().to_string();
let u = Unknown {
dxf_type: "LARGE_RADIAL_DIMENSION".into(),
tags: vec![
tag(100, "AcDbEntity"),
tag(8, "0"),
tag(92, &size),
tag(310, &hex),
tag(100, "AcDbDimension"),
tag(2, "*D1"),
tag(100, "AcDbRadialDimensionLarge"),
tag(40, "0.785398"),
],
graphics: Vec::new(),
};
assert_eq!(u.proxy_graphics_bytes(), g);
let es = proxy_entities(&u.proxy_graphics_bytes(), &tables(), Handle(1));
assert!(
matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Line(l) if l.a == Vec3::new(250.0, 150.0, 0.0) && l.b == Vec3::new(290.0, 190.0, 0.0)))
);
// Without graphics in the AcDbEntity part, a 92 in the entity's own data is not one.
let own = Unknown { tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbSomething"), tag(92, "4"), tag(310, "01020304")], ..u };
assert!(own.proxy_graphics_bytes().is_empty());
}
/// Saving renames the layer indices by name into the written table, reading only the 310
/// groups the declared size needs: a damaged group after them doesn't stop it.
#[test]
fn layer_indices_follow_the_written_table() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]);
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let read: Vec<String> = ["0", "A", "B", "C"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex), tag(310, "GG")],
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics[0].common.layer, "B");
let written: Vec<String> = ["0", "B", "C"].map(String::from).to_vec();
let tags = u.with_proxy_layers(&read, &written).expect("remapped");
let again = Unknown { tags, ..u.clone() };
assert_eq!(
proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer,
"B"
);
assert_eq!(again.tags[3].value, "GG", "the group after the graphics is kept as read");
}
/// An index whose graphics stay on the layer before (99 here, past the table) doesn't make
/// the index before it (3) look contradictory when that one comes again; an index above
/// 65,535 isn't named (it resolves through the file's table), and the others still are.
#[test]
fn indices_are_named_around_kept_layers_and_huge_indices() {
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let read: Vec<String> = ["0", "A", "C", "B"].map(String::from).to_vec();
let tables = ProxyTables { layers: read, ..ProxyTables::default() };
let named = |indices: &[u32]| {
let mut chunks = Vec::new();
for &i in indices {
chunks.push(chunk(16, &i.to_le_bytes()));
chunks.push(chunk(2, &circle));
}
let g = graphics(&chunks);
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) };
let mut learned: Vec<(u32, Option<String>)> = u.layers_by_index(&g, indices).into_iter().collect();
learned.sort();
learned
};
assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]);
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]);
// Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4
// keeps A): both circles follow index 4 in the marker decoding, on different layers.
let g = graphics(&[
chunk(16, &4u32.to_le_bytes()),
chunk(2, &circle),
chunk(16, &1u32.to_le_bytes()),
chunk(16, &4u32.to_le_bytes()),
chunk(2, &circle),
]);
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)],
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::<Vec<_>>(), ["0", "A"]);
assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named");
// Saved with the same table, nothing changes, so both circles stay where they are.
assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
+38 -88
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -271,8 +271,7 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
/// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked.
/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool {
// Attribute definitions are not drawn in an insert (its attribs are, see below), except
// constant ones, which the insert's bounds add on their own.
// Attribute definitions are not drawn in an insert (its attribs are, see below).
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
}
@@ -283,79 +282,13 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
}
}
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`.
fn contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
for be in blk.entities.iter() {
match &be.kind {
EntityKind::AttDef(a)
if a.constant
&& attmode != 0
&& (!a.invisible || attmode == 2)
&& be.common.visible
&& layer_counts(d, &be.common.layer, off_counts) =>
{
c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation())));
}
_ if in_block_visible(d, be, off_counts) => c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, off_counts)),
_ => {}
}
}
blocks.insert(key, c);
}
blocks.get(&key)
}
/// The box of a constant attribute definition's value, as a block reference draws it: upright
/// when the definition matches the layout's orientation, like other text (#2498).
fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
let turn = |r: f64| if upright { 0.0 } else { r };
match a.multiline_text() {
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, a.text.value.chars().count()),
_ => Bounds2::EMPTY,
}
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
}
/// A text that draws no glyph (empty, or only blanks and non-breaking spaces) takes no room.
@@ -411,9 +344,9 @@ pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
#[derive(Default)]
pub struct BlockBoundsCache<'a> {
/// By block name and depth, block contents on layers turned off left out ([`entity_bounds`]).
drawn: HashMap<(&'a str, usize), Contents<'a>>,
drawn: HashMap<(&'a str, usize), Bounds2>,
/// The same with those contents counted ([`extent_bounds`]).
extents: HashMap<(&'a str, usize), Contents<'a>>,
extents: HashMap<(&'a str, usize), Bounds2>,
}
/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
@@ -426,7 +359,7 @@ pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBou
bounds_of(d, e, 0, true, &mut cache.extents)
}
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>) -> Bounds2 {
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 {
match d.anno_draw(e) {
@@ -445,7 +378,7 @@ fn unknown_bounds<'a>(
d: &'a Drawing,
u: &crate::Unknown,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
off_counts: bool,
) -> Bounds2 {
if u.graphics.is_empty() {
@@ -466,7 +399,7 @@ fn unknown_bounds<'a>(
/// 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), Contents<'a>>, off_counts: bool) -> Bounds2 {
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>, off_counts: bool) -> Bounds2 {
match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
@@ -487,12 +420,19 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
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, off_counts)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -514,7 +454,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
@@ -551,7 +491,17 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// 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 = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.geometry);
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, off_counts)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
// The block draws translated by the insertion point (group 12), so its bounds
// move with it (#2634); the cache above keeps the block's own bounds.
let off = dm.insertion_point.xy();
-76
View File
@@ -113,43 +113,6 @@ impl Foreign {
&& self.appids.is_empty()
}
/// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or
/// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its
/// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so
/// saving writes its xdata, extension dictionary and reactors on the renamed record. Names
/// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case
/// changes nothing.
pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) {
let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
if from == to {
return;
}
for kind in kinds {
let old: ForeignKey = ((*kind).to_string(), from.clone());
let new: ForeignKey = ((*kind).to_string(), to.clone());
if let Some(extra) = self.records.remove(&old) {
self.records.insert(new.clone(), extra);
}
self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone());
}
}
/// Whether anything is kept for the record named `from` under one of `kinds`: what
/// [`Foreign::rename`] would re-key.
pub fn names(&self, kinds: &[&str], from: &str) -> bool {
let from = from.trim().to_ascii_uppercase();
let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str());
self.records.keys().any(hit) || self.targets.values().any(hit)
}
/// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps
/// something for the renamed record and the name really changes (not only its case).
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
if !from.trim().eq_ignore_ascii_case(to.trim()) && this.names(kinds, from) {
std::sync::Arc::make_mut(this).rename(kinds, from, to);
}
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
/// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry.
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
@@ -427,42 +390,3 @@ pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> +
pub fn class_index(number: Option<i64>) -> Option<usize> {
usize::try_from(number?.checked_sub(500)?).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn key(k: &str, n: &str) -> ForeignKey {
(k.to_string(), n.to_string())
}
#[test]
fn rename_rekeys_records_and_targets_of_the_given_kinds_only() {
let mut f = Foreign::default();
let xdict = ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() };
f.records.insert(key("BLOCK_RECORD", "DOOR"), xdict.clone());
f.records.insert(key("LAYER", "DOOR"), ForeignExtra { reactors: vec![Handle(0x41)], ..ForeignExtra::default() });
f.targets.insert(Handle(0x10), key("BLOCK_RECORD", "DOOR"));
f.targets.insert(Handle(0x11), key("BLOCK", "DOOR"));
f.targets.insert(Handle(0x12), key("LAYER", "DOOR"));
f.rename(&["BLOCK_RECORD", "BLOCK", "ENDBLK"], "Door", "Gate");
assert_eq!(f.records.get(&key("BLOCK_RECORD", "GATE")), Some(&xdict));
assert!(!f.records.contains_key(&key("BLOCK_RECORD", "DOOR")));
assert!(f.records.contains_key(&key("LAYER", "DOOR")), "another kind with the same name stays");
assert_eq!(f.targets.get(&Handle(0x10)), Some(&key("BLOCK_RECORD", "GATE")));
assert_eq!(f.targets.get(&Handle(0x11)), Some(&key("BLOCK", "GATE")));
assert_eq!(f.targets.get(&Handle(0x12)), Some(&key("LAYER", "DOOR")));
}
#[test]
fn rename_shared_leaves_an_unrelated_drawing_shared() {
let mut f = Foreign::default();
f.records.insert(key("LAYER", "A"), ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() });
let mut a = std::sync::Arc::new(f);
let snapshot = a.clone();
Foreign::rename_shared(&mut a, &["LAYER"], "B", "C");
assert!(std::sync::Arc::ptr_eq(&a, &snapshot));
Foreign::rename_shared(&mut a, &["LAYER"], "a", "c");
assert!(a.records.contains_key(&key("LAYER", "C")) && snapshot.records.contains_key(&key("LAYER", "A")));
}
}
+22 -48
View File
@@ -14,7 +14,6 @@ mod format;
mod gdt;
mod header;
pub mod library;
mod names;
mod plotstyle;
mod plotter;
mod raster;
@@ -37,7 +36,6 @@ pub use extents::{
pub use format::Format;
pub use gdt::*;
pub use header::{HVal, Header};
pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
@@ -103,26 +101,17 @@ pub struct Drawing {
pub header: Header,
/// File data CADCraft does not model, written back on save.
pub foreign: std::sync::Arc<foreign::Foreign>,
/// Layers in table order; [`Drawing::layer`] looks them up by name.
pub layers: NamedList<Layer>,
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
pub linetypes: NamedList<Linetype>,
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
pub text_styles: NamedList<TextStyle>,
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
pub dim_styles: NamedList<DimStyle>,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
/// Table styles in table order; looked up by name with [`NamedList::by_name`].
pub table_styles: NamedList<TableStyle>,
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
/// Block definitions by name; [`Drawing::block`] looks them up.
pub blocks: NamedMap<std::sync::Arc<Block>>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
pub layouts: NamedList<Layout>,
pub layouts: Vec<Layout>,
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
pub active_layout: Option<String>,
@@ -169,11 +158,6 @@ pub struct Drawing {
pub portable_fonts: bool,
/// The pixels of the raster images that are loaded (IMAGE). Never written to a file.
pub rasters: Rasters,
/// The LAYER table of the file this drawing was read from, in the file's order and under
/// the layers' current names: proxy graphics name layers by their index in it, and saving
/// turns those indices into the written table's (#3094). An empty name stands for a record
/// without one. Empty for a drawing not read from a file.
pub proxy_layers: Vec<String>,
}
impl Default for Drawing {
@@ -196,7 +180,7 @@ impl Drawing {
d.scales = metric_scales();
d.dim_styles.push(DimStyle::iso25());
d.mleader_styles = vec![MLeaderStyle::metric()];
d.table_styles = vec![TableStyle::metric()].into();
d.table_styles = vec![TableStyle::metric()];
d.header.set_str("DIMSTYLE", "ISO-25");
d
}
@@ -204,22 +188,20 @@ impl Drawing {
Drawing {
header: Header::default(),
foreign: std::sync::Arc::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
linetypes: vec![
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
Linetype::continuous(),
]
.into(),
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
],
text_styles: vec![TextStyle::default()],
dim_styles: vec![DimStyle::default()],
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()].into(),
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: NamedMap::default(),
blocks: BTreeMap::new(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
active_layout: None,
views: Vec::new(),
vports: Vec::new(),
@@ -239,7 +221,6 @@ impl Drawing {
skipped_records: BTreeMap::new(),
portable_fonts: false,
rasters: Rasters::default(),
proxy_layers: Vec::new(),
}
}
@@ -323,25 +304,20 @@ impl Drawing {
}
}
/// The first layer named `name`, without case.
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.by_name(name)
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first layer named `name`, without case, to change.
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.by_name_mut(name)
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first linetype named `name`, without case.
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.by_name(name)
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first text style named `name`, without case.
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
self.text_styles.by_name(name)
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first dimension style named `name`, without case.
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
self.dim_styles.by_name(name)
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The DIM* variables in the header that differ from the current dimension style, as
@@ -409,13 +385,11 @@ impl Drawing {
}
}
}
/// The block named exactly `name`, else the first by name order named `name` without case.
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.by_name(name)
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
}
/// The first layout named `name`, without case.
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.by_name(name)
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// Add a layer if missing; returns whether it was created.
-575
View File
@@ -1,575 +0,0 @@
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles,
//! table styles and layouts), whose names are looked up without case through an index instead of a
//! scan once a table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
//!
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
//! what scanning it always did, and one looked up many times in between is indexed once.
use std::collections::{BTreeMap, btree_map};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
const MIN_INDEXED: usize = 128;
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
/// hundred lookups costs at most about 2.5 times what scanning it always did.
const SCANS_BEFORE_INDEX: u32 = 256;
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
struct Index<V>(BTreeMap<Box<[u8]>, V>);
impl<V> Index<V> {
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
let mut map = BTreeMap::new();
for (name, v) in entries {
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
}
Index(map)
}
/// The first entry named `name`, without case.
fn get(&self, name: &str) -> Option<&V> {
with_folded(name, |folded| self.0.get(folded))
}
}
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
let mut buf = [0u8; 64];
match buf.get_mut(..name.len()) {
Some(short) => {
short.copy_from_slice(name.as_bytes());
short.make_ascii_lowercase();
f(short)
}
None => f(name.to_ascii_lowercase().as_bytes()),
}
}
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
/// dropped when the table changes.
struct Lazy<V> {
index: OnceLock<Arc<Index<V>>>,
/// Lookups that scanned the table since it last changed.
scans: AtomicU32,
}
impl<V> Lazy<V> {
/// The index of a table of `len` entries, built with `build` once the table has been scanned
/// often enough since it changed; `None` while it is to be scanned.
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
if let Some(ix) = self.index.get() {
return Some(ix);
}
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
return None;
}
Some(self.index.get_or_init(|| Arc::new(build())))
}
/// Forget the index: the table may change.
fn clear(&mut self) {
self.index = OnceLock::new();
*self.scans.get_mut() = 0;
}
}
impl<V> Default for Lazy<V> {
fn default() -> Self {
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
}
}
impl<V> Clone for Lazy<V> {
fn clone(&self) -> Self {
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
}
}
/// An entry of a [`NamedList`]: what it is looked up by.
pub trait Named {
fn name(&self) -> &str;
}
/// Entries named by their `name` field.
macro_rules! named_by_field {
($($t:ty),*) => {$(
impl Named for $t {
fn name(&self) -> &str {
&self.name
}
}
)*};
}
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, crate::Layout);
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
/// dimension styles, table styles and layouts). It reads and changes as a `Vec`;
/// [`NamedList::by_name`] finds the first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
}
impl<T: Named> NamedList<T> {
/// The position of the first entry named `name`, without case.
pub fn position_by_name(&self, name: &str) -> Option<usize> {
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
Some(ix) => ix.get(name).copied(),
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
}
}
/// The first entry named `name`, without case.
pub fn by_name(&self, name: &str) -> Option<&T> {
self.position_by_name(name).and_then(|i| self.list.get(i))
}
/// The first entry named `name`, without case, to change (which drops the index).
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
let i = self.position_by_name(name)?;
self.get_mut(i)
}
}
impl<T> Deref for NamedList<T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.list
}
}
impl<T> DerefMut for NamedList<T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
self.index.clear();
&mut self.list
}
}
impl<T> Default for NamedList<T> {
fn default() -> Self {
Vec::new().into()
}
}
impl<T: Clone> Clone for NamedList<T> {
fn clone(&self) -> Self {
NamedList { list: self.list.clone(), index: self.index.clone() }
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.list.fmt(f)
}
}
impl<T: PartialEq> PartialEq for NamedList<T> {
fn eq(&self, other: &Self) -> bool {
self.list == other.list
}
}
impl<T> From<Vec<T>> for NamedList<T> {
fn from(list: Vec<T>) -> Self {
NamedList { list, index: Lazy::default() }
}
}
impl<T> From<NamedList<T>> for Vec<T> {
fn from(l: NamedList<T>) -> Self {
l.list
}
}
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.list.serialize(s)
}
}
impl<T> FromIterator<T> for NamedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Vec::from_iter(iter).into()
}
}
impl<T> IntoIterator for NamedList<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.list.into_iter()
}
}
impl<'a, T> IntoIterator for &'a NamedList<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.list.iter()
}
}
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
/// order whose name matches without case.
pub struct NamedMap<V> {
map: BTreeMap<String, V>,
index: Lazy<Box<str>>,
}
impl<V> NamedMap<V> {
/// The entry named exactly `name`, else the first in name order named `name` without case.
pub fn by_name(&self, name: &str) -> Option<&V> {
if let Some(v) = self.map.get(name) {
return Some(v);
}
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
}
}
}
impl<V> Deref for NamedMap<V> {
type Target = BTreeMap<String, V>;
fn deref(&self) -> &BTreeMap<String, V> {
&self.map
}
}
impl<V> DerefMut for NamedMap<V> {
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
self.index.clear();
&mut self.map
}
}
impl<V> Default for NamedMap<V> {
fn default() -> Self {
BTreeMap::new().into()
}
}
impl<V: Clone> Clone for NamedMap<V> {
fn clone(&self) -> Self {
NamedMap { map: self.map.clone(), index: self.index.clone() }
}
}
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.map.fmt(f)
}
}
impl<V: PartialEq> PartialEq for NamedMap<V> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
fn from(map: BTreeMap<String, V>) -> Self {
NamedMap { map, index: Lazy::default() }
}
}
impl<V> FromIterator<(String, V)> for NamedMap<V> {
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
BTreeMap::from_iter(iter).into()
}
}
impl<V> IntoIterator for NamedMap<V> {
type Item = (String, V);
type IntoIter = btree_map::IntoIter<String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a, V> IntoIterator for &'a NamedMap<V> {
type Item = (&'a String, &'a V);
type IntoIter = btree_map::Iter<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
type Item = (&'a String, &'a mut V);
type IntoIter = btree_map::IterMut<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{MIN_INDEXED, Named, NamedList};
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
/// added (a miss).
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
}
fn layers_indexed(d: &Drawing) -> bool {
d.layers.index.index.get().is_some()
}
fn indexed<T>(list: &NamedList<T>) -> bool {
list.index.index.get().is_some()
}
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
/// name without case), by pointer, for the list's names and `extra`.
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
}
}
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
/// order finds (the first of a name without case): while they scan, once the table is indexed,
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
/// changed the first of a name and dropped the index.
#[test]
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
let mut d = Drawing::new_imperial();
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
let check = |d: &Drawing, extra: &[&str]| {
check_list(&d.linetypes, |n| d.linetype(n), extra);
check_list(&d.text_styles, |n| d.text_style(n), extra);
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
check_list(&d.layouts, |n| d.layout(n), extra);
};
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
// The first round scans until the index is built; the second reads only the index.
check(&d, &["dash", "missing"]);
assert!(all_indexed(&d));
check(&d, &["dash", "missing"]);
// The first of a name changes, and the later one of that name is found after it.
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
check(&d, &["SEVEN", "n7"]);
assert!(all_indexed(&d));
// A miss changes nothing and keeps the index.
assert!(d.dim_styles.by_name_mut("none").is_none());
assert!(indexed(&d.dim_styles));
check(&d, &["dash"]);
}
fn blocks_indexed(d: &Drawing) -> bool {
d.blocks.index.index.get().is_some()
}
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
/// name without case), and a large table looked up this often is left indexed.
fn check_layers(d: &mut Drawing, extra: &[&str]) {
let p = extra.first().copied().unwrap_or("L1");
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
assert!(want.is_none() || !layers_indexed(d));
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
}
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
}
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
/// else the first in name order of that name without case. Only names that miss an exact name
/// count towards building the index, so the names are looked up twice.
fn check_blocks(d: &Drawing, extra: &[&str]) {
let names: Vec<String> = d.blocks.keys().cloned().collect();
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
}
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
}
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
/// of its name without case, also names that differ only after a long shared prefix, names
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
/// case). Names are compared, not hashed, so no two names can share a slot.
#[test]
fn the_index_alone_finds_the_first_entry_of_every_name() {
let long = "x".repeat(100);
let names: Vec<String> = vec![
"Door".into(),
"DOOR".into(),
"door2".into(),
format!("{long}A"),
format!("{long}a"),
format!("{long}B"),
format!("{}b", "P".repeat(63)),
format!("{}B", "p".repeat(63)),
"Ärea".into(),
"ärea".into(),
"ÄREA".into(),
String::new(),
];
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
}
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
assert_eq!(ix.get("ärea"), Some(&9));
}
#[test]
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
let mut d = Drawing::new_imperial();
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
check_layers(&mut d, &["l5", "missing"]);
// Renamed through layer_mut (RENAME).
d.layer_mut("l7").unwrap().name = "Seven".into();
assert!(!layers_indexed(&d));
assert!(d.layer("L7").is_none());
check_layers(&mut d, &["SEVEN", "L7"]);
// Added (LAYER New, or a file's later record of a name it already has).
d.layers.push(Layer::new("SEVEN"));
assert!(!layers_indexed(&d));
check_layers(&mut d, &["seven"]);
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
d.layers.retain(|l| l.name != "L5");
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
check_layers(&mut d, &["L5"]);
// Inserted before an earlier layer of the same name.
d.layers.insert(0, Layer::new("l9"));
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
check_layers(&mut d, &["L9"]);
// Changed by position, and by a loop over all of them.
d.layers[3].name = "Third".into();
assert!(!layers_indexed(&d));
check_layers(&mut d, &["third"]);
for l in &mut d.layers {
l.name.make_ascii_uppercase();
}
assert!(!layers_indexed(&d));
check_layers(&mut d, &["doors"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
assert!(layers_indexed(&d));
let (snap, before) = (d.clone(), names(&d));
d.layers.clear();
d.layers.push(Layer::new("Only"));
check_layers(&mut d, &["only", "L1"]);
d = snap;
assert!(layers_indexed(&d));
assert_eq!(names(&d), before);
check_layers(&mut d, &["THIRD"]);
// The whole table replaced (LAYERP, LAYUNISO).
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
check_layers(&mut d, &["a"]);
}
#[test]
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
let block = |name: &str| Arc::new(Block::new(name));
let mut d = Drawing::new_imperial();
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
d.blocks.insert(name.clone(), block(&name));
}
check_blocks(&d, &["dOOR", "missing"]);
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
// Removed (PURGE, a definition replaced under another name).
d.blocks.remove("DOOR");
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
check_blocks(&d, &["dOOR"]);
// Added before the first of that name.
d.blocks.insert("DoOr".into(), block("DoOr"));
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
check_blocks(&d, &["dOOR"]);
// Renamed (RENAME takes the definition out and puts it back under the new name).
let b1 = d.blocks.remove("B1").unwrap();
d.blocks.insert("Renamed".into(), b1);
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
check_blocks(&d, &["b1", "RENAMED"]);
// Redefined in place, and changed through get_mut: the names stay.
d.blocks.insert("Door".into(), block("Door"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["DOOR"]);
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b2"]);
// Many removed at once.
d.blocks.retain(|k, _| !k.starts_with("B9"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b9", "b90"]);
// A loop over all of them.
for (_, b) in &mut d.blocks {
Arc::make_mut(b).description = "looped".into();
}
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b3"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let snap = d.clone();
d.blocks.clear();
d.blocks.insert("Only".into(), block("Only"));
check_blocks(&d, &["only", "door"]);
d = snap;
assert!(blocks_indexed(&d));
check_blocks(&d, &["DOOR", "only"]);
}
}
+3 -12
View File
@@ -79,21 +79,15 @@ impl Default for DevicePaper {
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. A sheet wider than tall is stored turned 90° and
/// its margins turn with it, so the printable area the caller measured against the sheet it
/// named is the one the stored portrait paper holds.
/// 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 };
}
if w > h {
let [l, b, r, t] = self.margins;
self.margins = [b, r, t, l];
}
self.width = w.min(h);
self.height = w.max(h);
let [l, b, r, t] = self.margins;
if l + r >= self.width || b + t >= self.height {
self.margins = [0.0; 4];
@@ -249,9 +243,6 @@ mod tests {
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");
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
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");
+3 -17
View File
@@ -782,10 +782,6 @@ impl Block {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PageSetup {
/// Original plot subclass and the modeled values it was read with.
/// Only edits that clone the page retain these original fields; the JSON form does not carry them.
#[serde(skip)]
pub file_plot_settings: Option<Box<FilePlotSettings>>,
pub device: String,
pub paper: String,
/// Paper size in millimetres (portrait width/height before rotation).
@@ -793,7 +789,7 @@ pub struct PageSetup {
pub height_mm: f64,
pub margins_mm: [f64; 4],
pub landscape: bool,
/// "layout" | "extents" | "display" | "window" | "limits" | "view".
/// "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],
@@ -842,7 +838,6 @@ pub struct PageSetup {
impl Default for PageSetup {
fn default() -> Self {
PageSetup {
file_plot_settings: None,
device: "None".into(),
paper: "ANSI A (8.50 x 11.00 Inches)".into(),
width_mm: 215.9,
@@ -867,15 +862,6 @@ impl Default for PageSetup {
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FilePlotSettings {
/// Groups after AcDbPlotSettings and before AcDbLayout, including unmodeled fields.
/// See the Autodesk DXF Reference, LAYOUT and PLOTSETTINGS.
pub tags: Vec<craft_dxf::Tag>,
/// The interpreted page with no nested file settings, for detecting edits on save.
pub page: PageSetup,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Layout {
@@ -1018,8 +1004,8 @@ impl LayerState {
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
}
}
+1 -322
View File
@@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() {
let i = Drawing::new_imperial();
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
assert_eq!(*i.table_styles, vec![TableStyle::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));
}
@@ -271,46 +271,6 @@ fn transform_arc_mirror_keeps_shape() {
}
}
#[test]
fn mirroring_a_rotated_dimension_reflects_its_direction() {
let dim = |kind: DimKind, marks: DimMarks| {
EntityKind::Dimension(Dimension {
kind,
defpt: Vec3::ZERO,
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(7.071_067_811_865_475, 7.071_067_811_865_475, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 10.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: vec![],
marks,
})
};
// A dimension line at 45° mirrored across the X axis runs at -45° (315°) and still measures 10.
let mut k = dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_4 }, DimMarks::default());
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::X));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
let DimKind::Linear { rotation } = d.kind else { panic!("a linear dimension") };
assert!((rotation - 7.0 * std::f64::consts::FRAC_PI_4).abs() < 1e-9, "{rotation}");
let p2 = Vec2::new(7.071_067_811_865_475, -7.071_067_811_865_475);
assert!((p2.dot(Vec2::from_angle(rotation)).abs() - 10.0).abs() < 1e-9, "the mirrored measurement");
// Oblique extension lines reflect about the mirror line too (a 45° line here) instead of
// being double-reflected (120° rather than 30°).
let mut k = dim(DimKind::Aligned, DimMarks { oblique: Some(std::f64::consts::FRAC_PI_3), ..DimMarks::default() });
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
assert!((d.marks.oblique.unwrap_or(0.0) - (std::f64::consts::FRAC_PI_2 - std::f64::consts::FRAC_PI_3)).abs() < 1e-9, "{:?}", d.marks.oblique);
}
#[test]
fn insert_bounds_with_cyclic_block_terminate() {
let mut d = Drawing::new_imperial();
@@ -560,21 +520,6 @@ fn block_entity_with_invisible_flag_is_ignored_in_insert_extents() {
assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0));
}
#[test]
fn a_visible_constant_attribute_definition_counts_in_insert_extents() {
// #3413: a reference draws a constant definition's value, so its extents reach it.
let def = |constant: bool, invisible: bool| {
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
(a.constant, a.invisible) = (constant, invisible);
Entity::new(Handle(2), EntityKind::AttDef(a))
};
let near = extents_pair(&drawing_with_block(def(false, false))).1;
assert!(extents_pair(&drawing_with_block(def(true, false))).1.y > near.y + 40.0);
// An invisible constant one, like a variable one, does not count.
assert_eq!(extents_pair(&drawing_with_block(def(true, true))).1, near);
}
#[test]
fn block_entity_on_frozen_layer_is_ignored_and_on_a_layer_turned_off_counts() {
let mut d = drawing_with_block(far_line("Hidden"));
@@ -819,269 +764,3 @@ fn dim_style_spellings_of_one_field_apply_once() {
assert!(st.apply_fields(m).is_empty());
assert_eq!(st.text_height, want);
}
/// A dimension's block in a parent block: `first` the dimension, or the reference to the same
/// block "B" (a line and a visible constant attribute definition at y = 50).
fn parent_of_dimension_and_insert(dimension_first: bool) -> Drawing {
// Only "P" is referenced from model space, so "B" is measured inside it and nowhere else.
let mut d = Drawing::new_imperial();
let mut b = Block::new("B");
b.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
a.constant = true;
b.entities.push(Entity::new(Handle(2), EntityKind::AttDef(a)));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let dim = EntityKind::Dimension(Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(1.0, 1.0, 0.0),
text_mid: Vec3::new(0.5, 1.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(1.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 1.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some("B".into()),
overrides: Default::default(),
assoc: vec![],
marks: Default::default(),
insertion_point: Vec3::ZERO,
});
let mut kids = vec![dim, plain_insert("B")];
if !dimension_first {
kids.reverse();
}
let mut parent = Block::new("P");
for (i, k) in kids.into_iter().enumerate() {
parent.entities.push(Entity::new(Handle(i as u64 + 10), k));
}
d.blocks.insert("P".into(), std::sync::Arc::new(parent));
d.add(&Space::Model, Common::default(), plain_insert("P")).unwrap();
d
}
#[test]
fn constant_values_count_whichever_reference_measures_the_block_first() {
// A dimension's block draws no constant value, a block reference does, and both read one
// cache of block bounds: the reference's extents must not depend on which comes first.
let first = extents_pair(&parent_of_dimension_and_insert(true));
assert_eq!(first, extents_pair(&parent_of_dimension_and_insert(false)));
assert!(first.1.y > 40.0, "the constant value at y = 50 counts: {first:?}");
}
#[test]
fn a_constant_value_that_matches_the_layout_orientation_is_measured_upright() {
// Drawn upright whatever rotation is stored (#2498), so the extents are those of rotation 0.
let def = |rotation: f64, upright: bool| {
let mut a = plain_attrib("C");
a.text.value = "a long constant value".into();
a.text.rotation = rotation;
a.constant = true;
let mut e = Entity::new(Handle(2), EntityKind::AttDef(a));
if upright {
e.common.xdata = vec![RawTag { code: 1001, value: "AcadAnnoPO".into() }, RawTag { code: 1070, value: "1".into() }];
}
e
};
let flat = extents_pair(&drawing_with_block(def(0.0, false)));
assert_eq!(extents_pair(&drawing_with_block(def(std::f64::consts::FRAC_PI_2, true))), flat);
assert_ne!(extents_pair(&drawing_with_block(def(std::f64::consts::FRAC_PI_2, false))), flat, "a plain one keeps its rotation");
}
#[test]
fn a_constant_value_the_reference_has_an_attribute_for_does_not_count() {
// Such a reference draws its attribute, not the definition's value, so a far-off definition
// does not stretch its extents; a reference without that attribute still shows the value.
let with = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 5000.0, 0.0);
a.constant = true;
blk.entities.push(Entity::new(Handle(2), EntityKind::AttDef(a)));
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
assert!(with(vec![]).y > 4000.0);
assert!(with(vec![plain_attrib("c")]).y < 100.0);
}
#[test]
fn constant_values_count_in_extents_as_attmode_shows_them() {
// The renderer shows no constant value at ATTMODE 0, and the invisible ones too at 2.
let top = |attmode: i64, invisible: bool| {
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
(a.constant, a.invisible) = (true, invisible);
let mut d = drawing_with_block(Entity::new(Handle(2), EntityKind::AttDef(a)));
d.header.set_i64("ATTMODE", attmode);
extents_pair(&d).1.y
};
assert!(top(1, false) > 40.0);
assert!(top(0, false) < 40.0, "ATTMODE 0 hides it");
assert!(top(1, true) < 40.0);
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
const N: usize = 60_000;
let mut d = Drawing::new_imperial();
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
for i in 0..N {
let name = format!("B{i}");
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
}
let started = std::time::Instant::now();
for i in 0..N {
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
/// Table entries for the cost tests below.
const NAMED: usize = 40_000;
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
/// about 50 bytes and not a length check, as in a crafted file.
fn long_name(kind: &str, tail: &str) -> String {
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
}
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
}
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
/// comparisons (#1924).
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
let started = std::time::Instant::now();
for i in 0..NAMED {
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
#[test]
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
}
#[test]
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
}
#[test]
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
}
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
#[test]
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
}
-1
View File
@@ -14,7 +14,6 @@ cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
craft-mime = { workspace = true }
craft-dxf = { workspace = true }
craft-csv = { workspace = true }
cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
-44
View File
@@ -1,44 +0,0 @@
//! Live array parameters of a running ARRAYRECT / ARRAYPOLAR: what the interactive command has
//! while it runs, read and written from the array window and kept in step with the command line.
use crate::Vec2;
/// Which array the live parameters belong to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArrayLiveKind {
Rectangular,
Polar,
}
/// The parameters of the running array command, with the fields of the other kind left at zero.
#[derive(Clone, Debug, PartialEq)]
pub struct ArrayLive {
pub kind: ArrayLiveKind,
/// Rectangular: number of columns.
pub cols: u64,
/// Both: number of rows.
pub rows: u64,
/// Rectangular: distance between columns.
pub col_spacing: f64,
/// Both: distance between rows.
pub row_spacing: f64,
/// Both: number of levels.
pub levels: u64,
/// Both: distance between levels.
pub level_spacing: f64,
/// Both: elevation added per row.
pub row_elevation: f64,
/// Both: whether the array is associative.
pub associative: bool,
/// Polar: number of items.
pub items: u64,
/// Polar: fill angle in degrees (positive = counterclockwise).
pub fill: f64,
/// Polar: whether items are rotated.
pub rotate: bool,
/// Polar: the centre; `None` for a rectangular array.
pub center: Option<Vec2>,
/// Polar only: the angle between items, degrees, derived from items and fill.
/// `None` for Rectangular.
pub between: Option<f64>,
}
+3 -6
View File
@@ -7,7 +7,7 @@
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
//! get new ones.
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
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};
@@ -425,9 +425,6 @@ 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();
// Multileader style names, lower-cased, built once: a scan per multileader made a file of N of
// them naming styles among N quadratic to audit (#1924).
let mleader_styles: BTreeSet<String> = d.mleader_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect();
// Missing names, counted: (what, name) → (objects, first location).
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
missing_layers(d, out);
@@ -465,12 +462,12 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
if let Some(t) = &mut m.text {
text_style(&mut t.style);
}
if !mleader_styles.contains(&m.style.to_ascii_lowercase()) {
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
note("multileader style", &m.style);
m.style = "Standard".into();
}
}
EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => {
EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => {
note("table style", &t.style);
t.style = "Standard".into();
}
+2 -3
View File
@@ -14,7 +14,7 @@ mod draw;
mod draw2;
mod draworder;
mod edit;
pub mod exchange;
mod exchange;
pub mod file;
mod gripcmds;
mod griphot;
@@ -47,10 +47,9 @@ mod qselect;
mod selecttools;
mod settings;
mod spline_opts;
pub mod table;
mod table;
mod tolerance;
mod trimextend;
pub use trimextend::PREVIEW_MAX_PICKS as TRIM_PREVIEW_MAX_PICKS;
mod txt2mtxt;
pub use txt2mtxt::Txt2MtxtOptions;
mod ucs;
+1 -7
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,7 +19,6 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -28,7 +27,6 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
use qleader::{QLeaderM, run_qleader};
use radial::{RadialM, run_diameter, run_radius};
pub fn specs() -> Vec<CommandSpec> {
@@ -95,10 +93,6 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["lead"])
.params("{points: [[x,y]...], text?}")
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
CommandSpec::new("qleader", "Quick Leader", run_qleader)
.alias(&["le"])
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
CommandSpec::new("dimstyle.update", "Update", run_update)
.menu(&["Dimension", "Update"])
.params("{handles?}")
+2 -4
View File
@@ -46,7 +46,7 @@ pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, a
DimKind::Linear { rotation: rotation.unwrap_or_else(auto) }
}
/// Add a dimension. With DIMASSOC 2, definition points that sit on object endpoints,
/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints,
/// vertices or centres are attached to them (associative dimensions).
pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result<Handle> {
let mut k = k;
@@ -74,10 +74,8 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result<Handle> {
Ok(h)
}
/// Only DIMASSOC mode 2 attaches newly created dimensions to their source geometry.
pub(super) fn assoc_enabled(s: &Session) -> bool {
// Mode 1 keeps a dimension as one object without linking it to source geometry.
s.doc().map(|d| d.header.i64("DIMASSOC", 2) == 2).unwrap_or(false)
s.doc().map(|d| d.header.i64("DIMASSOC", 2) != 0).unwrap_or(false)
}
pub(super) fn with_assoc(k: EntityKind, assoc: Vec<DimAssoc>) -> EntityKind {
+7 -12
View File
@@ -161,22 +161,17 @@ pub(super) fn run_dimtedit(s: &mut Session, p: &Value) -> Result<Value> {
}
/// DIMSPACE: equal spacing of parallel linear dimensions from a base dimension.
/// [Auto spacing](https://help.autodesk.com/cloudhelp/2023/ENU/AutoCAD-LT-MAC/files/GUID-18DF8B02-3E43-4531-ACE0-75FA7161F209.htm)
/// uses twice the base dimension's text height.
pub(super) fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
let base = hex_param(p, "base").ok_or_else(|| bad("dimspace", "`base` dimension is required"))?;
let hs: Vec<Handle> = dims_of(s, &targets(s, p)?).into_iter().filter(|h| *h != base).collect();
let d = s.doc()?;
let Some(EntityKind::Dimension(b)) = d.entity(base).map(|e| e.kind.clone()) else { return Err(bad("dimspace", "`base` is not a dimension")) };
let spacing = p.get("spacing").and_then(Value::as_f64).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or_else(|| {
let st = d.dim_style(&b.style).cloned().unwrap_or_default().with_overrides(&b.overrides);
let text_height = d
.text_style(&st.text_style)
.map(|style| style.height)
.filter(|height| height.is_finite() && *height > 0.0)
.unwrap_or_else(|| st.text_height * st.effective_scale(d.header.f64("DIMSCALE", 1.0)));
2.0 * text_height
});
let st = d.dim_style(&b.style).cloned().unwrap_or_default().with_overrides(&b.overrides);
let spacing = p
.get("spacing")
.and_then(Value::as_f64)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(st.baseline_spacing * st.effective_scale(d.header.f64("DIMSCALE", 1.0)) * 2.0);
let dir = match b.kind {
DimKind::Linear { rotation } => Vec2::from_angle(rotation),
DimKind::Aligned => (b.p14.xy() - b.p13.xy()).normalized(),
@@ -214,7 +209,7 @@ pub(super) fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
}
/// DIMSPACE at the command line: select the base dimension, select the dimensions to space, then
/// the spacing (Enter or Auto uses the base dimension's text height).
/// the spacing (Enter or Auto takes the DIMDLI-based default).
#[derive(Default)]
pub(super) struct DimSpaceM {
base: Option<Handle>,
+3 -25
View File
@@ -42,13 +42,8 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
pub(super) enum Annotation {
enum Annotation {
Text(Vec<String>),
/// QLEADER's text: its lines and its width.
Quick {
lines: Vec<String>,
width: f64,
},
/// A copy of a text or multiline text: its contents, height, width and style.
Copy(MText),
None,
@@ -268,13 +263,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
}
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
let z = sizes(s);
// The side the leader runs to: right unless its last segment runs left.
let dir = if end.x < before.x { -1.0 } else { 1.0 };
let mut vertices = pts.to_vec();
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
let d = end - before;
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
// the leader ends half the text height lower.
@@ -315,23 +310,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
columns: None,
}))?)
}
Annotation::Quick { lines, width } => {
// The middle of the first line level with the end on the right, of the last line on
// the left, whatever DIMTAD.
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
Some(s.add_entity(EntityKind::MText(MText {
insert: v3(end + Vec2::new(dir * z.gap, lift)),
height: z.text,
width,
attach,
rotation: 0.0,
style: z.text_style,
contents: lines.join("\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?)
}
Annotation::Copy(m) => {
let lift = if z.above { z.gap } else { 0.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
-121
View File
@@ -1,121 +0,0 @@
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! synthetic drawings): up to three points, a text width, then lines of text.
//!
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
//! as wide as the width given: with the middle of its first line level with the end when the
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
use serde_json::{Value, json};
use super::leader::{Annotation, add_leader};
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
use crate::cmd::size_param;
/// QLEADER's default number of leader points.
const MAX_POINTS: usize = 3;
#[derive(Clone, Copy, Default, PartialEq)]
enum Ask {
#[default]
Points,
Width,
FirstLine,
NextLine,
}
#[derive(Default)]
pub(super) struct QLeaderM {
ask: Ask,
pts: Vec<Vec2>,
width: f64,
lines: Vec<String>,
}
impl Interactive for QLeaderM {
fn name(&self) -> &'static str {
"QLEADER"
}
fn prompt(&self, _s: &Session) -> Prompt {
let last = self.pts.last().copied();
match self.ask {
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.ask {
Ask::Points => match i {
Input::Point(p) => {
self.pts.push(p);
if self.pts.len() == MAX_POINTS {
self.ask = Ask::Width;
}
}
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
// Enter after one point: no leader.
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
Input::Enter => self.ask = Ask::Width,
_ => {}
},
Ask::Width => {
// A point gives the width as its distance from the leader's end; a negative
// width is none.
let width = match i {
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
Input::Text(t) => crate::units::parse_distance(&t),
Input::Enter => Some(0.0),
_ => return Ok(Step::Continue),
};
let finite = width.filter(|w| w.is_finite());
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
self.ask = Ask::FirstLine;
}
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
Ask::FirstLine | Ask::NextLine => match i {
Input::Text(t) if !t.is_empty() => {
self.lines.push(t);
self.ask = Ask::NextLine;
}
Input::Text(_) | Input::Enter => {
let lines = std::mem::take(&mut self.lines);
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
return Ok(Step::Done);
}
_ => {}
},
}
Ok(Step::Continue)
}
}
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
/// as `width`, placed as the command line places them. The handles of the leader and its text.
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("points").is_none_or(Value::is_null) {
return Err(bad("qleader", "`points` is required"));
}
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&pts.len()) {
return Err(bad("qleader", "`points` takes 2 or 3 points"));
}
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
return Err(bad("qleader", "`text` must be a string"));
}
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
// would otherwise sit level with a blank last line. Text with nothing left is no text.
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
let hs = add_leader(s, &pts, false, true, ann)?;
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
-40
View File
@@ -318,46 +318,6 @@ fn dimtedit_and_dimspace() {
assert!((dim(&s, b).defpt.y - 1.5).abs() < 1e-9, "{:?}", dim(&s, b).defpt);
}
#[test]
fn dimspace_auto_uses_the_base_dimension_text_height_and_scale() {
let mut s = Session::new();
let text_height = 3.0;
let scale = 1.5;
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXT": 2, "DIMDLI": 7, "DIMSCALE": scale })).unwrap();
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
s.execute("dimoverride", &json!({ "handles": [base.hex()], "DIMTXT": text_height })).unwrap();
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
let first = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
let second = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [30, 0], "at": [15, 36] })).unwrap());
s.execute("dimspace", &json!({ "base": base.hex(), "handles": [first.hex(), second.hex()] })).unwrap();
let positions = [base, first, second].map(|handle| dim(&s, handle).defpt.y);
let expected_spacing = 2.0 * text_height * scale;
assert!((positions[0] - 4.0).abs() < 1e-9, "positions: {positions:?}");
assert!(positions.windows(2).all(|pair| (pair[1] - pair[0] - expected_spacing).abs() < 1e-9), "positions: {positions:?}");
}
#[test]
fn dimspace_auto_uses_the_base_dimension_fixed_text_style_height() {
let mut s = Session::new();
let fixed_height = 2.5;
s.execute("style", &json!({ "name": "Fixed", "height": fixed_height })).unwrap();
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXSTY": "Fixed", "DIMTXT": 3, "DIMDLI": 7, "DIMSCALE": 2 })).unwrap();
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
let target = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
s.start("dimspace").unwrap();
s.input(Input::Pick(vec![base])).unwrap();
s.input(Input::Pick(vec![target])).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Text("Auto".into())).unwrap();
let spacing = dim(&s, target).defpt.y - dim(&s, base).defpt.y;
assert!((spacing - 2.0 * fixed_height).abs() < 1e-9, "spacing: {spacing}");
}
#[test]
fn text_style_rename_follows_block_definition_text() {
let mut s = Session::new();
+14 -156
View File
@@ -368,36 +368,21 @@ fn preview_copies(s: &Session, hs: &[Handle], mats: impl Iterator<Item = Mat3>)
fn other(m: impl Into<String>) -> EngineError {
EngineError::Other(m.into())
}
/// The fill angle (degrees) that gives `b` between `items` items, with the command
/// line's own rule and error messages.
fn fill_for_between(items: u64, b: f64) -> Result<f64> {
if !b.is_finite() || b.abs() < 1e-9 {
return Err(other("Requires a nonzero angle."));
}
let n = items.max(1) as f64;
let fill = if (b.abs() * n - 360.0).abs() < 1e-9 { 360.0 * b.signum() } else { b * (n - 1.0).max(1.0) };
if fill.abs() > 360.0 + 1e-9 {
return Err(other("The items would span more than 360 degrees; enter a smaller angle or fewer items."));
}
Ok(fill.clamp(-360.0, 360.0))
}
fn fmt(v: f64) -> String {
format!("{v:.4}")
}
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
match i {
Input::Enter => Ok(Some(cur)),
Input::Text(t) => t
.trim()
.parse::<u64>()
.parse::<f64>()
.ok()
.filter(|v| (1..=max).contains(v))
.map(Some)
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
.map(|v| Some(v as u64))
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
_ => Ok(None),
}
@@ -439,7 +424,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
match p.get(key) {
None | Some(Value::Null) => Ok(default),
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
@@ -707,45 +692,6 @@ impl RectM {
};
Ok(Step::Continue)
}
fn live(&self) -> crate::ArrayLive {
crate::ArrayLive {
kind: crate::ArrayLiveKind::Rectangular,
cols: self.cols,
rows: self.rows,
col_spacing: self.cs,
row_spacing: self.rs,
levels: self.levels,
level_spacing: self.ls,
row_elevation: self.elev,
associative: self.assoc,
items: 0,
fill: 0.0,
rotate: false,
center: None,
between: None,
}
}
/// Apply the array window's values: they are validated first, so a refused value leaves the
/// command exactly as it was.
fn apply_live(&mut self, s: &Session, v: &crate::ArrayLive) -> Result<()> {
if v.kind != crate::ArrayLiveKind::Rectangular {
return Err(other("That is a polar array; these are the rectangular parameters."));
}
if v.cols < 1 || v.rows < 1 || v.levels < 1 {
return Err(other("Requires at least one column, row and level."));
}
let levels = if v.associative { v.levels } else { 1 };
check_size(s, v.rows.saturating_mul(v.cols).saturating_mul(levels), self.objs.len())?;
if ![v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation].iter().all(|d| d.is_finite()) {
return Err(other("Requires finite distances."));
}
(self.cols, self.rows, self.levels) = (v.cols, v.rows, v.levels);
(self.cs, self.rs, self.ls, self.elev) = (v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation);
self.assoc = v.associative;
Ok(())
}
}
fn yes(b: bool) -> &'static str {
@@ -758,16 +704,6 @@ fn assoc_prompt(cur: bool) -> Prompt {
}
impl Interactive for RectM {
fn array_live(&self) -> Option<crate::ArrayLive> {
Some(self.live())
}
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
self.apply_live(s, v)
}
fn array_set_main(&mut self) -> bool {
self.stage = RStage::Main;
true
}
fn name(&self) -> &'static str {
"ARRAYRECT"
}
@@ -1060,15 +996,9 @@ impl PolarM {
fn ready(&mut self, s: &mut Session) -> Step {
self.stage = PStage::Center;
self.assoc = assoc_default(s);
// Start at the centre prompt, pre-filled with the selection's centre.
self.center = Vec2::ZERO;
// Rows and levels default to 1.5 × the selection's size apart.
if let Ok(d) = s.doc() {
let b = bounds(d, &self.objs);
let c = b.center();
if c.is_finite() {
self.center = c;
}
let size = b.width().max(b.height());
if size.is_finite() && size > 1e-9 {
(self.rs, self.ls) = (size * 1.5, size * 1.5);
@@ -1153,89 +1083,9 @@ impl PolarM {
};
d.filter(|d| d.is_finite() && d.abs() > 1e-12).map(Some).ok_or_else(|| other("Requires a nonzero distance."))
}
fn live(&self) -> crate::ArrayLive {
crate::ArrayLive {
kind: crate::ArrayLiveKind::Polar,
cols: 0,
rows: self.rows,
col_spacing: 0.0,
row_spacing: self.rs,
levels: self.levels,
level_spacing: self.ls,
row_elevation: self.elev,
associative: self.assoc,
items: self.items,
fill: self.fill,
rotate: self.rotate,
center: Some(self.center),
between: Some(self.between()),
}
}
/// Apply the array window's values: they are validated first, so a refused value leaves the
/// command exactly as it was.
fn apply_live(&mut self, s: &Session, v: &crate::ArrayLive) -> Result<()> {
if v.kind != crate::ArrayLiveKind::Polar {
return Err(other("That is a rectangular array; these are the polar parameters."));
}
if v.items < 1 || v.rows < 1 || v.levels < 1 {
return Err(other("Requires at least one item, row and level."));
}
let levels = if v.associative { v.levels } else { 1 };
check_size(s, v.rows.saturating_mul(v.items).saturating_mul(levels), self.objs.len())?;
// The Angle between field derives the fill; an edited Fill angle always wins.
let between_changed = v.between.is_some_and(|b| !b.is_finite() || (b - self.between()).abs() > 1e-9);
let fill_changed = (v.fill - self.fill).abs() > 1e-9;
let fill = match v.between {
Some(b) if between_changed && !fill_changed => fill_for_between(v.items, b)?,
_ => v.fill,
};
if !fill.is_finite() || fill.abs() <= 0.0 || fill.abs() > 360.0 {
return Err(other("Requires a fill angle between -360 and 360 degrees (not 0)."));
}
if ![v.row_spacing, v.level_spacing, v.row_elevation].iter().all(|d| d.is_finite()) {
return Err(other("Requires finite distances."));
}
if let Some(c) = v.center
&& !c.is_finite()
{
return Err(other("Requires a finite center point."));
}
(self.items, self.rows, self.levels) = (v.items, v.rows, v.levels);
(self.rs, self.ls, self.elev) = (v.row_spacing, v.level_spacing, v.row_elevation);
self.fill = fill;
self.rotate = v.rotate;
self.assoc = v.associative;
// The centre is always taken, but the command only moves on when it actually changed;
// the window copying the prefilled centre straight back never advances.
if let Some(c) = v.center {
if c != self.center && self.stage == PStage::Center {
self.stage = PStage::Main;
}
self.center = c;
}
Ok(())
}
}
impl Interactive for PolarM {
fn array_live(&self) -> Option<crate::ArrayLive> {
Some(self.live())
}
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
self.apply_live(s, v)
}
fn array_set_main(&mut self) -> bool {
if matches!(self.stage, PStage::Center | PStage::CenterBase | PStage::CenterBaseKey) {
return false;
}
self.stage = PStage::Main;
true
}
fn array_pick_center(&mut self) -> bool {
self.stage = PStage::Center;
true
}
fn name(&self) -> &'static str {
"ARRAYPOLAR"
}
@@ -1391,7 +1241,15 @@ impl Interactive for PolarM {
(Between, Input::Enter) => Main,
(Between, _) => match angle(&i, self.between(), &s.angle_settings())? {
Some(b) => {
self.fill = fill_for_between(self.items, b)?;
if b.abs() < 1e-9 {
return Err(other("Requires a nonzero angle."));
}
let n = self.items as f64;
let fill = if (b.abs() * n - 360.0).abs() < 1e-9 { 360.0 * b.signum() } else { b * (n - 1.0).max(1.0) };
if fill.abs() > 360.0 + 1e-9 {
return Err(other("The items would span more than 360 degrees; enter a smaller angle or fewer items."));
}
self.fill = fill;
Main
}
None => stage,
+69 -221
View File
@@ -15,7 +15,7 @@ use super::machines::{SelOutcome, SelectPhase, number};
use super::{CommandSpec, bad, bool_or, f64_or, find_command, ok, point_param, point_req, point_value, str_param, targets};
use super::has_doc;
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
mod attdef;
mod attedit;
@@ -43,14 +43,14 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Insert", "Block..."])
.alias(&["i", "-insert", "ddinsert"])
.params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}")
.interactive(|s| Ok(Box::new(InsertM { person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
.interactive(|_| Ok(Box::new(InsertM::default()))),
CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette)
.params("{references?: bool (default true; counting reads every object)} → {blocks: [{name, description, references?}], truncated} (the app opens the Blocks palette instead)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("minsert", "Multiple Insert", run_minsert)
.params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}")
.interactive(|s| Ok(Box::new(InsertM { minsert: true, person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
.interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))),
CommandSpec::new("attdef", "Define Attributes...", run_attdef)
.menu(&["Draw", "Block", "Define Attributes..."])
.alias(&["att", "-attdef"])
@@ -73,14 +73,14 @@ pub fn specs() -> Vec<CommandSpec> {
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
.enabled(has_doc),
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
.enabled(has_doc),
CommandSpec::new("purge", "Purge", purge::run)
.alias(&["pu", "-purge"])
@@ -403,14 +403,13 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
/// MINSERT's JSON form: INSERT's parameters and the grid.
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
let count = |key: &str| -> Result<u32> {
match p.get(key) {
None | Some(Value::Null) => Ok(1),
Some(v) => v
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (1..=Grid::MAX).contains(n))
.as_f64()
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
.map(|n| n as u32)
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
}
};
@@ -834,35 +833,11 @@ enum InsStage {
/// rows).
Cell(Vec2),
ColSpacing,
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
/// asks "Specify second point:"), from the first.
Second(TwoPoints, Vec2),
Attribs,
/// A Verify attribute asked again.
Verify,
}
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
/// distance, the preset rotation by their direction.
#[derive(Clone, Copy, Debug, PartialEq)]
enum TwoPoints {
Scale,
Axis(usize),
Rotation,
ColSpacing,
}
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
// angle, where a point gives the distance from the insertion point, and where only a number does.
const NONZERO: &str = "Value must be nonzero.";
/// Exploded INSERT's scale factor, which must be positive.
const POSITIVE: &str = "Value must be positive and nonzero.";
const TWO_POINTS: &str = "Requires numeric distance or two points.";
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
const SECOND_POINT: &str = "Requires numeric distance or second point.";
const NUMERIC: &str = "Requires numeric value.";
#[derive(Default)]
struct InsertM {
stage: InsStage,
@@ -883,16 +858,6 @@ struct InsertM {
rotation: Option<f64>,
/// The attributes asked for: tag, prompt, default value, and Verify (asked again).
attdefs: Vec<(String, String, String, bool)>,
/// How many of `attdefs` have their value: counted here, not by `values`, whose key is the
/// tag, so two definitions with one tag are still each asked once.
asked: usize,
/// ATTDIA 1 and a person started the command: the values are asked for in the Edit
/// Attributes dialog. A script, LISP routine or JSON call that opened INSERT has nobody to
/// answer a dialog, so it asks at the command line, even after the program is done.
dialog: bool,
/// A person started this command ([`Session::command_origin`]), fixed for its whole life:
/// only then may ATTDIA 1 open the dialog.
person: bool,
values: serde_json::Map<String, Value>,
/// Verify attributes asked again so far.
verified: usize,
@@ -924,7 +889,7 @@ impl InsertM {
s.echo("Enter attribute values");
}
// Then the Verify attributes are asked again, with the values typed.
if self.stage == InsStage::Attribs && self.asked >= self.attdefs.len() && self.verified < self.verifying().len() {
if self.stage == InsStage::Attribs && self.values.len() >= self.attdefs.len() && self.verified < self.verifying().len() {
if self.verified == 0 {
s.echo("Verify attribute values");
}
@@ -932,7 +897,7 @@ impl InsertM {
return Ok(Step::Continue);
}
if self.stage == InsStage::Attribs
&& self.asked >= self.attdefs.len()
&& self.values.len() >= self.attdefs.len()
&& let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation)
{
let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values, self.grid())?;
@@ -983,8 +948,6 @@ impl InsertM {
s.echo(format!("Block \"{name}\" not found."));
return Ok(());
};
// A program cannot click the dialog: it asks at the command line, as ATTDIA 0 does.
self.dialog = s.settings.attdia && self.person;
self.attdefs = if self.explode || !s.settings.attreq {
Vec::new()
} else {
@@ -999,7 +962,6 @@ impl InsertM {
})
.collect()
};
self.asked = 0;
self.name = Some(b.name.clone());
self.stage = InsStage::Point;
Ok(())
@@ -1043,66 +1005,6 @@ impl InsertM {
}
Ok(d)
}
/// The Scale preset `f` for every axis.
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// One axis preset: the others are 1, and no scale factors are asked after the point.
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
Ok(Step::Continue)
}
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
self.rotation = Some(r);
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
/// the first prompt again.
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
let (first, refused) = match what {
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
};
self.stage = first;
match (what, i) {
(TwoPoints::ColSpacing, Input::Point(b)) => {
self.col_spacing = Some(a.dist(b));
self.advance(s)
}
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(refused.into())),
}
}
}
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
@@ -1110,14 +1012,8 @@ fn distance(t: &str) -> Result<f64> {
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
}
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
/// isn't a number the prompt's own message.
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
if v == 0.0 {
return Err(EngineError::Other(NONZERO.into()));
}
Ok(v)
fn nonzero(t: &str) -> Result<f64> {
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
}
impl Interactive for InsertM {
@@ -1138,33 +1034,24 @@ impl Interactive for InsertM {
}
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
// Exploded, after the insertion point, it takes a number only.
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
InsStage::PresetAxis(i) => {
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
}
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
// still comes from a click or LISP.
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
// Text is read here, not taken as a distance along the rubber band: the core console
// refuses 5 at this prompt (measured).
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
InsStage::XScale => {
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
}
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
InsStage::Attribs => {
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
// No default shown when there is none ("Value:", AutoCAD 2024), not "<>".
if default.is_empty() { p } else { p.default(default) }
@@ -1238,58 +1125,45 @@ impl Interactive for InsertM {
self.stage = InsStage::Point;
}
}
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
// nonzero.", measured).
InsStage::PresetScale if self.at.is_some() => {
return match i {
Input::Text(t) => {
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
self.preset_scale(s, f)
}
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(NUMERIC.into())),
};
}
// A point at a preset is the first of two (AutoCAD 2024, measured).
InsStage::PresetScale => {
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Scale, p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
};
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
}
// One axis preset: the others are 1, and no scale factors are asked after the point.
InsStage::PresetAxis(ax) => {
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
};
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
}
InsStage::PresetRotation => {
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Rotation, p);
Ok(Step::Continue)
}
Input::Text(t) => {
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
self.preset_rotation(r)
}
Input::Enter => self.preset_rotation(0.0),
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
};
self.rotation = Some(match i {
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
Input::Enter => 0.0,
_ => return Ok(Step::Continue),
});
self.stage = InsStage::Point;
}
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
InsStage::XScale => match i {
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
@@ -1298,7 +1172,7 @@ impl Interactive for InsertM {
return self.corner_scale(s, sc);
}
Input::Text(t) => {
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
self.x_scale = Some(nonzero(&t)?);
self.stage = InsStage::YScale;
}
Input::Enter => {
@@ -1315,11 +1189,10 @@ impl Interactive for InsertM {
}
InsStage::YScale => {
let x = self.x_scale.unwrap_or(1.0);
// A number only: AutoCAD 2024 refuses a point here (measured).
let y = match i {
Input::Text(t) => nonzero(&t, NUMERIC)?,
Input::Text(t) => nonzero(&t)?,
Input::Enter => x,
_ => return Err(EngineError::Other(NUMERIC.into())),
_ => return Ok(Step::Continue),
};
self.scale = Some(Vec2::new(x, y));
if self.xyz {
@@ -1328,15 +1201,11 @@ impl Interactive for InsertM {
}
return self.advance(s);
}
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
InsStage::ZScale => {
self.z_scale = Some(match i {
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
Input::Text(t) => nonzero(&t)?,
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
Input::Point(p) => {
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
}
_ => return Err(EngineError::Other(SECOND_POINT.into())),
_ => return Ok(Step::Continue),
});
return self.advance(s);
}
@@ -1350,14 +1219,17 @@ impl Interactive for InsertM {
return self.advance(s);
}
InsStage::Rows | InsStage::Cols => {
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
let n = match i {
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
Input::Enter => Some(1),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
Input::Text(t) => t
.trim()
.parse::<f64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
.map(|v| v as u32)
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
Input::Enter => 1,
_ => return Ok(Step::Continue),
};
if self.stage == InsStage::Rows {
self.rows = Some(n);
} else {
@@ -1379,31 +1251,19 @@ impl Interactive for InsertM {
return self.advance(s);
}
}
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
InsStage::ColSpacing => {
return match i {
Input::Text(t) => {
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
self.advance(s)
}
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
Ok(Step::Continue)
}
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
if let Input::Text(t) = i {
self.col_spacing = Some(distance(&t)?);
return self.advance(s);
}
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
let v = match i {
Input::Text(t) => t,
// A canvas click is no answer to a text prompt: the dialog stays up and the
// attribute is asked for again, as Verify does. Enter keeps the default.
Input::Point(_) => return Ok(Step::Continue),
_ => default,
};
self.values.insert(tag, Value::String(v));
self.asked += 1;
return self.advance(s);
}
// Enter keeps the value typed.
@@ -1441,18 +1301,6 @@ impl Interactive for InsertM {
self.grid().apply(&mut ins);
vec![EntityKind::Insert(ins)]
}
fn attribute_entry(&self) -> Option<AttribEntry> {
// Only before the first answer: values typed at the command line go on there.
if !self.dialog || self.stage != InsStage::Attribs || self.asked > 0 || self.attdefs.is_empty() {
return None;
}
let rows = self
.attdefs
.iter()
.map(|(tag, prompt, default, verify)| AttribAsk { tag: tag.clone(), prompt: prompt.clone(), default: default.clone(), verify: *verify })
.collect();
Some(AttribEntry::idle(self.name.clone().unwrap_or_default(), rows))
}
}
mod attribs;
+7 -4
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,14 +102,17 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
t.value = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
+27 -124
View File
@@ -1,11 +1,11 @@
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
//! at a distance's grip sets the distance.
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -30,8 +30,7 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(Value::as_i64)
.and_then(|n| i32::try_from(n).ok())
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
let part =
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
@@ -47,25 +46,11 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
return Err("the reference is on a locked layer".into());
}
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
drag_in(s, &mut d, h, node, part, to)?;
dynblock::drag_grip(&mut d, h, node, part, to)?;
*s.doc_mut().map_err(|e| e.to_string())? = d;
Ok(())
}
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
let alignment = dynblock::reference(d, h)
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
if !alignment {
return dynblock::drag_grip(d, h, node, part, to);
}
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, s.viewport_frozen(), h);
dynblock::align_grip(d, h, node, to, near)
}
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
/// reference's (as the renderer draws a block's contents).
@@ -111,16 +96,13 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
Entity { handle: Handle(0), common, kind }
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
}));
out
}
@@ -132,16 +114,11 @@ struct DynGripEdit {
part: GripPart,
/// Where the grip is (the rubber band's start).
from: Vec2,
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
/// The property it changes, and whether it is a distance (a typed number sets it).
property: String,
shape: GripShape,
/// Where the grip can stop (a value list or increments): tick marks across its travel.
stops: Vec<(Vec2, Vec2)>,
distance: bool,
}
/// Half a tick mark's length, in pixels.
const TICK_PX: f64 = 6.0;
impl Interactive for DynGripEdit {
fn name(&self) -> &'static str {
"GRIP"
@@ -152,22 +129,19 @@ impl Interactive for DynGripEdit {
}
fn prompt(&self, _s: &Session) -> Prompt {
let (msg, accept) = match self.shape {
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
GripShape::Alignment => ("Specify point location", Accept::POINT),
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
let (msg, accept) = if self.distance {
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
} else {
("** STRETCH ** Specify stretch point", Accept::POINT)
};
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
if self.shape == GripShape::Rotation { p.angle() } else { p }
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let to = match i {
Input::Point(p) => p,
Input::Deferred(d) => d.at,
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
Input::Text(t) if self.distance => {
let mut d = s.doc()?.clone();
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
*s.doc_mut()? = d;
@@ -181,30 +155,9 @@ impl Interactive for DynGripEdit {
Ok(Step::Done)
}
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
let half = TICK_PX * s.pixel_size();
let mut out: Vec<EntityKind> = self
.stops
.iter()
.map(|(at, way)| {
let n = way.perp() * half;
crate::cmd::helpers::line(*at - n, *at + n)
})
.collect();
out.push(crate::cmd::helpers::line(self.from, c));
out
}
/// A rotation grip's angle at the cursor, as Properties will show it.
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
if self.shape != GripShape::Rotation {
return None;
}
let mut d = s.doc().ok()?.clone();
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
/// The rubber band from the grip.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
vec![crate::cmd::helpers::line(self.from, c)]
}
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
@@ -212,7 +165,7 @@ impl Interactive for DynGripEdit {
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
let Ok(d) = s.doc() else { return Vec::new() };
let mut d = d.clone();
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
Ok(()) => drawn(&d, self.handle),
Err(_) => Vec::new(),
}
@@ -221,8 +174,8 @@ impl Interactive for DynGripEdit {
impl Session {
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
/// its choices and sets them with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
if self.running.is_some() {
self.cancel();
@@ -231,67 +184,17 @@ impl Session {
.into_iter()
.find(|g| g.node == node && g.part == part)
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
if matches!(g.shape, GripShape::List | GripShape::Flip) {
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
if g.shape == GripShape::List {
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
}
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
let machine = crate::guard::Guarded::wrap(Box::new(edit));
let st = self.state()?;
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
self.pending_window = None;
self.point_mods.clear();
self.echo(label);
self.echo("** STRETCH **");
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
-3
View File
@@ -171,8 +171,6 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(override_arrows(dm));
}
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
// A dimension kept as read draws, and is saved with, the block it names (#3438).
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
}
}
@@ -190,7 +188,6 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(override_arrows(dm));
}
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
}
}
+15 -24
View File
@@ -8,9 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::super::curves::KW;
use super::super::file::{
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
};
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::modify::erase_kept;
use super::super::{CommandSpec, bad, point_param, str_param, targets};
@@ -48,7 +46,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
let (entities, bytes, lost, version) = match str_param(p, "name") {
Some("*") => write(s, "wblock", &path, Source::Whole)?,
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
@@ -56,7 +54,6 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
@@ -67,7 +64,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
let (entities, bytes, lost, version) = match str_param(p, "name") {
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
None => {
let hs = targets(s, p)?;
@@ -83,17 +80,16 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
/// the version it was written at, for the caller to report as a save does. The
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
let src = s.doc()?;
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
// block's base point for a block.
@@ -119,19 +115,14 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
// The written drawing's own version: the writer is given no other.
let version = own_version(&d, path);
let lost = lost_writing(&d, path, version);
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
Ok((d.model.len(), bytes.len(), lost, version, notes))
Ok((d.model.len(), bytes.len(), lost, version))
}
/// Say on the command line what the file written at `path` and `version` left out, and what a
/// DWG keeps only in part (`notes`).
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
/// Say on the command line what the file written at `path` and `version` left out.
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
if let Some(msg) = lost_message(path, version, lost) {
s.echo(msg);
}
for note in notes {
s.echo(note);
}
}
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
@@ -350,7 +341,7 @@ impl DashWblockM {
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
match write(s, "-wblock", &self.path, what) {
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
@@ -361,8 +352,8 @@ impl DashWblockM {
return Ok(Step::Done);
}
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
Ok((.., lost, version, notes)) => {
echo_not_saved(s, &self.path, version, &lost, notes);
Ok((.., lost, version)) => {
echo_not_saved(s, &self.path, version, &lost);
erase(s, hs)?;
}
Err(e) => s.echo(e.to_string()),
+6 -18
View File
@@ -79,27 +79,17 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let defs = s.clipboard_source.as_ref().map(|c| c.defs.clone());
let space = s.space();
let d = s.doc_mut()?;
let renames = defs.as_ref().map(|x| merge(d, x)).unwrap_or_default();
let renames = defs.map(|x| merge(d, &x)).unwrap_or_default();
let mut out = Vec::new();
let mut copies = Vec::new();
for e in &ents {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
if let Some(st) = d.space_mut(&space) {
st.push(e);
}
}
if let Some(c) = &defs
&& !c.groups.is_empty()
{
super::groups::replicate_groups_from(d, &c.groups, &copies);
} else {
super::groups::replicate_groups_for_copies(d, &copies);
}
s.set_selection(out.clone());
Ok(out)
}
@@ -275,15 +265,13 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
}
let mut d = Drawing::new_imperial();
d.header = src.header.clone();
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
d.layers = pick(&src.layers, &used.layers, |l| &l.name);
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into();
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
let ent_handles: HashSet<Handle> = ents.iter().map(|e| e.handle).collect();
d.groups = src.groups.iter().filter(|g| !g.members.is_empty() && g.members.iter().all(|m| ent_handles.contains(m))).cloned().collect();
d.layouts.clear();
d
}
+1 -1
View File
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
if let Some(a) = annotative {
st.annotative = a;
}
let name = match d.dim_styles.by_name_mut(&name) {
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(existing) if replace => {
let kept = existing.name.clone();
*existing = DimStyle { name: kept.clone(), ..st };
+7 -5
View File
@@ -9,7 +9,10 @@ use super::helpers::{arc, circle, line, lwpoly, polygon_from_edge, polygon_typed
use super::machines::number;
use super::pline_opts::{Outcome, PlineAsk};
use super::{CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param};
use super::{
CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, find_command, point_param, point_req, point_value, points_param, size_param,
str_param,
};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, snap};
@@ -29,8 +32,7 @@ use line_pline::{LineM, PlineM, run_line, run_pline};
use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray};
use polygon::{PolygonM, run_polygon};
use solid::{SolidM, run_solid};
pub(super) use spline::SplineM;
use spline::run_spline;
use spline::{SplineM, run_spline};
use text::{MTextM, TextM, run_mtext, run_text};
pub(crate) use text::{justify, justify_prompt};
@@ -47,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pline", "Polyline", run_pline)
.menu(&["Draw", "Polyline"])
.alias(&["pl"])
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
.interactive(|_| Ok(Box::new(PlineM::default()))),
CommandSpec::new("circle", "Circle", run_circle)
.menu(&["Draw", "Circle", "Center, Radius"])
@@ -62,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
.menu(&["Draw", "Rectangle"])
.alias(&["rec", "rectangle"])
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
CommandSpec::new("polygon", "Polygon", run_polygon)
.menu(&["Draw", "Polygon"])
+3 -21
View File
@@ -45,21 +45,15 @@ fn current_elevation(s: &Session) -> Result<f64> {
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
let mut vertex_widths = false;
for v in raw.into_iter().flatten() {
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
size_param("pline", v, "startWidth", true)?;
size_param("pline", v, "endWidth", true)?;
}
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
if vs.len() < 2 {
return Err(bad("pline", "`vertices` needs at least 2 points"));
}
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
// give their own widths).
let width = match size_param("pline", p, "width", true)? {
Some(w) => w,
None if vertex_widths => 0.0,
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
};
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
@@ -272,11 +266,8 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
let w = s.doc()?.header.f64("PLINEWID", 0.0);
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
@@ -325,11 +316,6 @@ impl Interactive for PlineM {
self.end_w = self.start_w;
}
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
if self.asking_width == 0 {
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
}
return Ok(Step::Continue);
}
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
@@ -393,10 +379,6 @@ impl Interactive for PlineM {
l.bulge = 0.0;
(l.start_width, l.end_width) = (0.0, 0.0);
}
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
// to "Specify next point", where `_L` is Length, not arc mode's Line).
let n = self.verts.len();
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
self.sync(s, false)?;
Ok(Step::Continue)
}
+23 -41
View File
@@ -1,7 +1,7 @@
use super::{
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, points_param,
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, find_command,
points_param,
};
use crate::cmd::draw2::SplineCvM;
pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("object").is_some() {
@@ -26,11 +26,11 @@ pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
}
#[derive(Default)]
pub(in crate::cmd) struct SplineM {
pub(super) struct SplineM {
pts: Vec<Vec2>,
asking_method: bool,
/// Both entry points share Method and Object; CV handles its own points and degree.
cv: Option<SplineCvM>,
/// `Method` > `CV` hands over to the control-vertex machine (`spline.cv`).
delegate: Option<Box<dyn Interactive>>,
/// Knots, end tangents and fit tolerance chosen so far.
opts: cadcraft_geom::FitOptions,
/// An option asking a further question (Knots, Tangency, toLerance, Object).
@@ -38,10 +38,6 @@ pub(in crate::cmd) struct SplineM {
}
impl SplineM {
pub(in crate::cmd) fn cv() -> Self {
Self { cv: Some(SplineCvM::default()), ..Self::default() }
}
fn make(&self, closed: bool) -> Spline {
Spline::fit_with(&self.pts, closed, self.opts)
}
@@ -53,25 +49,18 @@ impl Interactive for SplineM {
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.opts.knots = crate::cmd::spline_opts::current_knots(s);
if let Some(cv) = &mut self.cv {
return cv.begin(s);
}
s.echo(format!("Current settings: Method=Fit Knots={}", self.opts.knots.name()));
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
if let Some(d) = &self.delegate {
return d.prompt(s);
}
if let Some(a) = &self.ask {
return a.prompt(&self.opts, &self.pts);
}
if self.asking_method {
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default(if self.cv.is_some() {
"CV"
} else {
"Fit"
});
}
if let Some(cv) = &self.cv {
return cv.prompt(s);
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default("Fit");
}
match self.pts.len() {
0 => Prompt::new("Specify first point", Accept::POINT).kw(&["Method", "Knots", "Object"]),
@@ -83,6 +72,9 @@ impl Interactive for SplineM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some(d) = &mut self.delegate {
return d.input(s, i);
}
if let Some(a) = &mut self.ask {
use crate::cmd::spline_opts::Outcome;
return match a.input(s, i, &mut self.opts, &self.pts)? {
@@ -104,32 +96,24 @@ impl Interactive for SplineM {
if self.asking_method {
match i {
Input::Keyword(k) if k == "CV" => {
let Some(factory) = find_command("spline.cv").and_then(|c| c.interactive) else {
return Err(crate::EngineError::Other("CV: not available yet".into()));
};
let mut m = factory(s)?;
self.asking_method = false;
return self.cv.get_or_insert_with(SplineCvM::default).begin(s);
let step = m.begin(s)?;
self.delegate = Some(m);
return Ok(step);
}
Input::Keyword(k) if k == "Fit" => {
self.asking_method = false;
self.cv = None;
return self.begin(s);
}
Input::Enter => self.asking_method = false,
Input::Keyword(_) | Input::Enter => self.asking_method = false,
Input::Text(_) => return Err(crate::EngineError::Other("Invalid option keyword.".into())),
_ => {}
}
return Ok(Step::Continue);
}
if let Some(cv) = &mut self.cv
&& !matches!(&i, Input::Keyword(k) if k == "Method" || k == "Object")
{
return cv.input(s, i);
}
match i {
Input::Point(p) => {
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
// nor a kink.
if self.pts.last() != Some(&p) {
self.pts.push(p);
}
self.pts.push(p);
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -164,8 +148,8 @@ impl Interactive for SplineM {
}
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if let Some(cv) = &self.cv {
return cv.preview(s, c);
if let Some(d) = &self.delegate {
return d.preview(s, c);
}
if self.pts.is_empty() {
return Vec::new();
@@ -179,8 +163,6 @@ impl Interactive for SplineM {
}
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
Some(_) => {}
// The cursor on the last point adds nothing, as a click there doesn't.
None if pts.last() == Some(&c) => {}
None => pts.push(c),
}
if pts.len() < 2 {
+3 -4
View File
@@ -7,7 +7,7 @@ use cadcraft_geom::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Spline, TA
use serde_json::{Value, json};
use super::curves::{self, Chain, MAX_GEN, TanObj};
use super::helpers::{arc, circle, line, lwpoly, rect_corners_fit, rect_vertices, rect_with_corners, v3};
use super::helpers::{arc, circle, line, lwpoly, rect_vertices, rect_with_corners, v3};
use super::machines::number;
use super::{CommandSpec, bad, bool_or, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param, targets};
@@ -28,8 +28,7 @@ mod xline;
pub(crate) use arc::arc_machine;
use arc::{ArcContinueM, ArcV, run_arc_continue, run_arc_variant, seq};
use centermark::{CenterM, run_centerline, run_centermark};
pub(super) use curves3d::SplineCvM;
use curves3d::{HelixM, Poly3dM, run_3dpoly, run_helix, run_spline_cv};
use curves3d::{HelixM, Poly3dM, SplineCvM, run_3dpoly, run_helix, run_spline_cv};
use divide::{DivideM, run_divide, run_measure};
use ellipse::{run_ellipse_arc, run_ellipse_axis};
pub(crate) use rect::{RectM2, run_rectang2};
@@ -150,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("spline.cv", "Control Vertices", run_spline_cv)
.menu(&["Draw", "Spline", "Control Vertices"])
.params("{control: [[x,y],...], degree?: 1..10 (default 3), closed?}")
.interactive(|_| Ok(Box::new(super::draw::SplineM::cv()))),
.interactive(|_| Ok(Box::new(SplineCvM::default()))),
CommandSpec::new("centermark", "Center Mark", run_centermark)
.menu(&["Draw", "Center Mark"])
.params("{handle | handles} (circles/arcs; lines on the CENTER linetype)")
+3 -5
View File
@@ -284,7 +284,7 @@ pub(super) fn run_spline_cv(s: &mut Session, p: &Value) -> Result<Value> {
}
#[derive(Default)]
pub(in crate::cmd) struct SplineCvM {
pub(super) struct SplineCvM {
pts: Vec<Vec2>,
degree: Option<usize>,
asking_degree: bool,
@@ -312,9 +312,7 @@ impl Interactive for SplineCvM {
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if self.asking_degree {
if let Input::Text(t) = &i {
let d = number(t)
.filter(|d| d.fract() == 0.0 && (1.0..=10.0).contains(d))
.ok_or_else(|| other("Degree must be a whole number from 1 to 10."))?;
let d = number(t).filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| other("Degree must be 1..10."))?;
self.degree = Some(d as usize);
}
self.asking_degree = false;
@@ -342,7 +340,7 @@ impl Interactive for SplineCvM {
s.add_entity(EntityKind::Spline(sp))?;
return Ok(Step::Done);
}
_ => return Err(other("Invalid option keyword.")),
_ => s.echo(format!("{k}: use SPLINE for fit points.")),
}
Ok(Step::Continue)
}
+14 -33
View File
@@ -139,15 +139,6 @@ impl DivideM {
pub(super) fn new(measure: bool) -> Self {
DivideM { measure, obj: None, phase: DivPhase::Object, block: None, align: true }
}
/// The JSON form's parameters for the picked object, before the count or length.
fn params(&self, h: Handle, pick: Vec2) -> Value {
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
params
}
}
impl Interactive for DivideM {
@@ -196,37 +187,27 @@ impl Interactive for DivideM {
self.phase = DivPhase::Value;
Ok(Step::Continue)
}
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let v = match inp {
Input::Text(t) => number(&t).ok_or_else(|| other("Requires a number."))?,
Input::Point(q) => pick.dist(q),
_ => return Ok(Step::Continue),
};
let mut params = self.params(h, pick);
params["length"] = json!(v);
run_measure(s, &params)?;
Ok(Step::Done)
}
(DivPhase::Value, inp) if !self.measure => {
// A whole number as typed: AutoCAD 2024 takes +5 and 05 here and refuses 5.0, 5.,
// 1e1, 4.5, 1, 32768, x, Enter and a point, naming the Block keyword while the
// prompt still offers it (measured).
let n = match inp {
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| (2..=32767).contains(n)),
_ => None,
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
if self.measure {
params["length"] = json!(v);
run_measure(s, &params)?;
} else {
if !(2.0..=32767.0).contains(&v) || v.fract() != 0.0 {
return Err(other("Requires an integer between 2 and 32767."));
}
params["segments"] = json!(v as u64);
run_divide(s, &params)?;
}
.ok_or_else(|| {
other(if self.block.is_some() {
"Requires an integer between 2 and 32767."
} else {
"Requires an integer between 2 and 32767, or option keyword."
})
})?;
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let mut params = self.params(h, pick);
params["segments"] = json!(n);
run_divide(s, &params)?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Cancel),
+16 -42
View File
@@ -1,6 +1,6 @@
use super::{
Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly,
number, other, point_param, point_req, rect_corners_fit, rect_with_corners, size_param,
number, other, point_param, point_req, rect_with_corners, size_param,
};
use crate::last_used::RectangModes;
@@ -19,30 +19,9 @@ fn rect_kind(first: Vec2, (w, h): (f64, f64), rot: f64, fillet: f64, chamfer: (f
k
}
/// The area a fillet's or chamfer's four corners take off the full rectangle (a fillet wins).
fn corner_area(fillet: f64, chamfer: (f64, f64)) -> f64 {
if fillet > 0.0 {
(4.0 - std::f64::consts::PI) * fillet * fillet
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
2.0 * chamfer.0 * chamfer.1
} else {
0.0
}
}
/// The sides of the rectangle of `area` with one side `side`, its length (or with `breadth`,
/// its width). AutoCAD sizes it so that the outline, corners cut, encloses the area: the corners'
/// area is added back. When the corners then don't fit they stay square, and the area is the full
/// rectangle's.
fn area_sides(area: f64, side: f64, breadth: bool, fillet: f64, chamfer: (f64, f64)) -> (f64, f64) {
let sides = |a: f64| if breadth { (a / side, side) } else { (side, a / side) };
let (w, h) = sides(area + corner_area(fillet, chamfer));
if rect_corners_fit(Vec2::new(w, h), fillet, chamfer) { (w, h) } else { sides(area) }
}
/// The width and height of a rectangle from its `dimensions`, its `p2` corner, its `area` with
/// `length` or `breadth`, or its second corner `p2`, rotated by `rot` about `a`.
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)> {
Ok(if let Some(d) = p.get("dimensions").and_then(Value::as_array) {
let l = d.first().and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
let wd = d.get(1).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
@@ -59,8 +38,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer:
return Err(bad("rectang", "area must be positive"));
}
match (p.get("length").and_then(Value::as_f64), p.get("breadth").and_then(Value::as_f64)) {
(Some(l), _) if l.is_finite() && l > 0.0 => area_sides(area, l, false, fillet, chamfer),
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
}
} else {
@@ -89,7 +68,7 @@ pub(crate) fn run_rectang2(s: &mut Session, p: &Value) -> Result<Value> {
}
let fillet = size_param("rectang", p, "fillet", true)?.unwrap_or(0.0);
let width = size_param("rectang", p, "width", true)?.unwrap_or(0.0);
let (w, h) = rect_size(p, a, rot, centered, fillet, ch)?;
let (w, h) = rect_size(p, a, rot, centered)?;
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
return Err(bad("rectang", "rectangle has no area"));
}
@@ -137,13 +116,10 @@ pub(crate) struct RectM2 {
asking: Option<RAsk>,
}
/// A rectangle's rotation (radians counterclockwise from +X) as AutoCAD 2024 shows it: from
/// ANGBASE in the ANGDIR sense, in the drawing's angle units, to two places. Rotation 30 typed
/// with ANGBASE 90 and ANGDIR 1 shows as "120.00", and 30.5 in degrees/minutes/seconds as
/// "30d30'".
fn rotation_text(s: &Session, rotation: f64) -> String {
let au = s.angle_settings();
crate::units::format_angle(au.shown(rotation), au.aunits, 2)
/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals.
fn rotation_text(rotation: f64) -> String {
let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0));
if t == "360.00" { "0.00".into() } else { t }
}
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
@@ -168,10 +144,9 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
if m.width > 0.0 {
parts.push(format!("Width={}", d(m.width)));
}
// Listed when the rectangle is turned from +X at all, to two places, whatever ANGBASE says.
let turned = format!("{:.2}", m.rotation.to_degrees().rem_euclid(360.0));
if turned != "0.00" && turned != "360.00" {
parts.push(format!("Rotation={}", rotation_text(s, m.rotation)));
let rot = rotation_text(m.rotation);
if rot != "0.00" {
parts.push(format!("Rotation={rot}"));
}
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
}
@@ -244,7 +219,7 @@ impl Interactive for RectM2 {
}
/// Asks for the pending option's value, or for the first and second points; in centre mode
/// the first prompt asks for the centre instead of a corner.
fn prompt(&self, s: &Session) -> Prompt {
fn prompt(&self, _s: &Session) -> Prompt {
let num = |m: &str, d: f64| Prompt::new(m, Accept::NUMBER).default(format!("{d:.4}"));
if let Some(a) = self.asking {
return match a {
@@ -262,7 +237,7 @@ impl Interactive for RectM2 {
RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)),
RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER)
.kw(&["Pick points"])
.default(rotation_text(s, self.rotation))
.default(rotation_text(self.rotation))
.base_opt(self.first),
RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT),
RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
@@ -324,7 +299,7 @@ impl Interactive for RectM2 {
self.asking = Some(a);
return Err(other("Value must be positive."));
}
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
return self.make(s, w, h);
}
RAsk::DimL => {
@@ -339,8 +314,7 @@ impl Interactive for RectM2 {
RAsk::Rotation => match i {
Input::Keyword(_) => self.asking = Some(RAsk::RotPick1),
Input::Point(p) => self.rotation = self.first.map(|f| f.angle_to(p)).unwrap_or(0.0),
// An amount turned in the ANGDIR sense from +X, ANGBASE aside, as AutoCAD takes it.
Input::Text(t) => self.rotation = s.angle_settings().rotation(&t).ok_or_else(|| other("Requires a valid angle."))?,
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
_ => {}
},
RAsk::RotPick1 => {
+1 -5
View File
@@ -26,10 +26,6 @@ fn default_max_arc_len(s: &Session, min: f64) -> f64 {
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
}
/// The bulge of every arc of a revision cloud (an arc of about 110°). Readers that check
/// `RevcloudProps` xdata and bulge accept a closed polyline whose bulges are within 0.02 of this.
const CLOUD_BULGE: f64 = 0.520567050552;
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
let mut pts: Vec<Vec2> = Vec::new();
@@ -73,7 +69,7 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re
out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0));
}
}
let b = if reverse { -CLOUD_BULGE } else { CLOUD_BULGE };
let b = if reverse { -0.5 } else { 0.5 };
Some(out.into_iter().map(|p| PolyVertex::with_bulge(p, b)).collect())
}
+5 -251
View File
@@ -729,57 +729,6 @@ fn divide_and_measure_command_line() {
s.cancel();
}
#[test]
fn divide_takes_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter the number of segments or [Block]:": +5, 05, the LISP real 5.0 and
// 32767 are taken; 5.0, 5., 1e1, 4.5, 1, 0, -3, 32768, x, Enter and a point from LISP are
// refused and asked again (measured).
let points = |s: &Session| kinds(s).iter().filter(|k| **k == "Point").count();
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
let asked = s.prompt_text();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments or [Block]:"));
for bad in ["5.0", "5.", "1e1", "4.5", "1", "0", "-3", "32768", "x", "", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 2 and 32767, or option keyword."], "{bad:?}");
assert_eq!(s.prompt_text(), asked, "{bad:?}");
}
assert_eq!(points(&s), 0);
s.cmdline("+5").unwrap();
assert!(s.running.is_none());
assert_eq!(points(&s), 4);
for (typed, n) in [("05", 4), ("(+ 2.5 2.5)", 4), ("2", 1), ("32767", 32766)] {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
s.cmdline(typed).unwrap();
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
assert_eq!(points(&s), n, "{typed}");
}
// MEASURE shares the prompt machine and is unchanged: Enter at its length still ends it.
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("measure 5,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(points(&s), 0);
// After Block the prompt offers no keyword, and the message names none (AutoCAD 2024, measured).
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let tick = s.execute("circle", &json!({"center": [50, 50], "radius": 0.1})).unwrap();
s.execute("block", &json!({"name": "DOT", "base": [50, 50], "handles": [h(&tick)], "keep": "delete"})).unwrap();
s.cmdline("divide 5,0 b DOT y").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments:"));
s.cmdline("5.0").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 2 and 32767."));
s.cmdline("5").unwrap();
assert!(s.running.is_none());
assert_eq!(kinds(&s).iter().filter(|k| **k == "Block Reference").count(), 4);
}
// ---------------- REVCLOUD ----------------
#[test]
@@ -1152,198 +1101,6 @@ fn rectang_options_command_line() {
}
}
/// RECTANG against what AutoCAD 2024 stores for the same typed input (black-box: synthetic
/// input in accoreconsole, read back with `entget`): Area with the corners taken off, and
/// corners too large for the sides.
#[test]
fn rectang_area_and_oversized_corners_match_autocad() {
type Case = (&'static [&'static str], &'static [[f64; 3]], [f64; 3]);
// (typed input, vertices [x, y, bulge], [width, elevation, thickness])
let cases: [Case; 4] = [
// RECTANG-028: Area counts the chamfered corners off.
(
&["rectang _C 1.5 2.5 26.36462345136234,-19.7291241693893 _R 0 _A 1442.9297064464572 _W 35.53488991311575"],
&[
[26.36462345136234, -18.2291241693893, 0.0],
[28.86462345136234, -19.7291241693893, 0.0],
[65.68168268505678, -19.7291241693893, 0.0],
[67.18168268505678, -17.2291241693893, 0.0],
[67.18168268505678, 14.30576574372644, 0.0],
[64.68168268505678, 15.80576574372644, 0.0],
[27.86462345136234, 15.80576574372644, 0.0],
[26.36462345136234, 13.30576574372644, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-035-VN: Area counts the fillets off, at survey coordinates.
(
&["rectang _F 2.0 612322.0691653182,2398792.948957577 _R 0 _A 592.8936847254046 _L 19.287858563349488"],
&[
[612322.0691653182, 2398794.948957577, 0.414213562373095],
[612324.0691653182, 2398792.948957577, 0.0],
[612339.3570238815, 2398792.948957577, 0.414213562373095],
[612341.3570238815, 2398794.948957577, 0.0],
[612341.3570238815, 2398821.866195597, 0.414213562373095],
[612339.3570238815, 2398823.866195598, 0.0],
[612324.0691653182, 2398823.866195598, 0.414213562373095],
[612322.0691653182, 2398821.866195597, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-029: a fillet too large: each corner two coincident vertices.
(
&["rectang _F 11.37084114989061 -21.46774953784037,-0.023473793210982308 _R 0 -2.5163476213560187,49.88119923361903"],
&[
[-21.46774953784036, -0.0234737932109823, 0.0],
[-21.46774953784036, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-039-VN: a chamfer too large, rotated, with Dimensions.
(
&[
"rectang _C 18.656567079201356 18.656567079201356 612317.9599920243,2398739.0200147885 _R 30 _D 26.652238684573366 32.64533161964191 612344.6122307089,2398771.6653464083",
],
&[
[612317.9599920243, 2398739.020014788, 0.0],
[612317.9599920243, 2398739.020014788, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
],
[0.0, 0.0, 0.0],
),
];
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
for (input, want, [width, elevation, thickness]) in cases {
let mut s = Session::new();
for line in input {
s.cmdline(line).unwrap();
assert!(s.running.is_none(), "{line}: {}", s.prompt_text());
}
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{input:?}: {:?}", e.kind) };
let got: Vec<[f64; 3]> = p.vertices.iter().map(|v| [v.p.x, v.p.y, v.bulge]).collect();
let ok = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.iter().zip(w).all(|(a, b)| same(*a, *b)));
assert!(
ok,
"{input:?}
got {got:?}
want {want:?}"
);
assert!(p.closed && same(p.const_width, width) && same(p.elevation, elevation) && same(e.common.thickness, thickness), "{input:?}");
}
// Rotation, elevation and thickness are remembered too: AutoCAD opens the next RECTANG with
// "Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96".
let mut s = Session::new();
s.cmdline("rectang _E 7.5 _T 2.25 0,0 _R _P 0,0 10,6 10,20").unwrap();
s.cmdline("rectang 100,100 110,105").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!(p.vertices[0].p == Vec2::new(100.0, 100.0) && same(edge.angle(), 6f64.atan2(10.0)), "{p:?}");
assert!(p.elevation == 7.5 && e.common.thickness == 2.25);
}
/// RECTANG's Rotation follows the drawing's angle settings as AutoCAD 2024's does.
#[test]
fn rectang_rotation_follows_the_angle_settings() {
let modes = |s: &Session| s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).cloned().collect::<Vec<_>>();
// With ANGBASE 90 and ANGDIR 1, AutoCAD 2024 turns a rectangle given Rotation 30 clockwise
// by 30° from +X (ANGBASE aside), and shows that rotation from ANGBASE: "Rotation=120.00",
// and <120.00> as the next rotation default.
let mut s = Session::new();
s.cmdline("setvar angbase 90").unwrap();
s.cmdline("setvar angdir 1").unwrap();
s.cmdline("rectang 50,0 _R 30 60,5").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!((edge.y.atan2(edge.x) + 30f64.to_radians()).abs() < 1e-9, "{p:?}");
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=120.00"]);
s.cmdline("50,0").unwrap();
s.cmdline("_R").unwrap();
assert!(s.prompt_text().contains("<120.00>"), "{}", s.prompt_text());
s.cancel();
// In degrees/minutes/seconds: "Rotation=30d30'".
let mut s = Session::new();
s.cmdline("setvar aunits 1").unwrap();
s.cmdline("rectang 50,0 _R 30.5 60,5").unwrap();
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=30d30'"]);
s.cancel();
}
/// Area allows for cut corners only while they fit: a fillet too large for the resulting sides
/// leaves square corners, so the rectangle is the full area asked for (4 × 1, not 4 × 1.858).
/// Corners exactly as long as the shorter side allows still fit; a hair longer and the corners
/// stay square, each still written twice (AutoCAD 2024, `entget` of a 4 x 2 rectangle).
#[test]
fn rectang_corners_at_the_limit_fit_and_just_over_stay_square() {
let b = (std::f64::consts::PI / 8.0).tan();
let fit: [(&str, &[(f64, f64, f64)]); 4] = [
(
"_F 0.9999",
&[
(0.0, 0.9999, b),
(0.9999, 0.0, 0.0),
(3.0001, 0.0, b),
(4.0, 0.9999, 0.0),
(4.0, 1.0001, b),
(3.0001, 2.0, 0.0),
(0.9999, 2.0, b),
(0.0, 1.0001, 0.0),
],
),
("_F 1", &[(0.0, 1.0, b), (1.0, 0.0, 0.0), (3.0, 0.0, b), (4.0, 1.0, 0.0), (4.0, 1.0, b), (3.0, 2.0, 0.0), (1.0, 2.0, b), (0.0, 1.0, 0.0)]),
(
"_C 1 1",
&[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (3.0, 0.0, 0.0), (4.0, 1.0, 0.0), (4.0, 1.0, 0.0), (3.0, 2.0, 0.0), (1.0, 2.0, 0.0), (0.0, 1.0, 0.0)],
),
(
"_C 1.2 0.8",
&[(0.0, 1.2, 0.0), (0.8, 0.0, 0.0), (2.8, 0.0, 0.0), (4.0, 0.8, 0.0), (4.0, 0.8, 0.0), (3.2, 2.0, 0.0), (1.2, 2.0, 0.0), (0.0, 1.2, 0.0)],
),
];
let square =
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 2.0, 0.0), (4.0, 2.0, 0.0), (0.0, 2.0, 0.0), (0.0, 2.0, 0.0)];
let over: [(&str, &[(f64, f64, f64)]); 2] = [("_F 1.0001", &square), ("_C 1.2 0.81", &square)];
for (corners, want) in fit.into_iter().chain(over) {
let mut s = Session::new();
s.cmdline(&format!("rectang {corners} 0,0 4,2")).unwrap();
let EntityKind::LwPolyline(p) = last(&s) else { panic!("no polyline") };
let got: Vec<(f64, f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect();
let ok = got.len() == want.len()
&& got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-6);
assert!(ok, "{corners}: {got:?}");
}
}
#[test]
fn rectang_area_with_corners_too_large_stays_exact() {
let check = |s: &Session| {
let pts = rect_pts(s);
let b = cadcraft_geom::Bounds2::from_points(pts.clone());
assert!(near(b.min, 0.0, 0.0) && near(b.max, 4.0, 1.0), "{pts:?}");
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
};
let mut s = Session::new();
s.cmdline("rectang _F 2 0,0 _A 4 _L 4").unwrap();
check(&s);
s.execute("rectang", &json!({"p1": [0, 0], "area": 4, "length": 4, "fillet": 2})).unwrap();
check(&s);
}
/// Guards the JSON `center: true` form for every sizing route: a picked corner mirrored about
/// the centre, full-size `dimensions`, full `area`, rotation about the centre, that the default
/// corner mode is untouched, and that centre mode without a size is rejected.
@@ -1379,7 +1136,7 @@ fn rectang_center_mode_json() {
}
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
#[test]
fn rectang_center_mode_honours_options() {
let mut s = Session::new();
@@ -1396,11 +1153,9 @@ fn rectang_center_mode_honours_options() {
assert_eq!(rect_pts(&s).len(), 8);
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// A fillet too large for the rectangle leaves sharp corners, each one two coincident vertices
// as in AutoCAD, still centred.
// A fillet too large for the rectangle falls back to sharp corners, still centred.
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
let pts = rect_pts(&s);
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
assert_eq!(rect_pts(&s).len(), 4);
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
}
@@ -1428,9 +1183,8 @@ fn rectang_center_mode_command_line() {
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// Area too: the rectangle of that area is centred on the first point (without the fillet
// remembered from above, which would take its corners off the area).
s.cmdline("rectang f 0 ce 10,10 a 96 l 8").unwrap();
// Area too: the rectangle of that area is centred on the first point.
s.cmdline("rectang ce 10,10 a 96 l 8").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
+17 -39
View File
@@ -63,11 +63,19 @@ enum Order {
Under,
}
fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order) -> usize {
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front => {
for (_, h) in &moving {
@@ -79,29 +87,6 @@ fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order
st.send_to_back(*h);
}
}
Order::Above | Order::Under => {}
}
moving.len()
}
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
if matches!(order, Order::Front | Order::Back) {
return Ok(reorder_store(st, hs, order));
}
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front | Order::Back => {}
Order::Above => {
let Some(&(_, mut cur)) = refs.iter().max() else { return Err(EngineError::Other("no reference objects".into())) };
for (_, h) in &moving {
@@ -196,23 +181,15 @@ impl Annot {
}
}
/// Reorder objects across all spaces (model space and all paper space layouts).
fn reorder_all_spaces(s: &mut Session, order: Order, keep: impl Fn(&EntityKind) -> bool) -> Result<usize> {
let d = s.doc_mut()?;
let mut total = 0;
// Model space
let hs: Vec<Handle> = d.model.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut d.model, &hs, order);
// All paper space layouts
for layout in &mut d.layouts {
let hs: Vec<Handle> = layout.entities.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut layout.entities, &hs, order);
}
Ok(total)
/// Every object of the current space that `keep` accepts, in draw order.
fn of_kind(s: &Session, keep: impl Fn(&EntityKind) -> bool) -> Result<Vec<Handle>> {
let d = s.doc()?;
Ok(d.space(&s.space()).map(|st| st.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect()).unwrap_or_default())
}
fn annotations_to_front(s: &mut Session, which: Annot) -> Result<Value> {
let n = reorder_all_spaces(s, Order::Front, |k| which.matches(k))?;
let hs = of_kind(s, |k| which.matches(k))?;
let n = reorder(s, &hs, Order::Front, &[])?;
Ok(json!({ "moved": n, "message": format!("{n} object(s) brought to front.") }))
}
@@ -231,7 +208,8 @@ fn run_texttofront(s: &mut Session, p: &Value) -> Result<Value> {
}
fn run_hatchtoback(s: &mut Session, _p: &Value) -> Result<Value> {
let n = reorder_all_spaces(s, Order::Back, |k| matches!(k, EntityKind::Hatch(_)))?;
let hs = of_kind(s, |k| matches!(k, EntityKind::Hatch(_)))?;
let n = reorder(s, &hs, Order::Back, &[])?;
Ok(json!({ "moved": n, "message": format!("{n} hatch object(s) sent to back.") }))
}
+19 -188
View File
@@ -1,5 +1,5 @@
//! Moving drawings in and out: EXPORT (DXF, DWG, SVG, PNG or PDF), IMPORT (the objects of another
//! DXF/DWG file or a PDF page), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
//! DXF/DWG file), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
//! ATTACH, SHARE and 3DORBIT are registered so the tool bar and command line say they are not
//! available yet.
//!
@@ -35,15 +35,11 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("import", "Import...", run_import)
.menu(&["File", "Import..."])
.alias(&["imp"])
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG; PDF pages can be imported too), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
CommandSpec::new("pdfimport", "Import PDF...", run_pdfimport)
.menu(&["File", "Import PDF..."])
.alias(&["pdfi"])
.params("{path | data: base64, name?: \"x.pdf\", page?: 1.. (default 1), password?, at?: [x,y] (default 0,0), scale?: (default 1), text?: true, fills?: true, lineweights?: true} → {imported, handles, layers, pages, page, warnings?}: vector paths, fills and supported text become editable objects; raster images and other unsupported content are reported. A scanned PDF has no editable vector content"),
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data, warnings?: what an image draws short of the drawing}")
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -123,7 +119,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)"));
}
let file = format!("export.{format}");
let (bytes, notes) = super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?;
let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?;
let folder = path.and_then(super::file::new_folder);
let mut r = match path {
Some(path) => {
@@ -134,164 +130,33 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
};
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
// ---------- IMPORT ----------
/// A PDF page reader installed by the app that links the PDF library.
pub type PdfImportHook = fn(&[u8], &Value) -> std::result::Result<(Drawing, usize), String>;
static PDF_IMPORT: std::sync::OnceLock<PdfImportHook> = std::sync::OnceLock::new();
/// Install the PDF page reader used by OPEN, IMPORT and PDFIMPORT.
pub fn set_pdf_import(hook: PdfImportHook) {
let _ = PDF_IMPORT.set(hook);
}
fn is_pdf(bytes: &[u8]) -> bool {
bytes.starts_with(b"%PDF-")
}
/// Read a PDF's first page as a metric drawing when this host has installed a PDF reader.
pub(super) fn open_pdf(bytes: &[u8]) -> Option<std::result::Result<Drawing, String>> {
if !is_pdf(bytes) {
return None;
}
let read = PDF_IMPORT.get()?;
Some(read(bytes, &json!({ "unit": 25.4 / 72.0 })).and_then(|(drawing, _)| {
if drawing.model.is_empty() {
let notes = drawing.read_notes.join("; ");
let message = if notes.is_empty() {
"PDF page 1 has no editable vector content; scanned drawings need manual tracing".to_string()
} else {
format!("PDF page 1 has no editable vector content; scanned drawings need manual tracing. {notes}")
};
Err(message)
} else {
Ok(drawing)
}
}))
}
/// Read an import source from a path or base64 data.
fn source_file(cmd: &str, p: &Value, default_name: &str) -> Result<(Vec<u8>, String)> {
if let Some(path) = str_param(p, "path") {
return Ok((read_file(path)?, path.to_string()));
}
let data = str_param(p, "data").ok_or_else(|| bad(cmd, "`path` or `data` (base64) is required"))?;
Ok((base64_decode(data).ok_or_else(|| bad(cmd, "invalid base64"))?, str_param(p, "name").unwrap_or(default_name).to_string()))
}
/// Parse the optional insertion point and scale shared by import commands.
fn placement(cmd: &str, p: &Value) -> Result<(Vec2, f64)> {
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
let at = match p.get("at") {
Some(v) => point_value(v).ok_or_else(|| bad(cmd, "`at` must be a point [x, y]"))?,
Some(v) => point_value(v).ok_or_else(|| bad("import", "`at` must be a point [x, y]"))?,
None => Vec2::ZERO,
};
let scale = match p.get("scale") {
Some(v) => {
v.as_f64().filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs())).ok_or_else(|| bad(cmd, "`scale` must be a non-zero number"))?
}
Some(v) => v
.as_f64()
.filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs()))
.ok_or_else(|| bad("import", "`scale` must be a non-zero number"))?,
None => 1.0,
};
Ok((at, scale))
}
fn source_name(name: &str) -> String {
std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()
}
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
let (at, scale) = placement("import", p)?;
let (bytes, name) = source_file("import", p, "import.dxf")?;
if is_pdf(&bytes) {
return import_pdf(s, "import", p, &bytes, &name, at, scale);
}
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
let (bytes, name) = if let Some(path) = str_param(p, "path") {
(read_file(path)?, path.to_string())
} else {
let data = str_param(p, "data").ok_or_else(|| bad("import", "`path` or `data` (base64) is required"))?;
(base64_decode(data).ok_or_else(|| bad("import", "invalid base64"))?, str_param(p, "name").unwrap_or("import.dxf").to_string())
};
let src = (hooks.read)(&bytes, &name).map_err(|e| bad("import", e))?;
import_drawing(s, &src, at, scale, &source_name(&name))
}
/// Convert millimetres to the current drawing's `$INSUNITS`.
fn units_per_mm(d: &Drawing) -> f64 {
match d.header.i64("INSUNITS", 4) {
1 => 1.0 / 25.4,
2 => 1.0 / 304.8,
3 => 1.0 / 1_609_344.0,
5 => 0.1,
6 => 0.001,
7 => 1e-6,
8 => 39_370.078_74,
9 => 39.370_078_74,
10 => 1.0 / 914.4,
11 => 1e7,
12 => 1e6,
13 => 1e3,
14 => 0.01,
15 => 1e-4,
16 => 1e-5,
17 => 1e-12,
18 => 1.0 / 1.495_978_707e14,
19 => 1.0 / 9.460_730_472_580_8e18,
20 => std::f64::consts::PI / (648_000.0 * 1.495_978_707e14),
// US survey units: a survey foot is 1200/3937 m.
21 => 3937.0 / 1_200_000.0,
22 => 3937.0 / 100_000.0,
23 => 3937.0 / 3_600_000.0,
24 => 3937.0 / 6_336_000_000.0,
_ => 1.0,
}
}
fn run_pdfimport(s: &mut Session, p: &Value) -> Result<Value> {
let (at, scale) = placement("pdfimport", p)?;
let (bytes, name) = source_file("pdfimport", p, "import.pdf")?;
if !is_pdf(&bytes) {
return Err(bad("pdfimport", format!("{} is not a PDF file", source_name(&name))));
}
import_pdf(s, "pdfimport", p, &bytes, &name, at, scale)
}
fn import_pdf(s: &mut Session, cmd: &str, p: &Value, bytes: &[u8], name: &str, at: Vec2, scale: f64) -> Result<Value> {
let read = PDF_IMPORT.get().ok_or_else(|| bad(cmd, "PDF import is not available in this build"))?;
let unit = 25.4 / 72.0 * units_per_mm(s.doc()?);
let mut options = serde_json::Map::new();
options.insert("unit".into(), json!(unit));
for key in ["page", "password", "text", "fills", "lineweights"] {
if let Some(value) = p.get(key) {
options.insert(key.into(), value.clone());
}
}
let (source, pages) = read(bytes, &Value::Object(options)).map_err(|e| bad(cmd, e))?;
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
if source.model.is_empty() {
let detail = source.read_notes.join("; ");
let message = if detail.is_empty() {
"the selected PDF page has no editable vector content; scanned drawings need manual tracing".to_string()
} else {
format!("the selected PDF page has no editable vector content; scanned drawings need manual tracing. {detail}")
};
return Err(bad(cmd, message));
}
let warnings = source.read_notes.clone();
let mut result = import_drawing(s, &source, at, scale, &source_name(name))?;
if let Some(object) = result.as_object_mut() {
object.insert("pages".into(), json!(pages));
object.insert("page".into(), json!(page));
object.insert("warnings".into(), json!(warnings));
let imported = object.get("imported").and_then(Value::as_u64).unwrap_or(0);
let mut message = format!("{imported} objects imported from page {page} of {pages} of {}", source_name(name));
if !source.read_notes.is_empty() {
message.push_str(". Some PDF content was omitted or approximated. See the command history for details.");
for note in &source.read_notes {
s.echo(note.clone());
}
}
object.insert("message".into(), json!(message));
}
Ok(result)
let file = std::path::Path::new(&name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
import_drawing(s, &src, at, scale, &file)
}
/// Copy `src`'s model space into the current space (scaled about the origin, then moved to
@@ -727,40 +592,6 @@ mod tests {
s
}
fn scanned_pdf(_: &[u8], _: &Value) -> std::result::Result<(Drawing, usize), String> {
let mut drawing = Drawing::new_metric();
drawing.read_notes.push("PDF: 1 raster image was not imported".into());
Ok((drawing, 1))
}
#[test]
fn scanned_pdf_does_not_open_or_import_as_an_empty_drawing() {
set_pdf_import(scanned_pdf);
let data = base64_encode(b"%PDF-1.7 synthetic scan");
let mut s = Session::new();
let before = s.doc().unwrap().model.len();
let open = s.execute("open", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
assert!(open.contains("no editable vector content") && open.contains("raster image"), "{open}");
let import = s.execute("pdfimport", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
assert!(import.contains("manual tracing") && import.contains("raster image"), "{import}");
assert_eq!(s.doc().unwrap().model.len(), before, "no empty drawing was opened or imported");
}
#[test]
fn survey_units_convert_like_their_international_counterparts() {
let per_mm = |insunits: i64| {
let mut d = Drawing::new_metric();
d.header.set_i64("INSUNITS", insunits);
units_per_mm(&d)
};
// Survey feet, inches, yards and miles beside feet, inches, yards and miles.
for (survey, international) in [(21, 2), (22, 1), (23, 10), (24, 3)] {
let ratio = per_mm(survey) / per_mm(international);
// The survey unit is two parts per million longer.
assert!(ratio < 1.0 && ratio > 1.0 - 1e-5, "INSUNITS {survey}: {ratio}");
}
}
fn temp(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("cadcraft-exchange-{}-{name}", std::process::id()))
}
+20 -135
View File
@@ -16,7 +16,7 @@ use super::{CommandSpec, EngineError, Interactive, always, bad, bool_or, find_co
use crate::{Accept, Input, Prompt, Result, Session, Step};
/// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT.
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases, user_alias_command};
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases};
pub(crate) use pgp::{greek_alias, specs as alias_specs, user_alias};
pub use template::{qnew_template, set_qnew_template};
@@ -49,47 +49,6 @@ pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
/// [`IoHooks::write`] and [`IoHooks::plot`] that also return what an image (PNG, SVG, PDF) draws
/// short of the drawing because of a render limit, one note each, such as dashed lines drawn
/// continuous past the dash limit (installed by the app with the image writers, a lower layer;
/// see `cadcraft_io::write_framed_noted` and `cadcraft_io::plotter::plot_noted`). EXPORT, QSAVE
/// and SAVEAS to an image, `document.bytes` and PLOT (so PUBLISH and PDFBOOK, sheet by sheet)
/// report them; without the hooks they write through [`IoHooks`] with no such notes. The app
/// installs the same writers as its [`IoHooks`].
pub struct NotedIo {
pub write: fn(&Drawing, &str) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
pub plot: fn(&Drawing, &cadcraft_doc::Space, &Value) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
}
static NOTED_IO: OnceLock<NotedIo> = OnceLock::new();
pub fn set_noted_io(h: NotedIo) {
let _ = NOTED_IO.set(h);
}
/// `d` written as `name` with the image's notes ([`NotedIo::write`]), or through `hooks.write`
/// with none when the app installed no [`NotedIo`].
pub(crate) fn write_noted(hooks: &IoHooks, d: &Drawing, name: &str) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.write)(d, name),
None => (hooks.write)(d, name).map(|bytes| (bytes, Vec::new())),
}
}
/// `d` plotted with the plot's notes ([`NotedIo::plot`]), or through `hook` with none when the
/// app installed no [`NotedIo`].
pub(crate) fn plot_noted(
hook: PlotHook,
d: &Drawing,
space: &cadcraft_doc::Space,
opts: &Value,
) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.plot)(d, space, opts),
None => hook(d, space, opts).map(|bytes| (bytes, Vec::new())),
}
}
/// An entity as DXF groups and back, for AutoLISP's `entget`, `entmake` and `entmod`
/// (installed by the app with the DXF reader and writer, a lower layer).
pub struct EntityCodec {
@@ -145,46 +104,6 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash
/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see
/// `cadcraft_io::dwg_notes`).
pub type DwgNotes = fn(&Drawing) -> Vec<String>;
static DWG_NOTES: OnceLock<DwgNotes> = OnceLock::new();
pub fn set_dwg_notes(f: DwgNotes) {
let _ = DWG_NOTES.set(f);
}
/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook.
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
DWG_NOTES.get().map(|f| f(d)).unwrap_or_default()
}
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
report_notes(s, r, notes);
}
/// Say each of `notes` on the command line and add them to the result's `warnings`.
pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
for note in &notes {
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
match o.get_mut("warnings").and_then(Value::as_array_mut) {
Some(list) => list.extend(notes.into_iter().map(Value::String)),
None => {
o.insert("warnings".into(), json!(notes));
}
}
}
}
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
@@ -289,10 +208,9 @@ fn is_dxf(path: &str) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// The drawing written to `path` with `opts`: an image, or a drawing file with no option set,
/// through [`IoHooks::write`] (with an image's notes, [`write_noted`]); a drawing file at a
/// chosen version or as binary DXF through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec<u8>, Vec<String>)> {
/// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set,
/// else through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<u8>> {
let hooks = io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?;
if opts.binary && !is_dxf(path) {
return Err(bad(cmd, "binary applies to DXF files only"));
@@ -301,12 +219,11 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec
let d: &cadcraft_doc::Drawing = if is_drawing_file(path) { s.state()?.drawing() } else { s.doc()? };
let copy = (opts.portable_fonts && is_drawing_file(path)).then(|| Drawing { portable_fonts: true, ..d.clone() });
let d = copy.as_ref().unwrap_or(d);
// An image has no version: `write_as` would write the same bytes without the notes.
let r = if !is_drawing_file(path) || (opts.version.is_none() && !opts.binary) {
write_noted(hooks, d, path)
let r = if opts.version.is_none() && !opts.binary {
(hooks.write)(d, path)
} else {
let w = write_as().ok_or_else(|| bad(cmd, "saving at a chosen version or as binary DXF is not available in this build"))?;
w(d, path, opts).map(|bytes| (bytes, Vec::new()))
w(d, path, opts)
};
r.map_err(|e| bad(cmd, e))
}
@@ -338,7 +255,7 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}")
.noundo(),
CommandSpec::new("script", "Run Script...", run_script)
.menu(&["Tools", "Run Script..."])
@@ -465,16 +382,11 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow.
fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile> {
let drawing = match super::exchange::open_pdf(bytes) {
Some(result) => result.map_err(|e| bad("open", e))?,
None => {
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
(hooks.read)(bytes, name).map_err(|e| bad("open", e))?
}
};
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?;
// A file that isn't a drawing (an imported SVG) gives the drawing no file name: QSAVE then
// asks where to save instead of exporting over the original.
let path = path.filter(|p| is_drawing_file(p) && !bytes.starts_with(b"%PDF-"));
let path = path.filter(|p| is_drawing_file(p));
// The SHX fonts its text styles name are looked for beside the drawing too.
if let Some(dir) = path.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
// A bare file name is in the current folder.
@@ -582,19 +494,18 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again.
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usize> {
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let bytes = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -606,7 +517,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usi
st.saved = st.drawing().clone();
}
}
Ok((n, notes))
Ok(n)
}
/// Put saved bytes where the user gets them: natively the file at `path`; on the web, which has
@@ -896,18 +807,15 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
let n = save_to(s, &path)?;
Ok(saved(&path, n))
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let n = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year());
r["binary"] = json!(opts.binary);
@@ -956,13 +864,10 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let opts = save_options("document.bytes", p)?;
let version = opts.version.unwrap_or_else(|| drawing_version(s, &format!("drawing.{fmt}")));
let lost = not_saved_as(s.doc()?, version);
let (bytes, notes) = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
report_notes(s, &mut r, notes);
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if is_dxf_file(format!("drawing.{fmt}")) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1095,9 +1000,7 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
let Ok(d) = s.doc() else { return };
let version = own_version(d, path);
let lost = lost_writing(d, path, version);
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
report_lost(s, r, path, version, &lost);
report_dwg_notes(s, r, notes);
}
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
@@ -1204,8 +1107,6 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
report_new_folder(s, &mut r, folder);
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1273,22 +1174,6 @@ mod tests {
use crate::Session;
use crate::temp_dir::TempDir;
/// Notes join the warnings a result already has instead of replacing them, and are said on
/// the command line.
#[test]
fn notes_are_added_to_the_warnings_a_result_has() {
let mut s = Session::new();
let mut r = json!({ "warnings": ["kept"] });
super::report_notes(&mut s, &mut r, vec!["added".into()]);
assert_eq!(r["warnings"], json!(["kept", "added"]));
let mut r = json!({});
super::report_notes(&mut s, &mut r, Vec::new());
assert!(r.get("warnings").is_none());
super::report_notes(&mut s, &mut r, vec!["first".into()]);
assert_eq!(r["warnings"], json!(["first"]));
assert!(s.log.ends_with(&["added".to_string(), "first".to_string()]), "{:?}", s.log);
}
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
#[cfg(unix)]
+8 -2
View File
@@ -455,9 +455,15 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
if let Some(n) = tinted.names.get(&key) {
return Some(n.clone());
}
let st = d.dim_style(name)?.clone();
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
let base = format!("COMPARE_{}_{}", tag(color), st.name);
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
let new = tinted.next.find(
"dimension style",
&base,
d.dim_styles.len(),
|i| suffixed(&base, i),
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
);
d.dim_styles.push(DimStyle {
name: new.clone(),
dim_line_color: Color::ByBlock,
-15
View File
@@ -54,21 +54,6 @@ fn store() -> MutexGuard<'static, Aliases> {
USER.get_or_init(|| Mutex::new(Aliases::default())).lock().unwrap_or_else(PoisonError::into_inner)
}
/// The command a user alias stands for, `name` typed in any case; `None` when it is no user alias.
/// The interface resolves a lone typed alias with this before its own command routes, so a user
/// alias of HATCH opens the Hatch dialog as HATCH does.
pub fn user_alias_command(name: &str) -> Option<String> {
// Keys are stored with their ASCII letters in lower case. Past ASCII, the key and the name
// are compared in lower case, so `ΚΡ` finds `κρ` and `éx` finds a key stored as `Éx`.
let name = name.trim();
if let Some(command) = user_alias(&name.to_ascii_lowercase()) {
return Some(command);
}
let lower = name.to_lowercase();
let aliases = store();
aliases.map.iter().find(|(key, _)| key.to_lowercase() == lower).map(|(_, command)| command.clone())
}
/// The command a user alias stands for (`name` in lower case).
pub(crate) fn user_alias(name: &str) -> Option<String> {
store().map.get(name).cloned()
-29
View File
@@ -71,35 +71,6 @@ fn next_unnamed(d: &Drawing) -> String {
(1..=d.groups.len() + 1).map(|n| format!("*A{n}")).find(|n| !used.contains(n)).unwrap_or_else(|| format!("*A{}", d.groups.len() + 1))
}
/// When entities are copied, replicate any whole groups whose members were all copied.
pub(crate) fn replicate_groups_from(d: &mut Drawing, src_groups: &[Group], copies: &[(Handle, Handle)]) {
if copies.is_empty() || src_groups.is_empty() {
return;
}
let map: std::collections::HashMap<Handle, Handle> = copies.iter().copied().collect();
let mut new_groups = Vec::new();
for g in src_groups {
let active_members: Vec<Handle> = g.members.iter().copied().filter(|h| d.entity(*h).is_some()).collect();
if !active_members.is_empty() && active_members.iter().all(|h| map.contains_key(h)) {
let new_members: Vec<Handle> = active_members.iter().filter_map(|h| map.get(h).copied()).collect();
new_groups.push((g.description.clone(), g.selectable, new_members));
}
}
for (desc, selectable, members) in new_groups {
if d.groups.len() >= MAX_GROUPS {
break;
}
let name = next_unnamed(d);
d.groups.push(Group { name, description: desc, selectable, members });
}
}
/// When entities in the drawing `d` are copied, replicate any whole groups among them.
pub(crate) fn replicate_groups_for_copies(d: &mut Drawing, copies: &[(Handle, Handle)]) {
let groups = d.groups.clone();
replicate_groups_from(d, &groups, copies);
}
/// `hs` without repeats and without handles of objects that don't exist.
fn existing(d: &Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
+13 -41
View File
@@ -17,7 +17,6 @@ use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_p
use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step};
mod arcs;
mod assoc;
pub(crate) use assoc::detach;
mod edit;
@@ -55,15 +54,13 @@ pub(super) fn outline_tol(ext: Bounds2) -> f64 {
}
/// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each
/// with the handle of the object it came from and its exact piece ([`arcs::pieces_of`]), and
/// the flattening tolerance.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>, Vec<Option<arcs::Piece>>, f64) {
/// with the handle of the object it came from.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>) {
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) };
let ext = d.extents(space);
let tol = outline_tol(ext);
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new(), Vec::new(), tol) };
let mut out = Vec::new();
let mut owners = Vec::new();
let mut pieces = Vec::new();
for e in store.iter() {
if !d.is_visible(e) || matches!(e.kind, EntityKind::Hatch(_) | EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) {
continue;
@@ -76,10 +73,9 @@ fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>
}
let polys = object_polys(d, e, tol, ext);
owners.extend(std::iter::repeat_n(e.handle, polys.len()));
pieces.extend(arcs::pieces_of(e, polys.len()));
out.extend(polys);
}
(out, owners, pieces, tol)
(out, owners)
}
/// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous
@@ -197,7 +193,7 @@ impl OriginMode {
}
/// The origin for loops: `current` when the mode keeps it.
pub(crate) fn origin(self, loops: &[HatchLoop], current: Vec2) -> Vec2 {
let b = loops_bounds(loops);
let b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
if b.is_empty() {
return current;
}
@@ -212,25 +208,6 @@ impl OriginMode {
}
}
/// The extents of hatch loops with their arcs: a bulged edge reaches past its vertices (a circle
/// kept as two half-circle vertices spans its whole height).
fn loops_bounds(loops: &[HatchLoop]) -> Bounds2 {
let mut b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
for l in loops {
let vs = &l.vertices;
for (i, v) in vs.iter().enumerate() {
let Some(next) = vs.get((i + 1) % vs.len()) else { continue };
if let Some((arc, _)) = cadcraft_geom::bulge_to_arc(v.p, next.p, v.bulge) {
let ab = arc.bounds();
if ab.min.is_finite() && ab.max.is_finite() {
b = b.union(&ab);
}
}
}
}
b
}
/// Island detection style by name (HPISLANDDETECTION 0 normal, 1 outer, 2 ignore).
pub(crate) fn island_style(t: &str) -> Option<u8> {
match t.trim().to_ascii_lowercase().as_str() {
@@ -247,17 +224,15 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let space = s.space();
let ext = d.extents(&space);
let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9);
let (polys, owners, pieces, ftol) = outlines(d, &space, None);
let (polys, owners) = outlines(d, &space, None);
// A line that ends on a flattened curve (an ellipse) can stop short of its chords.
let polys = cadcraft_geom::region::snap_ends(&polys, ftol, tol);
let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(ext), tol);
let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d))
.ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?;
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
// The traced outline is flattened: circular runs become arcs again (#1167).
let mut loops =
vec![HatchLoop { vertices: arcs::with_arcs(&outer, &found.outer_edges, &pieces, ftol), outer: true, boundary_flags: None, sources }];
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -286,7 +261,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop {
vertices: arcs::with_arcs(&island.outline, &island.edges, &pieces, ftol),
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
outer: false,
boundary_flags: None,
sources,
@@ -299,9 +274,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<HatchLoop>> {
let d = s.doc()?;
let mut loops = Vec::new();
let mut seen = std::collections::HashSet::new();
// An object selected twice is one boundary.
for h in hs.iter().filter(|h| seen.insert(**h)) {
for h in hs {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
}
@@ -456,18 +429,17 @@ fn same_loop(a: &HatchLoop, b: &HatchLoop) -> bool {
})
}
/// Deduplicate boundary loops that describe the same boundary in the same role. A loop that is
/// one pick's outer loop and another's island (a pick inside a circle and one around it) stays
/// twice: merged, the island would be gone and the even-odd fill would leave the circle empty.
/// Deduplicate boundary loops that describe the same boundary.
fn dedup_loops(loops: &mut Vec<HatchLoop>) {
let mut unique: Vec<HatchLoop> = Vec::with_capacity(loops.len());
for l in loops.drain(..) {
if let Some(existing) = unique.iter_mut().find(|u| u.outer == l.outer && same_loop(u, &l)) {
if let Some(existing) = unique.iter_mut().find(|u| same_loop(u, &l)) {
for s in l.sources {
if !existing.sources.contains(&s) {
existing.sources.push(s);
}
}
existing.outer = existing.outer || l.outer;
} else {
unique.push(l);
}
-147
View File
@@ -1,147 +0,0 @@
//! Exact arcs in traced hatch boundaries (#1167).
//!
//! The boundary search works on flattened curves, so a loop traced around an internal point
//! comes out as chords: a hatch in a circle had 158 straight edges and the wrong area. Each
//! traced edge knows the input polyline it lies on, and each input polyline is one piece of one
//! object (a line, a circle, an arc or one segment of a polyline), so nothing is guessed from
//! nearby geometry: a run of edges on the same circular piece becomes one bulged vertex again,
//! and the corners move onto the exact curves (where a line or another circle crosses).
use cadcraft_doc::{Entity, EntityKind, Prim};
use cadcraft_geom::{Circle, Line, PolyVertex, Segment, Vec2, arc_to_bulge, circle_circle, line_circle, shoelace};
/// The exact curve behind one input polyline.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Piece {
Line(Line),
Circle(Circle),
}
/// The exact piece behind each of `e`'s `n` outline polylines (one per primitive, in order, as
/// `select::hit_polylines` makes them), or `None` for each when `e` isn't made of lines and
/// circular arcs or the count doesn't match.
pub(crate) fn pieces_of(e: &Entity, n: usize) -> Vec<Option<Piece>> {
if !matches!(e.kind, EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::LwPolyline(_)) {
return vec![None; n];
}
let prims = e.kind.prims();
if prims.len() != n {
return vec![None; n];
}
prims
.iter()
.map(|p| match p {
Prim::Seg(Segment::Line(l)) => Some(Piece::Line(*l)),
Prim::Seg(Segment::Arc { arc, .. }) => Some(Piece::Circle(Circle::new(arc.center, arc.radius))),
Prim::Circle(c) => Some(Piece::Circle(*c)),
_ => None,
})
.collect()
}
fn same_circle(a: &Circle, b: &Circle) -> bool {
a.center == b.center && a.radius == b.radius
}
/// The loop `pts` (edge `i` from `pts[i]` to the next vertex, closed) with its circular runs
/// as bulged vertices. `edges` names each edge's input polyline, `pieces` each polyline's exact
/// curve; `tol` is the flattening tolerance the polylines were made with. Anything that doesn't
/// check out stays as traced.
pub(crate) fn with_arcs(pts: &[Vec2], edges: &[Option<usize>], pieces: &[Option<Piece>], tol: f64) -> Vec<PolyVertex> {
let n = pts.len();
let plain = || pts.iter().map(|p| PolyVertex::new(*p)).collect::<Vec<_>>();
if n < 3 || edges.len() != n || !(tol.is_finite() && tol > 0.0) || pts.iter().any(|p| !p.is_finite()) {
return plain();
}
let at = |i: usize| pts.get(i % n).copied().unwrap_or_default();
let piece = |i: usize| edges.get(i % n).copied().flatten().and_then(|k| pieces.get(k).copied().flatten());
// A chord of a curve flattened to `tol` stays within `tol` of it; corners split where two
// chords cross may be a little further.
let slack = tol * 4.0;
let near_circle = |c: &Circle, q: Vec2| (c.center.dist(q) - c.radius).abs() <= slack;
// The circle each edge lies on: its piece is a circle and both ends and the middle are on
// it (the middle, so a long chord across the circle doesn't pass for an arc).
let circ: Vec<Option<(usize, Circle)>> = (0..n)
.map(|i| {
let k = edges.get(i).copied().flatten()?;
let Some(Piece::Circle(c)) = piece(i) else { return None };
let (a, b) = (at(i), at(i + 1));
(c.radius.is_finite() && c.radius > slack && near_circle(&c, a) && near_circle(&c, b) && near_circle(&c, a.mid(b))).then_some((k, c))
})
.collect();
let key = |i: usize| circ.get(i % n).copied().flatten().map(|(k, _)| k);
if circ.iter().all(Option::is_none) {
return plain();
}
let ccw = shoelace(pts) > 0.0;
// One whole circle: two half circles, as a hatch made by selecting the circle has.
if let Some(Some((k0, c))) = circ.first().copied()
&& (0..n).all(|i| key(i) == Some(k0))
{
let b = if ccw { 1.0 } else { -1.0 };
return vec![PolyVertex::with_bulge(c.center - Vec2::X * c.radius, b), PolyVertex::with_bulge(c.center + Vec2::X * c.radius, b)];
}
let line_of = |i: usize| match piece(i) {
Some(Piece::Line(l)) if l.a != l.b && [at(i), at(i + 1)].iter().all(|q| ((*q - l.a).cross(l.b - l.a) / l.a.dist(l.b)).abs() <= slack) => {
Some(l)
}
_ => None,
};
let onto = |c: &Circle, q: Vec2| {
let d = q - c.center;
if d.len() > 0.0 { c.center + d.normalized() * c.radius } else { q }
};
// Vertex `i` (between edges `i - 1` and `i`) on the exact curves: where the two pieces
// cross, nearest the traced corner, or else moved onto the circle it is on.
let corner = |i: usize| -> Vec2 {
let p = at(i);
let (prev, next) = (circ.get((i + n - 1) % n).copied().flatten(), circ.get(i % n).copied().flatten());
let crossings: Vec<Vec2> = match (prev, next) {
(Some((_, a)), Some((_, b))) if same_circle(&a, &b) => return onto(&a, p),
(Some((_, a)), Some((_, b))) => circle_circle(&a, &b),
(Some((_, c)), None) => line_of(i).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, Some((_, c))) => line_of(i + n - 1).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, None) => return p,
};
// Where two curves cross at a shallow angle, a corner off them by the flattening
// tolerance can be off along them by up to about √(2·r·tolerance): the crossing nearest
// the traced corner is taken within that reach, when no other crossing is as near.
let r = prev.or(next).map_or(0.0, |(_, c)| c.radius);
let reach = slack * 2.0 + (2.0 * r * slack).sqrt();
let mut xs: Vec<(f64, Vec2)> = crossings.into_iter().filter(|x| x.is_finite()).map(|x| (x.dist(p), x)).collect();
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
match (xs.first(), xs.get(1)) {
(Some(&(d, x)), second) if d <= reach && second.is_none_or(|&(d2, _)| d2 > 2.0 * d + slack) => x,
_ => prev.or(next).map_or(p, |(_, c)| onto(&c, p)),
}
};
// Start where a run begins, so no run wraps past the end.
let Some(s) = (0..n).find(|&i| key(i) != key(i + n - 1)) else { return plain() };
let mut out = Vec::with_capacity(n);
let mut i = 0;
while i < n {
let e = (s + i) % n;
let p = corner(e);
let Some((k, c)) = circ.get(e).copied().flatten() else {
out.push(PolyVertex::new(p));
i += 1;
continue;
};
// The angle the run turns through about the centre, edge by edge.
let mut sweep = 0.0;
let mut a = p;
let mut j = i;
while j < n && key(s + j) == Some(k) {
let last = j + 1 >= n || key(s + j + 1) != Some(k);
let b = if last { corner(s + j + 1) } else { at(s + j + 1) };
let (u, v) = (a - c.center, b - c.center);
sweep += u.cross(v).atan2(u.dot(v));
a = b;
j += 1;
}
let bulge = arc_to_bulge(sweep);
out.push(PolyVertex::with_bulge(p, if bulge.is_finite() { bulge } else { 0.0 }));
i = j;
}
if out.len() < 2 { plain() } else { out }
}
+5 -12
View File
@@ -87,14 +87,8 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
return Refill::Open;
}
let tol = super::outline_tol(nb);
let mut polys: Vec<Vec<Vec2>> = Vec::new();
let mut pieces = Vec::new();
for e in live.iter().filter_map(|h| after.entity(*h)) {
let ps = object_polys(after, e, tol, nb);
pieces.extend(super::arcs::pieces_of(e, ps.len()));
polys.extend(ps);
}
let snap = ((nb.width() + nb.height()) * 1e-9).max(1e-9);
let polys: Vec<Vec<Vec2>> = live.iter().filter_map(|h| after.entity(*h)).flat_map(|e| object_polys(after, e, tol, nb)).collect();
let polys = region::snap_ends(&polys, tol, snap);
let gap = gap_tolerance(after);
let found = if l.outer {
@@ -103,14 +97,13 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
let ob = if ob.is_empty() { nb } else { ob };
let old = outline_of(&l.vertices, (ob.width() + ob.height()).max(1e-9) / 20000.0);
region::interior_point(&old)
.and_then(|q| region::enclosing_loop_edges_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline_edges(&polys, snap, gap))
.and_then(|q| region::enclosing_loop_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline(&polys, snap, gap))
} else {
region::outline_edges(&polys, snap, gap)
region::outline(&polys, snap, gap)
};
match found {
// Traced again from flattened curves: circular runs become arcs again (#1167).
Some((pts, edges)) => Refill::Loop(super::arcs::with_arcs(&pts, &edges, &pieces, tol)),
Some(pts) => Refill::Loop(pts.into_iter().map(PolyVertex::new).collect()),
None => Refill::Open,
}
}
+2 -16
View File
@@ -8,7 +8,7 @@ use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json};
use super::assoc::{detach, same_shape};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles, same_loop};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{bad, bool_or, point_param, points_param, size_param, str_param, targets};
use crate::{Accept, Input, Interactive, Picker, Prompt, Result, Session, Step};
@@ -420,21 +420,7 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<(
return Ok(());
}
h.loops = h.loops.drain(..).enumerate().filter_map(|(i, l)| (!removed.contains(&i)).then_some(l)).collect();
// A boundary the hatch already has is not added again (whatever role it has here): a second
// copy would cancel it under the odd-parity fill. Its objects join the loop there, so picking
// it links an unlinked loop to them.
for a in added {
match h.loops.iter_mut().find(|l| same_loop(l, a)) {
Some(l) => {
for s in &a.sources {
if !l.sources.contains(s) {
l.sources.push(*s);
}
}
}
None => h.loops.push(a.clone()),
}
}
h.loops.extend_from_slice(added);
dedup_loops(&mut h.loops);
if h.loops.is_empty() {
return Err(bad("hatchedit", "a hatch needs at least one boundary loop"));
+14 -33
View File
@@ -68,48 +68,29 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then
/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the
/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or
/// chamfer too large for the shorter side leaves the corners square, each as two coincident
/// vertices, as AutoCAD stores them.
/// chamfer that doesn't fit leaves the corners square.
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)];
let Some((d_in, d_out)) = rect_corner_cuts(fillet, chamfer) else { return corners.into_iter().map(PolyVertex::new).collect() };
let fits = rect_corners_fit(b - a, fillet, chamfer);
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
let bulge = if fillet > 0.0 { sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2) } else { 0.0 };
let short = (b.x - a.x).abs().min((b.y - a.y).abs());
let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 {
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
(fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 {
(chamfer.0, chamfer.1, 0.0)
} else {
return corners.into_iter().map(PolyVertex::new).collect();
};
let mut out = Vec::with_capacity(8);
for (i, cur) in corners.iter().enumerate() {
let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue };
if fits {
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
} else {
out.extend([PolyVertex::new(*cur), PolyVertex::new(*cur)]);
}
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
}
out
}
/// How far a rectangle's fillet or chamfer cuts into the edges into and out of each corner, if
/// one is set: the fillet radius on both, or the two chamfer distances. A fillet wins over a
/// chamfer.
fn rect_corner_cuts(fillet: f64, chamfer: (f64, f64)) -> Option<(f64, f64)> {
if fillet > 0.0 {
Some((fillet, fillet))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
Some(chamfer)
} else {
None
}
}
/// Whether a fillet or chamfer fits a rectangle of `size` (signed sides): its two cuts together
/// no longer than the shorter side. True when neither is set.
pub fn rect_corners_fit(size: Vec2, fillet: f64, chamfer: (f64, f64)) -> bool {
rect_corner_cuts(fillet, chamfer).is_none_or(|(d_in, d_out)| d_in + d_out <= size.x.abs().min(size.y.abs()) + 1e-12)
}
// ---------- the user's support files ----------
/// Largest support file (linetype, hatch pattern or alias file) read.
+11 -143
View File
@@ -4,15 +4,15 @@
//! the drawing as a crossed-out frame.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use cadcraft_doc::{Drawing, EntityKind, Image, Raster};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use super::file::base64_decode;
use super::{CommandSpec, bad, point_value, str_param};
use super::{CommandSpec, bad, f64_or, point_param, str_param};
use crate::{Result, Session};
/// Most image files loaded per drawing.
@@ -27,9 +27,6 @@ const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
const MAX_LOADED_BYTES: u64 = 2 << 30;
/// Most bytes one decoded image takes: the image reader decodes at most 128 million pixels, four
/// bytes each (`cadcraft_io::raster::MAX_IMAGE_PIXELS`).
const MAX_DECODED_BYTES: u64 = 512_000_000;
/// Most image files decoded at the same time when a drawing opens.
const MAX_LOADERS: usize = 4;
/// Longest image path taken from a caller.
@@ -186,11 +183,13 @@ fn over_limit(path: &str) -> String {
/// what opening a drawing with large images waits for). The results are in the order of `paths`.
fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<Raster, String>> {
// Decoded bytes so far, shared by the loaders: past the limit no further file is started.
let budget = Budget::default();
let decoded_bytes = AtomicU64::new(0);
let load = |path: &str| -> std::result::Result<Raster, String> {
let mut decoding = budget.start().ok_or_else(|| format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20))?;
if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES {
return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20));
}
let r = read_file(path, host).and_then(|bytes| decode(&bytes))?;
decoding.bytes = bytes_of(&r);
decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed);
Ok(r)
};
let mut results: Vec<Option<std::result::Result<Raster, String>>> = paths.iter().map(|_| None).collect();
@@ -225,83 +224,6 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<R
results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect()
}
/// The decoded bytes the loaders of one drawing share.
#[derive(Default)]
struct Budget {
spent: Mutex<Spent>,
/// Signaled when a file finishes decoding.
finished: Condvar,
}
/// Decoded bytes so far, and how many files are being decoded.
#[derive(Default)]
struct Spent {
decoded: u64,
decoding: u64,
}
/// Whether a loader may start decoding a file.
#[derive(Debug, PartialEq)]
enum Admit {
Start,
/// Not until another file finishes.
Wait,
/// The images decoded so far are past the limit.
Full,
}
impl Spent {
/// A file starts while the images decoded so far, and the largest image each file being
/// decoded can become, fit under `limit`. A file always starts when no other one is being
/// decoded, so that the images run past `limit` by one image at most.
fn admit(&mut self, limit: u64, largest: u64) -> Admit {
if self.decoded > limit {
return Admit::Full;
}
let reserved = self.decoding.saturating_add(1).saturating_mul(largest);
if self.decoding > 0 && self.decoded.saturating_add(reserved) > limit {
return Admit::Wait;
}
self.decoding = self.decoding.saturating_add(1);
Admit::Start
}
/// A file finished decoding into `bytes` (0 when it failed).
fn finish(&mut self, bytes: u64) {
self.decoding = self.decoding.saturating_sub(1);
self.decoded = self.decoded.saturating_add(bytes);
}
}
impl Budget {
/// Wait until a file may start decoding; `None` once the images decoded so far are past the
/// limit.
fn start(&self) -> Option<Decoding<'_>> {
let mut spent = self.spent.lock().unwrap_or_else(PoisonError::into_inner);
loop {
match spent.admit(MAX_LOADED_BYTES, MAX_DECODED_BYTES) {
Admit::Start => return Some(Decoding { budget: self, bytes: 0 }),
Admit::Full => return None,
Admit::Wait => spent = self.finished.wait(spent).unwrap_or_else(PoisonError::into_inner),
}
}
}
}
/// A file being decoded. Dropping it counts `bytes` as decoded and lets a waiting loader check
/// again, also when the decoding failed.
struct Decoding<'a> {
budget: &'a Budget,
bytes: u64,
}
impl Drop for Decoding<'_> {
fn drop(&mut self) {
self.budget.spent.lock().unwrap_or_else(PoisonError::into_inner).finish(self.bytes);
self.budget.finished.notify_all();
}
}
/// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large
/// image needs several hundred megabytes while it is decoded) and no more than there are files.
fn loader_count(files: usize) -> usize {
@@ -346,9 +268,6 @@ pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(ID, "`path` is too long"));
}
let place = placement(p)?;
if p.get("name").is_some_and(|n| !(n.is_null() || n.is_string())) {
return Err(bad(ID, "`name` must be text"));
}
let raster = pixels(s, p, &path)?;
let (w, h) = (f64::from(raster.width()), f64::from(raster.height()));
// One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`).
@@ -386,32 +305,18 @@ struct Placement {
/// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1).
fn placement(p: &Value) -> Result<Placement> {
let at = match p.get("at") {
None | Some(Value::Null) => Vec2::ZERO,
Some(v) => point_value(v).ok_or_else(|| bad(ID, "`at` must be a point"))?,
};
let at = point_param(p, "at").unwrap_or(Vec2::ZERO);
if !(at.x.is_finite() && at.y.is_finite()) {
return Err(bad(ID, "`at` must be a point"));
}
// `scale` is checked even when `width` takes precedence over it.
let scale = number(p, "scale")?;
let width = match p.get("width") {
Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?,
None => scale.unwrap_or(1.0),
None => f64_or(p, "scale", 1.0),
};
if !(width.is_finite() && width > 0.0) {
return Err(bad(ID, "`scale` and `width` must be greater than zero"));
}
let rotation = number(p, "rotation")?.unwrap_or(0.0);
Ok(Placement { at, rotation: rotation.to_radians(), width })
}
/// The number `key` of `p`: `None` when it is omitted or null, an error when it is not a number.
fn number(p: &Value, key: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| bad(ID, format!("`{key}` must be a number"))),
}
Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width })
}
/// The pixels of the image at `path`: decoded from `data` when the caller hands the file over,
@@ -479,40 +384,3 @@ fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value {
};
json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) })
}
#[cfg(test)]
mod tests {
use super::*;
/// A file starts only while the largest image each file being decoded can become still fits,
/// one file always starts when none is being decoded, and none starts past the limit.
#[test]
fn loaders_start_files_within_the_limit() {
let mut s = Spent::default();
// Room for two of the largest images.
assert_eq!(s.admit(10, 4), Admit::Start);
assert_eq!(s.admit(10, 4), Admit::Start);
assert_eq!(s.admit(10, 4), Admit::Wait);
s.finish(3);
assert_eq!(s.admit(10, 4), Admit::Wait, "3 decoded and two files that can become 4 each are past 10");
s.finish(5);
// Over the limit only by the one file being decoded.
assert_eq!(s.admit(10, 4), Admit::Start);
s.finish(4);
assert_eq!(s.admit(10, 4), Admit::Full);
// A failed file counts nothing.
let mut s = Spent::default();
assert_eq!(s.admit(10, 4), Admit::Start);
s.finish(0);
assert_eq!((s.decoded, s.decoding), (0, 0));
}
/// Files that fail still let the other loaders go on: every file gets a result.
#[test]
fn decode_files_finishes_when_every_file_fails() {
let paths = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"];
let results = decode_files(&paths, None);
assert_eq!(results.len(), paths.len());
assert!(results.iter().all(std::result::Result::is_err), "none of these files exists");
}
}
+4 -9
View File
@@ -532,17 +532,12 @@ pub(super) fn object_area(s: &Session, h: Handle) -> Result<(f64, f64)> {
(cadcraft_geom::PI * a * b, arc.arc_length_from(0.0, cadcraft_geom::TAU))
}
EntityKind::Hatch(hh) => {
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled
// island. The loops the fill keeps (a repeated loop once; an outer loop and an island
// that are the same boundary cancel), each measured exactly with its arcs.
let kept = cadcraft_render::hatch_fill_loop_indices(hh, 1e-3);
let geoms: Vec<Polyline> =
kept.iter().filter_map(|(i, _)| hh.loops.get(*i)).map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = kept.into_iter().map(|(_, p)| p).collect();
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled island.
let geoms: Vec<Polyline> = hh.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = geoms.iter().map(|g| g.tessellate(1e-3)).collect();
let mut total = (0.0, 0.0);
for (i, g) in geoms.iter().enumerate() {
// As the fill tests nesting: an edge's middle (a vertex may touch the loop around).
let probe = polys.get(i).and_then(|p| cadcraft_render::hatch_loop_probe(p));
let probe = polys.get(i).and_then(|p| p.first().copied());
let depth = probe.map_or(0, |pt| polys.iter().enumerate().filter(|(j, q)| *j != i && cadcraft_geom::point_in_polygon(q, pt)).count());
total.0 += if depth % 2 == 0 { g.area().abs() } else { -g.area().abs() };
total.1 += g.len();
+2 -1
View File
@@ -62,7 +62,8 @@ impl Scope {
Some(_) => {
let name = given.unwrap_or_default();
let d = s.doc()?;
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
let l =
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
Ok(Scope::Space(Space::Paper(l.name.clone())))
}
}
+8 -66
View File
@@ -4,7 +4,7 @@ mod prompts;
mod state_prompts;
use cadcraft_color::Color;
use cadcraft_doc::{EntityKind, Layer, Lineweight};
use cadcraft_doc::{Layer, Lineweight};
use serde_json::{Value, json};
use super::machines::SelectRun;
@@ -101,8 +101,7 @@ fn run_list(s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({ "layers": layers, "states": d.layer_states.iter().map(|st| st.name.clone()).collect::<Vec<_>>() }))
}
/// Lower-case names of layers that have objects on them (model, layouts and block definitions),
/// or that proxy graphics draw on: AutoCAD keeps those too.
/// Lower-case names of layers that have objects on them (model, layouts and block definitions).
pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<String> {
let mut set = std::collections::HashSet::new();
let ents = d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter()));
@@ -114,9 +113,6 @@ pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<Strin
for layer in super::blocks::object_attribs(e).iter().filter_map(|a| a.props.layer.as_ref()) {
set.insert(layer.to_ascii_lowercase());
}
if let EntityKind::Unknown(u) = &e.kind {
set.extend(u.graphics.iter().map(|g| g.common.layer.to_ascii_lowercase()));
}
}
set
}
@@ -251,7 +247,6 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
*l = updated;
if let Some(nn) = new_name {
l.name = nn.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LAYER"], &old, &nn);
// Re-point entities in model space, every layout and every block definition.
repoint(&mut d.model, &old, &nn);
for layout in &mut d.layouts {
@@ -263,7 +258,6 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
merge::rename_in_viewports(d, &old, &nn);
d.rename_proxy_layer(&old, &nn);
if cur.eq_ignore_ascii_case(&old) {
d.header.set_str("CLAYER", &nn);
}
@@ -298,7 +292,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYERP", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
d.layers = layers.into();
d.layers = layers;
Ok(json!({"message": "Restored previous layer states."}))
}
@@ -308,7 +302,10 @@ fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
if name == "0" || name.eq_ignore_ascii_case("Defpoints") || d.header.str("CLAYER", "0").eq_ignore_ascii_case(&name) {
return Err(bad("layer.delete", "cannot delete layer 0, Defpoints or the current layer"));
}
if used_layers(d).contains(&name.to_ascii_lowercase()) {
let used = d.model.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name))
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)))
|| d.blocks.values().any(|b| b.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)));
if used {
return Err(bad("layer.delete", "layer has objects on it"));
}
d.layers.retain(|l| !l.name.eq_ignore_ascii_case(&name));
@@ -376,7 +373,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYISO", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
d.layers = layers.into();
d.layers = layers;
ok()
}
@@ -781,61 +778,6 @@ mod tests {
assert!(s.doc().unwrap().layer("A").is_some());
}
/// A session with layers A, B and C and a proxy on layer 0 whose graphics draw a line on B
/// (#3094).
fn proxy_on_b() -> Session {
use cadcraft_doc::{Common, Entity, EntityKind, Handle, Line, Space, Unknown};
let mut s = Session::new();
for name in ["A", "B", "C"] {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
let line = Entity {
handle: Handle(0),
common: Common { layer: "B".into(), ..Common::default() },
kind: EntityKind::Line(Line { a: cadcraft_doc::geom::Vec3::ZERO, b: cadcraft_doc::geom::Vec3::new(1.0, 0.0, 0.0) }),
};
let proxy = EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![line] });
s.doc_mut().unwrap().add(&Space::Model, Common::default(), proxy).unwrap();
s
}
fn graphics_layer(s: &Session) -> String {
s.doc()
.unwrap()
.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Unknown(u) => u.graphics.first().map(|g| g.common.layer.clone()),
_ => None,
})
.unwrap()
}
/// As in AutoCAD, PURGE and layer.delete keep a layer only proxy graphics draw on.
#[test]
fn layers_proxy_graphics_draw_on_are_in_use() {
let mut s = proxy_on_b();
assert!(s.execute("layer.delete", &json!({ "name": "B" })).is_err());
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.layer("B").is_some() && d.layer("A").is_none() && d.layer("C").is_none());
}
/// RENAME and LAYMRG take the graphics with the layer, LAYDEL drops them to layer 0.
#[test]
fn rename_merge_and_laydel_move_proxy_graphics() {
let mut s = proxy_on_b();
s.doc_mut().unwrap().proxy_layers = vec!["0".into(), "A".into(), "B".into(), "C".into()];
s.execute("layer.set", &json!({ "name": "B", "newName": "B2" })).unwrap();
assert_eq!(graphics_layer(&s), "B2");
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "B2", "C"]);
s.execute("laymrg", &json!({ "from": "B2", "to": "C" })).unwrap();
assert_eq!(graphics_layer(&s), "C");
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "C", "C"]);
s.execute("laydel", &json!({ "name": "C" })).unwrap();
assert_eq!(graphics_layer(&s), "0");
}
#[test]
fn rename_repoints_paper_space_and_block_entities() {
let mut s = Session::new();
-9
View File
@@ -175,10 +175,6 @@ pub(super) fn run_laymrg(s: &mut Session, p: &Value) -> Result<Value> {
hs.len()
});
forget_in_viewports(d, &set);
// Proxy graphics drawn on a merged layer move to the target, as its objects do.
for source in &sources {
d.rename_proxy_layer(source, &target);
}
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
let mut msg = format!("Merged {} into \"{target}\": {} moved.", quoted(&sources), plural(moved, "object"));
if set.contains(&d.header.str("CLAYER", "0").to_ascii_lowercase()) {
@@ -206,11 +202,6 @@ pub(super) fn run_laydel(s: &mut Session, p: &Value) -> Result<Value> {
hs.len()
});
forget_in_viewports(d, &set);
// A proxy isn't deleted for drawing on a deleted layer (its parts can't be); they fall back
// to layer 0, the proxy's own layer.
for source in &sources {
d.rename_proxy_layer(source, "0");
}
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
s.set_selection(Vec::new());
let msg = format!("Deleted {} and {}.", quoted(&sources), plural(erased, "object"));
+9 -175
View File
@@ -26,18 +26,14 @@ pub fn specs() -> Vec<CommandSpec> {
.interactive(|_| Ok(Box::new(prompts::LayoutM::default()))),
CommandSpec::new("layout.new", "New Layout", run_new)
.menu(&["Insert", "Layout", "New Layout"])
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name only; LAYOUT.NEWAREA also asks the area)")
.params("{name?, viewport?: bool (default true)} → {name, viewport}")
.interactive(|_| Ok(Box::new(NewLayoutM))),
CommandSpec::new("layout.newarea", "New Layout from Area...", run_new)
.menu(&["Insert", "Layout", "New Layout from Area..."])
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name, then the area)")
.interactive(|_| Ok(Box::new(NewLayoutAreaM::default()))),
CommandSpec::new("layout.delete", "Delete Layout", run_delete).params("{name}"),
CommandSpec::new("layout.rename", "Rename Layout", run_rename).params("{from?: current layout, to}"),
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(),
CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas)
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}")
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
.noundo(),
CommandSpec::new("mview", "Viewports", run_mview)
.alias(&["mv"])
@@ -229,133 +225,7 @@ impl Interactive for NewLayoutM {
}
}
/// LAYOUT.NEWAREA from the menu or command line: asks for the name (Enter takes the next free one),
/// then for the part of the model the new layout shows. The Model tab is shown for that, so it
/// can be zoomed and panned first; two corners pick the area (Enter takes the whole drawing). The
/// new layout is then shown, zoomed to that area.
#[derive(Default)]
struct NewLayoutAreaM {
/// The checked name, once it has been asked.
name: Option<String>,
/// The first corner of the model area.
first: Option<Vec2>,
/// The tab the command started in, put back when it is cancelled.
from: Option<Space>,
}
impl NewLayoutAreaM {
/// Show tab `space` (`layout.set`).
fn show(s: &mut Session, space: &Space) -> Result<()> {
let set = find_command("layout.set").ok_or_else(|| crate::EngineError::UnknownCommand("layout.set".into()))?;
(set.run)(s, &json!({ "name": space.tab_name() }))?;
Ok(())
}
}
impl Interactive for NewLayoutAreaM {
fn name(&self) -> &'static str {
"LAYOUT"
}
fn prompt(&self, s: &Session) -> Prompt {
match (&self.name, self.first) {
(None, _) => {
let next = s.doc().map(next_layout_name).unwrap_or_else(|_| "Layout1".into());
Prompt::new("Enter name of new layout", Accept::TEXT).default(next)
}
(Some(_), None) => {
Prompt::new("Specify first corner of the model area to show in the layout, or press ENTER for the whole drawing", Accept::POINT)
}
// A window's first corner: with ortho on, the opposite corner is not bent onto it.
(Some(_), Some(a)) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(name) = self.name.clone() else {
let name = match i {
Input::Text(t) if !t.trim().is_empty() => t.trim().to_string(),
Input::Text(_) | Input::Enter => next_layout_name(s.doc()?),
_ => return Ok(Step::Continue),
};
// A taken or invalid name is an error: the session reports it and asks again.
let name = check_name("layout.newarea", s.doc()?, &name, None)?;
// The area is picked in the Model tab, where the drawing can be zoomed and panned.
self.from = Some(s.layout_space());
Self::show(s, &Space::Model)?;
self.name = Some(name);
return Ok(Step::Continue);
};
// The corners are model points. If another tab was shown meanwhile (a tab click, `layout.set`),
// a point would be read in that space, so the command ends and leaves that choice alone.
if s.layout_space() != Space::Model {
self.from = None;
return Ok(Step::Cancel);
}
let window = match (i, self.first) {
(Input::Point(p), None) => {
self.first = Some(p);
return Ok(Step::Continue);
}
(Input::Point(p), Some(a)) => Some([a, p]),
(Input::Enter, None) => None,
_ => return Ok(Step::Continue),
};
let mut p = json!({ "name": name });
if let (Some([a, b]), Some(o)) = (window, p.as_object_mut()) {
o.insert("window".into(), json!([[a.x, a.y], [b.x, b.y]]));
}
// A window without width or height is an error, reported before any layout is added:
// the session asks for the first corner again.
self.first = None;
run_new(s, &p)?;
Self::show(s, &Space::Paper(name))?;
Ok(Step::Done)
}
/// Puts back the tab the command started in.
fn cancelled(&mut self, s: &mut Session) {
// Only if the Model tab is still shown: a tab the user chose since is left alone.
if let Some(from) = self.from.take()
&& s.layout_space() == Space::Model
&& let Err(e) = Self::show(s, &from)
{
s.echo(e.to_string());
}
}
/// The rectangle following the cursor while the second corner is picked.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
let Some(a) = self.first else { return Vec::new() };
let corners = [a, Vec2::new(c.x, a.y), c, Vec2::new(a.x, c.y), a];
corners
.windows(2)
.filter_map(|w| match w {
[p, q] => Some(super::helpers::line(*p, *q)),
_ => None,
})
.collect()
}
}
/// The model-space window of a `layout.new`, when it has one: `window: [[x1, y1], [x2, y2]]`.
fn window_param(p: &Value) -> Result<Option<Bounds2>> {
let Some(raw) = p.get("window").filter(|w| !w.is_null()) else { return Ok(None) };
let corners = raw.as_array();
let a = corners.and_then(|c| c.first()).and_then(point_value);
let b = corners.and_then(|c| c.get(1)).and_then(point_value);
let (Some(a), Some(b)) = (a, b) else {
return Err(bad("layout.new", "`window` needs two corners: [[x1, y1], [x2, y2]]"));
};
let w = Bounds2::new(a, b);
if w.min.is_finite() && w.max.is_finite() && w.width() > 1e-9 && w.height() > 1e-9 && w.width() < 1e12 && w.height() < 1e12 {
Ok(Some(w))
} else {
Err(bad("layout.new", "the window needs a width and a height"))
}
}
/// LAYOUT.NEW from JSON: add a layout (with a viewport unless `viewport` is false), zoomed to
/// `window` when it has one and to the model extents otherwise.
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
// Checked before anything is added, so a bad window leaves no layout behind.
let window = window_param(p)?;
let d = s.doc()?;
let name = match str_param(p, "name") {
Some(n) => check_name("layout.new", d, n, None)?,
@@ -366,30 +236,16 @@ fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut()?.layouts.push(Layout { page, ..Layout::new(&name, order) });
let mut vp = Value::Null;
if bool_or(p, "viewport", true) {
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents,
// or to the `window` when it has one.
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents.
let space = Space::Paper(name.clone());
let rect = printable(s, &name)?;
if let Some(h) = add_viewports(s, &space, rect, 1, "")?.first() {
if let Some(w) = window {
show_window(s, *h, w)?;
}
vp = json!(h.hex());
}
}
Ok(json!({ "name": name, "viewport": vp }))
}
/// Zoom viewport `h` to the model area `w`.
fn show_window(s: &mut Session, h: Handle, w: Bounds2) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Viewport(v) = &mut e.kind {
(v.view_center, v.view_height) = fit_bounds(w, v.width, v.height);
}
})?;
Ok(())
}
fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layout.delete", "`name` is required"))?;
let name = layout_name("layout.delete", s.doc()?, name)?;
@@ -581,11 +437,6 @@ fn fit_view(d: &Drawing, w: f64, h: f64) -> (Vec2, f64) {
let hi = d.header.point("LIMMAX").map(|p| p.xy()).unwrap_or(Vec2::new(12.0, 9.0));
ext = Bounds2::new(lo, hi);
}
fit_bounds(ext, w, h)
}
/// The view centre and height that show the model area `ext` in a viewport of size `w` × `h`.
fn fit_bounds(ext: Bounds2, w: f64, h: f64) -> (Vec2, f64) {
let aspect = (w / h.max(1e-12)).max(1e-12);
let vh = (ext.height().max(ext.width() / aspect) * 1.02).max(1e-9);
let c = ext.center();
@@ -832,21 +683,8 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
// The standard size the layout had before this call, so that resubmitting it (the Plot
// dialog's Apply to Layout always sends `paper`) keeps the layout's paper units.
let old_paper = cadcraft_render::paper_size(&page.paper).map(|ps| ps.name);
let turned = p.get("landscape").and_then(Value::as_bool).filter(|l| *l != page.landscape);
// The orientation first: a paper taken from a device turns its margins to the sheet the page
// names when `page_device` copies them.
if let Some(l) = turned {
page.landscape = l;
}
// A plotter's own papers (with their printable areas) come first.
let device_paper = super::plotters::page_device(cmd, p, &mut page)?;
// A page that keeps its paper keeps its margins, and the margins are measured against the
// sheet's axes: turning the orientation turns them too (#1266). Explicit margins are already
// on the new sheet's axes.
if turned.is_some() && !device_paper && p.get("margins").is_none() {
page.margins_mm =
if page.landscape { super::plotters::landscape_margins(page.margins_mm) } else { super::plotters::portrait_margins(page.margins_mm) };
}
if let Some(paper) = p.get("paper").filter(|_| !device_paper) {
let n = paper.as_str().ok_or_else(|| bad(cmd, "`paper` must be a paper name"))?;
let ps = cadcraft_render::paper_size(n).ok_or_else(|| {
@@ -885,6 +723,9 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
(None, None) if p.get("width").is_none() && p.get("height").is_none() => {}
_ => return Err(bad(cmd, "`width` and `height` (mm, 0-5080) are both required for a custom size")),
}
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
page.landscape = l;
}
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
// (an ARCH D sheet can be drawn in millimetres, #3249).
if let Some(v) = p.get("paperUnits") {
@@ -1049,7 +890,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
@@ -1068,22 +909,15 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
}
}
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
}
}
+1 -4
View File
@@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
use super::super::{bad, str_param};
use super::layout_name;
use super::prompts::current_layout;
@@ -136,9 +136,6 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("notSaved".into(), json!(lost));
}
}
if drops_unknown(&path) {
report_dwg_notes(s, &mut r, dwg_notes(&t));
}
Ok(r)
}
-136
View File
@@ -88,7 +88,6 @@ fn new_layout_from_the_menu_asks_for_a_name() {
s.cmdline("Layout1").unwrap();
assert!(s.running.is_some(), "a taken name asks again");
s.cmdline("Sheet A").unwrap();
// The name is all it asks: no model area, no tab change.
assert!(s.running.is_none());
s.start("layout.new").unwrap();
s.cmdline("").unwrap();
@@ -96,141 +95,6 @@ fn new_layout_from_the_menu_asks_for_a_name() {
assert!(d.layout("Sheet A").is_some() && d.layout("Layout3").is_some(), "Enter takes the default name");
}
/// LAYOUT.NEWAREA asks the name, then the area; Enter takes the whole drawing.
#[test]
fn new_layout_from_area_asks_a_name_then_the_area() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet A").unwrap();
assert!(s.running.is_some() && s.current_prompt().is_some_and(|p| p.message.contains("first corner of the model area")));
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert!(s.doc().unwrap().layout("Sheet A").is_some());
}
/// The viewport of layout `name`.
fn only_viewport(s: &Session, name: &str) -> Viewport {
let v = viewports(s, name);
assert_eq!(v.len(), 1, "one viewport");
v.into_iter().next().map(|(_, v)| v).unwrap()
}
/// A `window` zooms the new layout's viewport to that part of the model.
#[test]
fn a_new_layout_can_show_a_window_of_the_model() {
let mut s = session_with_model();
s.execute("layout.new", &json!({"name": "Sheet W", "window": [[10, 10], [30, 20]]})).unwrap();
let v = only_viewport(&s, "Sheet W");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "centred on the window: {:?}", v.view_center);
let aspect = v.width / v.height;
assert!(v.view_height >= 10.0 && v.view_height * aspect >= 20.0, "the whole window is in view");
assert!(v.view_height <= (10.0_f64).max(20.0 / aspect) * 1.02 + 1e-9, "and not much more: {}", v.view_height);
// Without a window the viewport shows the model extents, as before.
s.execute("layout.new", &json!({"name": "Sheet E"})).unwrap();
let e = only_viewport(&s, "Sheet E");
assert!(e.view_height > v.view_height * 2.0, "extents are larger than the window");
}
/// A window without area, or not two corners, is an error that leaves no layout behind.
#[test]
fn a_bad_layout_window_adds_no_layout() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
for w in [
json!([[1, 1], [1, 9]]),
json!([[1, 1], [9, 1]]),
json!([[1, 1]]),
json!("all"),
json!([[1, 1], ["a", 2]]),
json!([[f64::MAX, 0], [-f64::MAX, 1]]),
] {
assert!(s.execute("layout.new", &json!({"name": "Bad", "window": w})).is_err(), "{w}");
}
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout is left behind");
}
/// The interactive command shows the Model tab, takes two corners and shows the new layout.
#[test]
fn new_layout_picks_the_model_area_in_the_model_tab() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet P").unwrap();
assert_eq!(s.space(), Space::Model, "the Model tab is shown to pick the area");
s.cmdline("10,10").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message == "Specify opposite corner"));
// A window without width re-asks for the first corner and adds nothing.
s.cmdline("10,30").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message.contains("first corner")), "{:?}", s.current_prompt().map(|p| p.message));
assert!(s.doc().unwrap().layout("Sheet P").is_none());
s.cmdline("10,10").unwrap();
s.cmdline("30,20").unwrap();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Sheet P".into()), "the new layout is shown");
let v = only_viewport(&s, "Sheet P");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "{:?}", v.view_center);
s.undo().unwrap();
assert!(s.doc().unwrap().layout("Sheet P").is_none(), "one undo step");
}
/// A tab shown while the corners are picked ends the command instead of reading points in that space.
#[test]
fn new_layout_ends_if_another_tab_is_shown_while_picking() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet T").unwrap();
assert_eq!(s.space(), Space::Model);
// A tab shown meanwhile: the next point must not be taken for a model corner.
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cmdline("10,10").unwrap();
assert!(s.running.is_none(), "the command ended");
assert_eq!(s.layout_space(), Space::Paper("Layout1".into()), "the tab that was shown stays");
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout was added");
}
/// The opposite-corner prompt is a window corner, so ortho does not bend it.
#[test]
fn the_opposite_corner_is_not_bent_by_ortho() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet O").unwrap();
s.cmdline("10,10").unwrap();
let p = s.current_prompt().unwrap();
assert!(p.corner && p.base == Some(Vec2::new(10.0, 10.0)), "a window's opposite corner prompt");
}
/// Esc puts back the tab the command started in and adds no layout.
#[test]
fn cancelling_new_layout_puts_the_tab_back() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet C").unwrap();
assert_eq!(s.space(), Space::Model);
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout2".into()), "back in the tab it started in: {:?}", s.log);
assert_eq!(s.doc().unwrap().layouts.len(), before);
// Esc at the name prompt changes nothing either.
s.start("layout.newarea").unwrap();
s.cancel();
assert_eq!(s.space(), Space::Paper("Layout2".into()));
}
/// Esc after the user chose another tab leaves that tab shown, not the one the command started in.
#[test]
fn cancelling_new_layout_keeps_a_tab_chosen_meanwhile() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet K").unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout1".into()), "the tab chosen meanwhile stays: {:?}", s.log);
}
#[test]
fn mview_arrangements_and_interactive() {
let mut s = session_with_model();
+2 -6
View File
@@ -18,7 +18,6 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St
mod break_join;
mod explode;
mod extrim;
mod fillet;
mod offset;
mod oops;
@@ -37,14 +36,11 @@ pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
};
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
pub fn specs() -> Vec<CommandSpec> {
vec![
extrim::spec(),
CommandSpec::new("erase", "Erase", run_erase)
.menu(&["Modify", "Erase"])
.alias(&["e", "delete"])
+50 -376
View File
@@ -129,406 +129,80 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
return Err(EngineError::Other("An object is on a locked layer.".into()));
}
let hs = joinable_picks(s.doc()?, hs);
let hs = &hs[..];
if let Some(h) = join_on_source(s, hs)? {
return Ok(Some(h));
}
let d = s.doc()?;
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
// polyline facing down; measured).
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
let mut segs: Vec<Segment> = Vec::new();
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
let mut owners: Vec<Handle> = Vec::new();
let mut common = None;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
let piece =
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
let unit: Vec<Piece> = match &e.kind {
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
EntityKind::Arc(a) => {
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
}
// Repeated vertices included: AutoCAD 2024 keeps them.
EntityKind::LwPolyline(p) if !p.closed => {
// The elevation is along the polyline's normal: down Z for a mirrored one.
let z = if down(e) { -p.elevation } else { p.elevation };
p.vertices
.windows(2)
.map(|w| {
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
})
.collect()
}
_ => Vec::new(),
};
if !unit.is_empty() {
units.push((down(e), unit));
common.get_or_insert_with(|| e.common.clone());
match &e.kind {
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
_ => {}
}
owners.resize(segs.len(), *h);
}
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
if segs.len() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
// on one circle onto those), so objects facing either way still join there.
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
// A new polyline takes the source's properties.
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
let tol = 1e-6;
let links = chain_units(units, tol);
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
// ("0 segments added to polyline").
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
if links.len() < 2 || one_object {
loop {
let start = chain.first().map(Segment::start).unwrap_or_default();
let end = chain.last().map(Segment::end).unwrap_or_default();
let Some(i) =
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
else {
break;
};
let s0 = segs.remove(i);
used.push(owners.remove(i));
if s0.start().near(end, tol) {
chain.push(s0);
} else if s0.end().near(end, tol) {
chain.push(s0.reversed());
} else if s0.end().near(start, tol) {
chain.insert(0, s0);
} else {
chain.insert(0, s0.reversed());
}
}
if chain.len() < 2 {
return Err(EngineError::Other("Objects are not connected.".into()));
}
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
// A polyline's own segments keep their widths.
let mut vs: Vec<PolyVertex> = links
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
.iter()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
.map(|s| PolyVertex {
p: s.start(),
bulge: match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
},
..Default::default()
})
.collect();
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
}
// A new polyline goes in the source's space, whichever space is current.
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
let space = s.space();
let doc = s.doc_mut()?;
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
// added to polyline").
if let Some(src) = first
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
{
for h in hs.iter().filter(|h| **h != src && used(h)) {
doc.remove_entity(*h);
}
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
s.set_selection(Vec::new());
return Ok(Some(src));
}
for h in hs.iter().filter(|h| used(h)) {
for h in hs.iter().filter(|h| used.contains(*h)) {
doc.remove_entity(*h);
}
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
// elevation runs along its normal: negated for one facing down. Not measured: the core
// console's JOIN makes no new polyline.
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
let common = common.unwrap_or_default();
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
let mut kind = lwpoly(vs, closed);
if let EntityKind::LwPolyline(p) = &mut kind {
p.elevation = elevation;
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, common, kind });
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
}
s.set_selection(Vec::new());
Ok(Some(nh))
}
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
let joinable = |h: &Handle| {
d.entity(*h).is_some_and(|e| match &e.kind {
EntityKind::Line(_) => true,
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
EntityKind::LwPolyline(p) => !p.closed,
_ => false,
})
};
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
}
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
/// is (measured).
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
let Ok(d) = s.doc() else { return false };
// Elliptical arcs and splines join another way, and a locked object stops the join.
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
return false;
}
let picks = joinable_picks(d, hs);
let arcs: Vec<&cadcraft_doc::Arc> = picks
.iter()
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => Some(a),
_ => None,
})
.collect();
let tol = 1e-6;
match &arcs[..] {
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
_ => false,
}
}
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
/// and radius). An arc that starts even a hair before the source's start reaches on round past
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
let same_circle =
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
}
/// The chain JOIN builds from the first object: each next object with an end on one of the
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
/// their heights.
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
let near = |p, q| meet(p, q, tol);
if units.is_empty() {
return Vec::new();
}
// A source that already ends where it starts still takes more, unless it has no length at all
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
// length).
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
return chain.into();
}
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
let Some(i) = units.iter().position(meets) else { break };
let unit = units.remove(i);
let Some((a, b)) = ends(&unit) else { break };
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
// it (measured): a polyline by its first vertex if it can, and before the chain rather
// than after it; a line or an arc turned round if it can, its end on the chain's end
// before its start on the chain's start.
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
let (before, turned) = if polyline {
if near(a, start) {
(true, true)
} else if near(a, end) {
(false, false)
} else {
(near(b, start), !near(b, start))
}
} else if near(b, end) {
(false, true)
} else if near(a, start) {
(true, true)
} else {
(!near(a, end), false)
};
match (before, turned) {
(false, false) => chain.extend(unit),
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
}
// A chain that a join closes takes nothing more.
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
break;
}
}
chain.into()
}
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
/// polyline's own segment, its widths.
#[derive(Clone, Copy)]
struct Piece {
owner: Handle,
ends: (Vec2, Vec2),
heights: (f64, f64),
bulge: f64,
widths: Option<(f64, f64)>,
}
impl Piece {
fn flipped(self) -> Self {
Piece {
ends: (self.ends.1, self.ends.0),
heights: (self.heights.1, self.heights.0),
bulge: -self.bulge,
widths: self.widths.map(|(a, b)| (b, a)),
..self
}
}
fn start(&self) -> (Vec2, f64) {
(self.ends.0, self.heights.0)
}
fn end(&self) -> (Vec2, f64) {
(self.ends.1, self.heights.1)
}
}
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
/// at 5 and a line at 0, end to end in plan, stay as they are).
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
}
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
/// polyline joins, the end vertex's widths are cleared.
///
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
/// starts from the source and takes its segments in order).
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
let (&first, &last) = (run.first()?, run.last()?);
if sp.closed || run.len() != last - first + 1 {
return None;
}
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
let mut own = sp.vertices.clone();
if other_polyline && sp.const_width > 0.0 {
// The constant width goes, so spell it out on the source's own segments.
for v in &mut own {
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
}
}
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
let (head, tail) = (widths(own.first()?), widths(own.last()?));
let vertex = |i: usize, fill: (f64, f64)| {
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
};
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
vs.extend(own);
if last + 1 < links.len() {
// The source's end vertex starts the first piece after it.
let v = vertex(last + 1, tail);
if let Some(end) = vs.last_mut() {
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
}
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
}
if other_polyline && let Some(end) = vs.last_mut() {
(end.start_width, end.end_width) = (0.0, 0.0);
}
if closed {
// The last vertex is the first one again.
vs.pop();
}
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
}
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
///
/// - Lines on the source's line make one line, from the source's start end to the farthest
/// point the way it runs (and back past its start if one reaches behind it).
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
/// end; arcs that reach all the way round make a circle, a new object in their place.
///
/// `None` when the objects aren't all of one of those kinds.
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
let d = s.doc()?;
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
if rest.is_empty() || ents.len() != hs.len() {
return Ok(None);
}
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
let tol = 1e-6;
let kind = match &src.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let len = a.dist(b);
let lines: Vec<&cadcraft_doc::Line> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(o) => Some(o),
_ => None,
})
.collect();
let level = |z: f64| (z - l.a.z).abs() < tol;
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
return Ok(None);
}
let u = (b - a) * (1.0 / len);
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
return Ok(None);
}
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
let at = |t: f64| (a + u * t).to3(l.a.z);
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
}
EntityKind::Arc(g) => {
let arcs: Vec<&cadcraft_doc::Arc> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Arc(o) => Some(o),
_ => None,
})
.collect();
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
if far > cadcraft_geom::TAU - tol {
let circle = Entity {
handle: Handle(0),
common: src.common.clone(),
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
};
// In the source's space, whichever space is current.
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs {
doc.remove_entity(*h);
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, ..circle });
}
s.set_selection(Vec::new());
return Ok(Some(nh));
}
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
}
_ => return Ok(None),
};
let src_h = src.handle;
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| **h != src_h) {
doc.remove_entity(*h);
}
doc.modify_entity(src_h, |e| e.kind = kind)?;
s.set_selection(Vec::new());
Ok(Some(src_h))
}
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if p.get("close").and_then(Value::as_bool) == Some(true) {
-719
View File
@@ -1,719 +0,0 @@
//! EXTRIM (Express Tools): every object that crosses one cutting edge loses its part on the side
//! picked. The edge is traced a hair's breadth away on that side, and each object that crossing
//! line meets is trimmed there, with the picked object as the only cutting edge. Objects that don't
//! cross the edge, and the edge itself, stay as they are.
use std::cell::RefCell;
use cadcraft_color::Color;
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, entity_bounds};
use cadcraft_geom::{Bounds2, Line, Vec2, line_line, point_in_polygon};
use serde_json::{Value, json};
use super::offset::offset_points;
use super::{Edges, trim};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{CommandSpec, bad, point_param, targets};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// Most points of the line traced along the edge.
const MAX_FENCE: usize = 10_000;
/// Most objects one call trims.
const MAX_OBJECTS: usize = 10_000;
/// Most stretches one call removes (an object can lose several).
const MAX_STRETCHES: usize = 10_000;
/// Most objects the preview draws (beyond that it shows nothing, to keep the cursor smooth).
const MAX_PREVIEW: usize = 2000;
/// The traced line's distance from the edge, as a fraction of the edge's size.
const TRACE_GAP: f64 = 1e-5;
pub(super) fn spec() -> CommandSpec {
CommandSpec::new("extrim", "Extended Trim", run_extrim)
.menu(&["Tools", "Additional Tools", "Extended Trim"])
.params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut}")
.interactive(|s| Ok(Box::new(ExtrimM::new(s))))
}
/// Whether objects of this kind can be the cutting edge.
fn edge_kind(k: &EntityKind) -> bool {
matches!(
k,
EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::Ellipse(_) | EntityKind::LwPolyline(_) | EntityKind::Spline(_)
)
}
/// Whether TRIM can cut objects of this kind.
fn trimmable(k: &EntityKind) -> bool {
edge_kind(k)
}
/// Whether the object closes on itself, from what it is rather than from where its ends lie: an
/// open polyline drawn back to its start is still open.
fn closed_kind(k: &EntityKind) -> bool {
match k {
EntityKind::Circle(_) => true,
EntityKind::LwPolyline(p) => p.closed,
EntityKind::Ellipse(e) => {
cadcraft_geom::Ellipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio, start: e.start, end: e.end }.is_full()
}
EntityKind::Spline(sp) => sp.closed,
_ => false,
}
}
/// Consecutive polylines joined end to end (an object's primitives come in drawing order).
fn chains(polys: Vec<Vec<Vec2>>, tol: f64) -> Vec<Vec<Vec2>> {
let mut out: Vec<Vec<Vec2>> = Vec::new();
for p in polys.into_iter().filter(|p| p.len() >= 2) {
match out.last_mut() {
Some(cur) if cur.last().zip(p.first()).is_some_and(|(a, b)| a.near(*b, tol)) => cur.extend(p.into_iter().skip(1)),
_ => out.push(p),
}
}
out
}
/// Twice the signed area of a closed polyline (positive: counter-clockwise).
fn signed_area(pts: &[Vec2]) -> f64 {
pts.windows(2).filter_map(|w| Some(w.first()?.cross(*w.get(1)?))).sum()
}
/// Which side of the edge's direction the trace runs on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Side {
Left,
Right,
}
impl Side {
/// The trace's offset sign along the edge's left normal.
fn factor(self) -> f64 {
match self {
Side::Left => 1.0,
Side::Right => -1.0,
}
}
}
/// The full circle or ellipse an arc or elliptical arc lies on: inside and outside it, as OFFSET
/// takes them, decide the side even for a pick past the arc's ends.
#[derive(Clone, Copy)]
enum Round {
Circle { center: Vec2, radius: f64 },
Ellipse { center: Vec2, major: Vec2, ratio: f64 },
}
impl Round {
fn of(k: &EntityKind) -> Option<Round> {
match k {
EntityKind::Arc(a) => Some(Round::Circle { center: a.center.xy(), radius: a.radius }),
EntityKind::Ellipse(e) => Some(Round::Ellipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio }),
_ => None,
}
}
fn center(self) -> Vec2 {
match self {
Round::Circle { center, .. } | Round::Ellipse { center, .. } => center,
}
}
fn inside(self, p: Vec2) -> bool {
match self {
Round::Circle { center, radius } => p.dist(center) < radius,
Round::Ellipse { center, major, ratio } => {
let a = major.len();
let b = a * ratio.abs();
let u = major.normalized();
let d = p - center;
let (x, y) = (d.dot(u) * b, d.dot(u.perp()) * a);
x * x + y * y < (a * b) * (a * b)
}
}
}
}
/// The cutting edge traced along, with the scale of the trim.
#[derive(Clone)]
struct Edge {
handle: Handle,
pts: Vec<Vec2>,
closed: bool,
/// An arc's circle (an elliptical arc's ellipse), and whether its inside is to the left of
/// the edge's direction.
round: Option<(Round, bool)>,
/// Distance of the traced line from the edge.
gap: f64,
}
impl Edge {
/// The cutting edge `h`: a line, arc, circle, ellipse, polyline or spline of the current space.
fn new(s: &Session, h: Handle) -> Result<Edge> {
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| bad("extrim", format!("no object {}", h.hex())))?;
if !edge_kind(&e.kind) {
return Err(bad("extrim", "the cutting edge must be a line, arc, circle, ellipse, polyline or spline"));
}
if d.space_of(h).as_ref() != Some(&s.space()) || !d.is_visible(e) {
return Err(bad("extrim", format!("object {} is not a visible object of the current space", h.hex())));
}
let b = entity_bounds(d, e, 0);
let size = b.width() + b.height();
if !size.is_finite() || size <= 0.0 {
return Err(bad("extrim", "the cutting edge has no length"));
}
let closed = closed_kind(&e.kind);
// A finer trace for a small edge; a coarser one when a long or curved edge would need too
// many points. The trace stays within a twentieth of the gap of the true edge, so the
// traced line never strays to the other side.
let mut gap = (size * TRACE_GAP).max(1e-9);
for _ in 0..6 {
let Some(pts) = chains(crate::select::hit_polylines(d, e, gap / 20.0), gap / 20.0).into_iter().next() else { break };
if pts.len() <= MAX_FENCE {
// The centre lies on the inside of the arc's bend.
let mid = (pts.len() / 2).max(1);
let inside_left = |r: Round| match (pts.get(mid - 1), pts.get(mid)) {
(Some(a), Some(b)) => (*b - *a).cross(r.center() - *a) > 0.0,
_ => true,
};
let round = if closed { None } else { Round::of(&e.kind) }.map(|r| (r, inside_left(r)));
return Ok(Edge { handle: h, pts, closed, round, gap });
}
gap *= 4.0;
}
Err(bad("extrim", "the cutting edge is too complex"))
}
/// Which side the trace runs on for a pick at `p`; `None` for a point on the edge.
fn side(&self, p: Vec2) -> Option<Side> {
if !p.is_finite() {
return None;
}
let segs = || self.pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?)));
let (near, dist) = segs().map(|l| (l, l.dist(p))).min_by(|a, b| a.1.total_cmp(&b.1))?;
if dist <= self.gap {
return None;
}
let left = match self.round {
_ if self.closed => {
// Inside a counter-clockwise outline is to its left.
point_in_polygon(&self.pts, p) == (signed_area(&self.pts) > 0.0)
}
Some((round, inside_left)) => round.inside(p) == inside_left,
None => (near.b - near.a).cross(p - near.closest(p)) > 0.0,
};
Some(if left { Side::Left } else { Side::Right })
}
/// The line traced beside the edge on `side`.
fn trace(&self, side: Side) -> Vec<Vec2> {
offset_points(&self.pts, self.gap * side.factor(), self.closed)
}
}
/// One stretch of an object the trim removes: where it is picked, and its outline.
struct Stretch {
pick: Vec2,
parts: Vec<Vec<Vec2>>,
}
/// Where the trim would cut: each object the trace crosses, with the stretches it loses, and
/// what it leaves alone.
#[derive(Default)]
struct Plan {
work: Vec<(Handle, Vec<Stretch>)>,
locked: usize,
other: usize,
/// Objects the edge crosses but no trim can cut there (a circle crossed once).
uncut: Vec<Handle>,
}
/// Segments of `pts` with their bounds, bucketed in a grid so crossings are found without
/// testing every pair.
struct Grid {
segs: Vec<(Line, Bounds2)>,
bounds: Bounds2,
n: usize,
cells: Vec<Vec<usize>>,
}
impl Grid {
fn new(pts: &[Vec2]) -> Grid {
let segs: Vec<(Line, Bounds2)> =
pts.windows(2).filter_map(|w| Some((Line::new(*w.first()?, *w.get(1)?), Bounds2::from_points([*w.first()?, *w.get(1)?])))).collect();
let bounds = Bounds2::from_points(pts.iter().copied());
// About as many cells as segments.
let n = ((segs.len() as f64).sqrt().ceil() as usize).clamp(1, 128);
let mut g = Grid { segs: Vec::new(), bounds, n, cells: vec![Vec::new(); n * n] };
for (i, (_, b)) in segs.iter().enumerate() {
for c in g.cells_of(b) {
if let Some(cell) = g.cells.get_mut(c) {
cell.push(i);
}
}
}
g.segs = segs;
g
}
/// The cells `b` overlaps.
fn cells_of(&self, b: &Bounds2) -> Vec<usize> {
let w = self.bounds.width().max(1e-12);
let h = self.bounds.height().max(1e-12);
let n = self.n;
let col = |x: f64| ((((x - self.bounds.min.x) / w) * n as f64).floor().max(0.0) as usize).min(n - 1);
let row = |y: f64| ((((y - self.bounds.min.y) / h) * n as f64).floor().max(0.0) as usize).min(n - 1);
let (c0, c1, r0, r1) = (col(b.min.x), col(b.max.x), row(b.min.y), row(b.max.y));
(r0..=r1).flat_map(|r| (c0..=c1).map(move |c| r * n + c)).collect()
}
/// Where segment `l` crosses the grid's segments.
fn crossings(&self, l: &Line) -> Vec<Vec2> {
let lb = Bounds2::from_points([l.a, l.b]);
if !lb.intersects(&self.bounds) {
return Vec::new();
}
let mut seen = std::collections::HashSet::new();
self.cells_of(&lb)
.into_iter()
.filter_map(|c| self.cells.get(c))
.flatten()
.filter(|i| seen.insert(**i))
.filter_map(|i| self.segs.get(*i))
.filter(|(_, b)| b.intersects(&lb))
.filter_map(|(s, _)| line_line(l, s))
.collect()
}
}
/// An object outline measured along its length, for cutting stretches out of it.
struct Outline<'a> {
pts: &'a [Vec2],
/// Distance along the outline to each point.
at: Vec<f64>,
}
impl<'a> Outline<'a> {
fn new(pts: &'a [Vec2]) -> Outline<'a> {
let mut at = Vec::with_capacity(pts.len());
let mut t = 0.0;
at.push(t);
for w in pts.windows(2) {
if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
t += a.dist(*b);
}
at.push(t);
}
Outline { pts, at }
}
fn total(&self) -> f64 {
self.at.last().copied().unwrap_or(0.0)
}
/// The distances along the outline where it crosses `grid`, sorted, each once.
fn crossings(&self, grid: &Grid) -> Vec<f64> {
let mut out = Vec::new();
for (i, w) in self.pts.windows(2).enumerate() {
let (Some(a), Some(b), Some(t0)) = (w.first(), w.get(1), self.at.get(i)) else { continue };
out.extend(grid.crossings(&Line::new(*a, *b)).into_iter().map(|c| t0 + a.dist(c)));
}
out.sort_by(f64::total_cmp);
// A crossing at a vertex shows up on both segments that meet there.
let eps = self.total() * 1e-9;
out.dedup_by(|a, b| (*a - *b).abs() <= eps);
out
}
/// The part of the outline between distances `from` and `to`.
fn part(&self, from: f64, to: f64) -> Vec<Vec2> {
let mut out = Vec::new();
let first = self.at.partition_point(|t| *t < from).saturating_sub(1);
for i in first..self.pts.len().saturating_sub(1) {
let (Some(a), Some(b), Some(t0), Some(t1)) = (self.pts.get(i), self.pts.get(i + 1), self.at.get(i), self.at.get(i + 1)) else { break };
if *t0 > to {
break;
}
if *t1 < from || t1 <= t0 {
continue;
}
let p = |t: f64| *a + (*b - *a) * ((t.clamp(*t0, *t1) - t0) / (t1 - t0));
if out.is_empty() {
out.push(p(from));
}
out.push(p(to.min(*t1)));
}
out
}
}
/// The stretches of one object outline the trim removes on the traced side: between the edge
/// crossings either side of each place the trace meets the outline. Every crossing is found once.
/// `None` for a closed outline the edge crosses only once, which no trim can open.
fn stretches_of(pts: &[Vec2], closed: bool, edge: &Grid, trace: &Grid) -> Option<Vec<Vec<Vec<Vec2>>>> {
let o = Outline::new(pts);
let total = o.total();
let eps = total * 1e-9;
let mut cuts = o.crossings(edge);
if closed {
// The seam: the outline's start and end are one point, so a crossing there is one cut.
for t in &mut cuts {
if *t >= total - eps {
*t = 0.0;
}
}
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|a, b| (*a - *b).abs() <= eps);
} else {
// An object that only touches the edge with an end isn't cut there, as TRIM has it.
cuts.retain(|t| *t > eps && *t < total - eps);
}
let hits = o.crossings(trace);
if cuts.is_empty() || hits.is_empty() {
return Some(Vec::new());
}
if closed && cuts.len() < 2 {
return None;
}
let mut out = Vec::new();
// Each stretch once, however many times the trace meets it.
let mut done = std::collections::HashSet::new();
for tp in hits {
// The edge crossings either side, as indices into `cuts`.
let k = cuts.partition_point(|t| *t < tp);
let lo = k.checked_sub(1);
let hi = (k < cuts.len()).then_some(k);
let (lo, hi) = if closed { (lo.or(cuts.len().checked_sub(1)), hi.or(Some(0))) } else { (lo, hi) };
if !done.insert((lo, hi)) {
continue;
}
let at = |i: Option<usize>| i.and_then(|i| cuts.get(i).copied());
out.push(match (at(lo), at(hi)) {
// Across the seam of a closed outline.
(Some(a), Some(b)) if closed && a >= b => vec![o.part(a, total), o.part(0.0, b)],
(Some(a), Some(b)) => vec![o.part(a, b)],
(None, Some(b)) => vec![o.part(0.0, b)],
(Some(a), None) => vec![o.part(a, total)],
(None, None) => continue,
});
}
Some(out)
}
/// The trim of everything crossing `edge` on `side`, worked out without changing anything.
fn plan(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Result<Plan> {
let trace = edge.trace(side);
let trace_grid = Grid::new(&trace);
let edge_grid = Grid::new(&edge.pts);
let tol = edge.gap / 20.0;
let mut p = Plan::default();
let mut stretches_total = 0;
for h in crate::select::select_fence(d, space, &trace) {
if h == edge.handle {
continue;
}
let Some(e) = d.entity(h) else { continue };
if !trimmable(&e.kind) {
p.other += 1;
continue;
}
if d.layer(&e.common.layer).is_some_and(|l| l.locked) || crate::cmd::blocks::refedit::locked(d, h) {
p.locked += 1;
continue;
}
let outlines = chains(crate::select::hit_polylines(d, e, tol), tol);
// A closed object is one closed outline.
let closed = closed_kind(&e.kind) && outlines.len() == 1;
let mut stretches: Vec<Stretch> = Vec::new();
for pts in &outlines {
let Some(parts) = stretches_of(pts, closed, &edge_grid, &trace_grid) else {
p.uncut.push(h);
continue;
};
for parts in parts {
// Trimmed at the middle of the stretch, well clear of the edge, so the cut
// doesn't depend on how closely the trim follows a curved edge.
let Some(pick) = parts.iter().max_by(|a, b| arc_length(a).total_cmp(&arc_length(b))).and_then(|q| midpoint(q)) else { continue };
stretches.push(Stretch { pick, parts });
}
}
stretches_total += stretches.len();
if !stretches.is_empty() {
p.work.push((h, stretches));
}
if p.work.len() > MAX_OBJECTS {
return Err(bad("extrim", format!("more than {MAX_OBJECTS} objects cross the cutting edge; trim a smaller area")));
}
if stretches_total > MAX_STRETCHES {
return Err(bad("extrim", format!("more than {MAX_STRETCHES} stretches would be trimmed; trim a smaller area")));
}
}
Ok(p)
}
fn arc_length(pts: &[Vec2]) -> f64 {
pts.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?))).sum()
}
/// The point halfway along `pts`.
fn midpoint(pts: &[Vec2]) -> Option<Vec2> {
let mut left = arc_length(pts) / 2.0;
for w in pts.windows(2) {
let (a, b) = (*w.first()?, *w.get(1)?);
let l = a.dist(b);
if l >= left && l > 0.0 {
return Some(a + (b - a) * (left / l));
}
left -= l;
}
pts.last().copied()
}
/// The length of an object's drawn outline.
fn length(d: &Drawing, e: &Entity, tol: f64) -> f64 {
crate::select::hit_polylines(d, e, tol).iter().flat_map(|pl| pl.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?)))).sum()
}
pub(super) fn run_extrim(s: &mut Session, p: &Value) -> Result<Value> {
let h = match p.get("edge") {
Some(Value::String(t)) => {
Handle::parse_hex(t).ok_or_else(|| bad("extrim", "`edge` must be an object handle (a hex string such as \"1A2\")"))?
}
// One cutting edge: several objects would leave which one cuts to chance.
None | Some(Value::Null) => match targets(s, p)?.as_slice() {
[] => return Err(bad("extrim", "`edge` is required")),
[h] => *h,
_ => return Err(bad("extrim", "give exactly one cutting edge")),
},
Some(_) => return Err(bad("extrim", "`edge` must be an object handle (a hex string such as \"1A2\")")),
};
let point = point_param(p, "side").ok_or_else(|| bad("extrim", "`side` ([x, y]) is required"))?;
let edge = Edge::new(s, h)?;
let side = edge.side(point).ok_or_else(|| bad("extrim", "pick the side away from the cutting edge"))?;
trim_side(s, &edge, side)
}
/// Trim every object crossing `edge` on `side`: one undo step, everything checked first.
fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
let space = s.space();
let plan = plan(s.doc()?, &space, edge, side)?;
let edges = Edges { only: Some(std::slice::from_ref(&edge.handle)), implied: false };
let tol = edge.gap / 20.0;
let mut trimmed = 0;
let mut created = Vec::new();
// Objects some planned cut failed on, reported rather than counted as done.
let mut uncut = plan.uncut;
for (h, stretches) in plan.work {
let mut live = vec![h];
let mut cut = false;
// The object as it is before any cut: its lines and arcs, exactly.
let exact = s.doc()?.entity(h).and_then(|e| exact_outline(&e.kind));
for x in stretches.into_iter().map(|st| st.pick) {
// The pick lies on the flattened outline, which strays from a large-radius arc by up to
// a millionth of its radius (far more than `tol` next to a short edge): bring it onto
// the object itself, and measure the pieces exactly too.
let x = exact.as_deref().map_or(x, |segs| on_outline(segs, x));
// A trim replaces the object with pieces: the pick goes to the piece it lies on (none:
// that part is already gone). The pick is on the outline traced within `tol`, so 3 tol
// allows for that and for rounding, and is far less than the distance to any other
// piece, since a stretch's middle is well away from the edge where pieces meet.
let target = {
let d = s.doc()?;
live.iter()
.filter_map(|l| {
let e = d.entity(*l)?;
let dist =
exact_outline(&e.kind).map_or_else(|| crate::select::entity_distance(d, e, x, tol), |segs| on_outline(&segs, x).dist(x));
Some((*l, dist))
})
.filter(|(_, dist)| *dist <= 3.0 * tol)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(l, _)| l)
};
// No piece there: a planned stretch the trim can't find. Say so rather than count
// the object as trimmed through.
let Some(t) = target else {
if !uncut.contains(&h) {
uncut.push(h);
}
continue;
};
let Ok(pieces) = trim(s, t, x, edges) else {
if !uncut.contains(&h) {
uncut.push(h);
}
continue;
};
cut = true;
live.retain(|l| *l != t);
for n in pieces {
// Never leave a piece of no length behind.
let d = s.doc()?;
if d.entity(n).is_some_and(|e| length(d, e, tol) <= tol) {
s.doc_mut()?.remove_entity(n);
} else {
live.push(n);
}
}
}
if cut {
trimmed += 1;
created.extend(live.into_iter().filter(|l| *l != h));
}
}
let mut message = format!("{trimmed} object(s) trimmed.");
if plan.locked > 0 {
message.push_str(&format!(" {} on locked layers left as they are.", plan.locked));
}
if plan.other > 0 {
message.push_str(&format!(" {} that can't be trimmed (blocks, hatches, text…) left as they are.", plan.other));
}
if !uncut.is_empty() {
message.push_str(&format!(" {} could not be cut everywhere the edge crosses them.", uncut.len()));
}
Ok(json!({
"trimmed": trimmed,
"handles": created.iter().map(|h| h.hex()).collect::<Vec<_>>(),
"skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len() },
"message": message,
}))
}
/// An object's outline as exact lines and arcs, when it is made of nothing else (lines, arcs,
/// circles, polylines); `None` for ellipses, splines and the rest.
fn exact_outline(k: &EntityKind) -> Option<Vec<cadcraft_geom::Segment>> {
let mut out = Vec::new();
for p in k.prims() {
match p {
cadcraft_doc::Prim::Seg(sg) => out.push(sg),
cadcraft_doc::Prim::Circle(c) => out.push(cadcraft_geom::Segment::Arc {
arc: cadcraft_geom::Arc { center: c.center, radius: c.radius, start: 0.0, end: std::f64::consts::TAU },
ccw: true,
}),
_ => return None,
}
}
(!out.is_empty()).then_some(out)
}
/// The point of `segs` nearest `p`.
fn on_outline(segs: &[cadcraft_geom::Segment], p: Vec2) -> Vec2 {
segs.iter().map(|sg| sg.closest(p)).min_by(|a, b| a.dist(p).total_cmp(&b.dist(p))).unwrap_or(p)
}
/// The parts the trim would remove, drawn red.
fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Vec<Entity> {
let Ok(plan) = plan(d, space, edge, side) else { return Vec::new() };
if plan.work.len() > MAX_PREVIEW {
return Vec::new();
}
let mut out = Vec::new();
for (h, stretches) in plan.work {
let Some(e) = d.entity(h) else { continue };
for part in stretches.into_iter().flat_map(|st| st.parts).filter(|p| p.len() >= 2) {
let mut ent = Entity::new(Handle(0), lwpoly(part.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false));
ent.common.color = Color::Index(1);
ent.common.layer = e.common.layer.clone();
out.push(ent);
}
}
out
}
/// EXTRIM at the prompts: the cutting edge (or the one object selected beforehand), then the side,
/// with the parts that will go shown red as the cursor moves.
pub(super) struct ExtrimM {
edge: Option<Edge>,
/// The preview for each side (left, right), worked out once.
previews: RefCell<[Option<Vec<Entity>>; 2]>,
}
impl ExtrimM {
fn new(_s: &Session) -> Self {
ExtrimM { edge: None, previews: RefCell::new([None, None]) }
}
fn set_edge(&mut self, s: &mut Session, h: Handle) -> bool {
match Edge::new(s, h) {
Ok(e) => {
self.edge = Some(e);
self.previews = RefCell::new([None, None]);
true
}
Err(e) => {
s.echo(e.to_string());
false
}
}
}
}
impl Interactive for ExtrimM {
fn name(&self) -> &'static str {
"EXTRIM"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
// One object selected beforehand is the cutting edge.
if s.settings.pickfirst
&& let [h] = s.selection().as_slice()
&& s.doc().ok().and_then(|d| d.entity(*h)).is_some_and(|e| edge_kind(&e.kind))
{
let h = *h;
self.set_edge(s, h);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.edge {
None => Prompt::new("Select the cutting edge (line, arc, circle, ellipse, polyline or spline)", Accept::SELECT),
Some(_) => Prompt::new("Specify the side to trim on", Accept::POINT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (&self.edge, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(_, Input::Enter) => Ok(Step::Done),
(None, Input::Pick(hs)) => {
match hs.as_slice() {
[h] => {
self.set_edge(s, *h);
}
[] => s.echo("No object found."),
_ => s.echo("Select exactly one cutting edge."),
}
Ok(Step::Continue)
}
(Some(edge), Input::Point(p)) => {
let Some(side) = edge.side(p) else {
s.echo("Pick the side away from the cutting edge.");
return Ok(Step::Continue);
};
let edge = edge.clone();
s.set_selection(Vec::new());
match trim_side(s, &edge, side) {
Ok(v) => s.echo(v.get("message").and_then(Value::as_str).unwrap_or_default().to_string()),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
}
_ => Ok(Step::Continue),
}
}
fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec<Entity> {
let Some(edge) = &self.edge else { return Vec::new() };
let Some(side) = edge.side(cursor) else { return Vec::new() };
let slot = usize::from(side == Side::Right);
let cached = self.previews.borrow().get(slot).cloned().flatten();
let mut v = match cached {
Some(v) => v,
None => {
let Ok(d) = s.doc() else { return Vec::new() };
let v = preview(d, &s.space(), edge, side);
if let Some(c) = self.previews.borrow_mut().get_mut(slot) {
*c = Some(v.clone());
}
v
}
};
// A band a few pixels wide at the current zoom, so it shows over the object it covers.
let width = 3.0 * s.pixel_size();
for e in &mut v {
if let EntityKind::LwPolyline(p) = &mut e.kind {
p.const_width = width;
}
}
v
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ fn decimate(pts: &[Vec2], max: usize) -> Vec<Vec2> {
v
}
pub(super) fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec<Vec2> {
fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec<Vec2> {
let n = pts.len();
let mut out = Vec::with_capacity(n);
for i in 0..n {
+32 -216
View File
@@ -1,9 +1,8 @@
use super::break_join::{join, join_makes_circle};
use super::break_join::join;
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line,
mirror_entities, mirror_kind, number,
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, number,
};
// ---------------- interactive ----------------
@@ -20,18 +19,6 @@ pub(super) enum Op {
Join,
}
/// COPY's Array option: asking how many items, then where the second one goes (or, with Fit, the
/// last one).
#[derive(Clone, Copy, PartialEq)]
enum CopyArray {
Off,
Count,
Items { n: u16, fit: bool },
}
/// The most items COPY's Array option makes, the original included, as in AutoCAD.
const MAX_COPY_ITEMS: u16 = 32767;
/// Select objects, then collect the points/values the operation needs.
pub(super) struct SelectThen {
op: Op,
@@ -49,16 +36,9 @@ pub(super) struct SelectThen {
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
copy_mode: bool,
/// COPY: one copy and done (COPYMODE 1, until the Multiple option), else copies until Exit.
copy_single: bool,
/// COPY: the objects each placement made, so Undo takes back the last one.
copies: Vec<Vec<Handle>>,
copy_array: CopyArray,
ask_erase: bool,
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
join_source: Option<Handle>,
/// JOIN of arcs that make a circle: asking whether to.
ask_circle: bool,
}
impl SelectThen {
@@ -74,12 +54,8 @@ impl SelectThen {
ref_from: None,
ref_len: None,
copy_mode: false,
copy_single: false,
copies: Vec::new(),
copy_array: CopyArray::Off,
ask_erase: false,
join_source: None,
ask_circle: false,
}
}
fn apply(&mut self, s: &mut Session) -> Result<Step> {
@@ -107,120 +83,8 @@ impl SelectThen {
}
}
/// COPY's prompt once the base point is known, as AutoCAD 2024 asks it.
fn copy_prompt(&self, base: Option<Vec2>) -> Prompt {
match self.copy_array {
CopyArray::Count => Prompt::new("Enter number of items to array", Accept::NUMBER),
CopyArray::Items { fit: false, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Fit"]).base_opt(base),
CopyArray::Items { fit: true, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).base_opt(base),
CopyArray::Off if self.copies.is_empty() => {
Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).default("use first point as displacement").base_opt(base)
}
CopyArray::Off => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).default("Exit").base_opt(base),
}
}
/// COPY once the base point is known (AutoCAD 2024, measured): a point places a copy; Enter
/// at the first prompt copies by the base point taken as a displacement, and after a copy
/// ends the command; Array asks for a number of items, the original included, then puts
/// them a second point apart (or, with Fit, spread up to it, Enter keeping them at the
/// base); Undo takes back the last placement. One placement ends a single-copy COPY.
fn copy_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Continue) };
let placed = match (self.copy_array, i) {
(CopyArray::Count, Input::Enter) => return self.copy_done(s),
(CopyArray::Count, i) => {
// A whole number as typed, from 2 to 32767 whatever the selection: AutoCAD 2024 takes
// +3 and 03 here, refuses 4.0, 1e1, 8/2, 1', 3", 50002 and a point, and doesn't
// apply MAXARRAY (with MAXARRAY 100000, four lines and 26000 items made 104000
// lines; measured).
let n = match i {
Input::Text(t) => t.trim().parse::<u16>().ok().filter(|v| (2..=MAX_COPY_ITEMS).contains(v)),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 2 and {MAX_COPY_ITEMS}.")))?;
// Not AutoCAD's: the copies (items after the first, times the objects) stay within
// ARRAY's own limit, whatever MAXARRAY says, so a large selection can't run out of
// memory.
let copies = u64::from(n - 1).saturating_mul(u64::try_from(self.objs.len()).unwrap_or(u64::MAX));
if copies > cadcraft_doc::MAX_ARRAY_ITEMS {
return Err(EngineError::Other(format!(
"The array would create {copies} objects; the limit is {}. Use fewer items or select fewer objects.",
cadcraft_doc::MAX_ARRAY_ITEMS
)));
}
self.copy_array = CopyArray::Items { n, fit: false };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, Input::Keyword(kw)) if kw == if fit { "Array" } else { "Fit" } => {
self.copy_array = CopyArray::Items { n, fit: !fit };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, i @ (Input::Point(_) | Input::Enter)) => {
let p = if let Input::Point(p) = i { p } else { base };
let step = if fit { (p - base) * (1.0 / f64::from(n - 1)) } else { p - base };
self.copy_array = CopyArray::Off;
let mut made = Vec::new();
for k in 1..n {
match transform_entities(s, &self.objs, &Mat3::translate(step * f64::from(k)), true) {
Ok(hs) => made.extend(hs),
Err(e) => {
// The items made so far are a placement Undo takes back.
self.copies.push(made);
return Err(e);
}
}
}
made
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Array" => {
self.copy_array = CopyArray::Count;
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Undo" => {
if let Some(last) = self.copies.pop() {
let d = s.doc_mut()?;
for h in last {
d.remove_entity(h);
}
if self.copies.is_empty() {
s.echo("Command has been completely undone.");
}
}
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Exit" => return self.copy_done(s),
(CopyArray::Off, Input::Enter) if !self.copies.is_empty() => return self.copy_done(s),
(CopyArray::Off, Input::Enter) => {
transform_entities(s, &self.objs, &Mat3::translate(base), true)?;
return self.copy_done(s);
}
(CopyArray::Off, Input::Point(p)) => transform_entities(s, &self.objs, &Mat3::translate(p - base), true)?,
_ => return Ok(Step::Continue),
};
self.copies.push(placed);
if self.copy_single {
return self.copy_done(s);
}
Ok(Step::Continue)
}
fn copy_done(&mut self, s: &mut Session) -> Result<Step> {
s.set_selection(Vec::new());
Ok(Step::Done)
}
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
/// as AutoCAD 2024 does.
/// JOIN the selected objects and report what they became.
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
if join_makes_circle(s, &self.objs) {
self.ask_circle = true;
return Ok(Step::Continue);
}
self.join_apply(s)
}
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
match join(s, &self.objs) {
Ok(h) => {
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
@@ -230,9 +94,6 @@ impl SelectThen {
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
Some(EntityKind::Spline(_)) => "spline",
Some(EntityKind::Ellipse(_)) => "ellipse",
Some(EntityKind::Line(_)) => "line",
Some(EntityKind::Arc(_)) => "arc",
Some(EntityKind::Circle(_)) => "circle",
_ => "polyline",
};
s.echo(format!("{n} objects joined into 1 {what}"))
@@ -387,11 +248,10 @@ impl SelectThen {
}
}
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
fn needs_mirror_preview(k: &EntityKind) -> bool {
/// Objects whose text MIRROR keeps readable instead of mirroring it with the geometry.
fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
match k {
EntityKind::Insert(i) => !i.attribs.is_empty(),
EntityKind::Hatch(h) => !h.solid || h.gradient.is_some(),
k => matches!(
k,
EntityKind::Text(_)
@@ -405,8 +265,8 @@ fn needs_mirror_preview(k: &EntityKind) -> bool {
}
}
/// Objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
const MAX_MIRROR_OBJECT_PREVIEW: usize = 1000;
/// Text objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
const MAX_MIRROR_TEXT_PREVIEW: usize = 1000;
/// A finite length greater than zero (rejects 0, negatives, NaN and infinity).
fn positive_length(v: Option<f64>) -> Option<f64> {
@@ -446,9 +306,6 @@ impl Interactive for SelectThen {
if self.ask_erase {
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
}
if self.ask_circle {
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
}
if let Some(src) = self.join_source {
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
@@ -469,7 +326,7 @@ impl Interactive for SelectThen {
match (self.op, k) {
(Op::Move | Op::Copy, 0) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]),
(Op::Move, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(base),
(Op::Copy, _) => self.copy_prompt(base),
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(base),
(Op::Rotate | Op::Scale, 0) => Prompt::new("Specify base point", Accept::POINT),
// ROTATE and SCALE offer the angle/factor used last time.
(Op::Rotate, _) => {
@@ -490,7 +347,6 @@ impl Interactive for SelectThen {
_ => Prompt::new("", Accept::POINT),
}
}
/// Advance the selected transform command, applying MIRROR fill policy at commit.
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if !self.sel.done {
match self.sel.feed(s, &i)? {
@@ -502,21 +358,13 @@ impl Interactive for SelectThen {
}
}
}
// No leaves every arc as it is (AutoCAD 2024, measured).
if self.ask_circle {
return match &i {
Input::Keyword(k) if k == "No" => Ok(Step::Done),
Input::Keyword(_) | Input::Enter => self.join_apply(s),
_ => Err(EngineError::Other("Invalid option keyword.".into())),
};
}
if let Some(src) = self.join_source {
return self.join_source_input(s, src, i);
}
if self.ask_erase {
let yes = matches!(&i, Input::Keyword(k) if k == "Yes") || matches!(&i, Input::Text(t) if t.trim().to_ascii_lowercase().starts_with('y'));
let (a, b) = (self.pts[0], self.pts[1]);
mirror_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
transform_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
@@ -537,6 +385,10 @@ impl Interactive for SelectThen {
self.reference = true;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Keyword(kw)) if kw == "Exit" => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(_, 0, Input::Point(p)) => {
self.pts.push(p);
Ok(Step::Continue)
@@ -553,7 +405,15 @@ impl Interactive for SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, i) => self.copy_input(s, i),
(Op::Copy, _, Input::Point(p)) => {
let d = p - self.pts[0];
transform_entities(s, &self.objs, &Mat3::translate(d), true)?;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Enter) => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
let a = match inp {
Input::Point(p) => self.pts[0].angle_to(p),
@@ -596,7 +456,6 @@ impl Interactive for SelectThen {
_ => Ok(Step::Continue),
}
}
/// Build bounded transform previews, retaining readable text and hatch fill directions.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_preview(s, c);
@@ -625,18 +484,13 @@ impl Interactive for SelectThen {
.filter_map(|h| d.entity(*h))
.map(|e| {
let mut k = e.kind.clone();
if self.op == Op::Mirror {
mirror_kind(&mut k, &m);
} else {
k.transform(&m);
}
k.transform(&m);
k
})
.collect();
out.push(line(base, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
fn drag(&self, s: &Session, c: Vec2) -> Option<crate::prompt::Drag> {
if (self.op == Op::Rotate && self.reference) || !self.sel.done {
return None;
@@ -654,19 +508,19 @@ impl Interactive for SelectThen {
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
// Readable text and unchanged hatch directions cannot be drawn by reflecting their
// already-rendered primitives: preview those objects individually, the rest on the GPU.
// Mirrored text keeps reading left to right (MIRRTEXT 0), which the matrix alone can't
// draw: those objects are transformed one by one, the rest is mirrored on the GPU.
let d = s.doc().ok()?;
let mut handles = Vec::with_capacity(self.objs.len());
let mut individual = 0;
let mut texts = 0;
for h in &self.objs {
let Some(e) = d.entity(*h) else { continue };
if !needs_mirror_preview(&e.kind) {
if !keeps_reading_when_mirrored(&e.kind) {
handles.push(*h);
} else if individual < MAX_MIRROR_OBJECT_PREVIEW {
individual += 1;
} else if texts < MAX_MIRROR_TEXT_PREVIEW {
texts += 1;
let mut k = e.kind.clone();
mirror_kind(&mut k, &matrix);
k.transform(&matrix);
extra.push(k);
}
}
@@ -679,13 +533,11 @@ impl Interactive for SelectThen {
pub(super) struct DisplaceM {
inner: SelectThen,
displacement: bool,
/// COPY's mOde option: asking Single or Multiple.
ask_mode: bool,
}
impl DisplaceM {
pub(super) fn new(op: Op) -> Self {
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
DisplaceM { inner: SelectThen::new(op), displacement: false }
}
/// At "Specify base point": objects selected, no point yet.
fn at_base(&self) -> bool {
@@ -698,26 +550,14 @@ impl Interactive for DisplaceM {
self.inner.name()
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.inner.copy_single = self.inner.op == Op::Copy && s.settings.copymode;
self.inner.begin(s)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.displacement {
return Prompt::new("Specify displacement", Accept::POINT).default("0,0");
}
if self.ask_mode {
let current = if s.settings.copymode { "Single" } else { "Multiple" };
return Prompt::new("Enter a copy mode option", crate::cmd::curves::KW).kw(&["Single", "Multiple"]).default(current);
}
if self.at_base() {
// COPY: mOde sets COPYMODE; Multiple, offered while it is single, copies until Exit
// this once.
let kw: &[&str] = match self.inner.op {
Op::Copy if self.inner.copy_single => &["Displacement", "mOde", "Multiple"],
Op::Copy => &["Displacement", "mOde"],
_ => &["Displacement"],
};
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
}
self.inner.prompt(s)
}
@@ -734,34 +574,10 @@ impl Interactive for DisplaceM {
s.set_selection(Vec::new());
return Ok(Step::Done);
}
if self.ask_mode {
match &i {
Input::Keyword(k) if k == "Single" || k == "Multiple" => s.settings.copymode = k == "Single",
Input::Enter => {}
_ => return Ok(Step::Continue),
}
// The mode shown is the mode this COPY runs in, Enter keeping it.
self.inner.copy_single = s.settings.copymode;
self.ask_mode = false;
return Ok(Step::Continue);
}
if self.at_base() && (matches!(&i, Input::Enter) || matches!(&i, Input::Keyword(k) if k == "Displacement")) {
self.displacement = true;
return Ok(Step::Continue);
}
if self.at_base() && self.inner.op == Op::Copy {
match &i {
Input::Keyword(k) if k == "mOde" => {
self.ask_mode = true;
return Ok(Step::Continue);
}
Input::Keyword(k) if k == "Multiple" => {
self.inner.copy_single = false;
return Ok(Step::Continue);
}
_ => {}
}
}
self.inner.input(s, i)
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
+4 -55
View File
@@ -3,7 +3,6 @@ use super::{
Accept, Entity, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelectKind, SelectMode, Session, Step, Value, Vec2, bad, json,
line, points_param,
};
use cadcraft_geom::Arc;
/// An area whose vertices STRETCH moves: a window's box, or a polygon closed back to its first
/// point.
@@ -41,18 +40,6 @@ fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>)
}
}
/// The bulge that keeps an arc's height (bulge × chord / 2) when its chord changes length; none
/// once the chord collapses to a point, which has no arc left to keep.
fn keep_height(bulge: f64, old_chord: f64, new_chord: f64) -> f64 {
if new_chord.is_nan() || new_chord <= 1e-12 {
0.0
} else if old_chord.is_finite() {
bulge * old_chord / new_chord
} else {
bulge
}
}
/// Move the vertices of `e` that lie inside any of the areas `wins` by `d` (STRETCH).
fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
let inside = |p: Vec2| wins.iter().any(|a| a.contains(p));
@@ -68,56 +55,18 @@ fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
mv(&mut l.b);
}
EntityKind::LwPolyline(pl) => {
let old: Vec<Vec2> = pl.vertices.iter().map(|v| v.p).collect();
for v in &mut pl.vertices {
if inside(v.p) {
v.p += d;
}
}
// An arc segment keeps its height (bulge × chord / 2) as its ends move, as in AutoCAD.
let n = pl.vertices.len();
let segs = if pl.closed { n } else { n.saturating_sub(1) };
for i in 0..segs {
let j = (i + 1) % n;
let (Some(a0), Some(b0), Some(b1)) = (old.get(i), old.get(j), pl.vertices.get(j).map(|v| v.p)) else { continue };
if let Some(v) = pl.vertices.get_mut(i)
&& v.bulge != 0.0
{
v.bulge = keep_height(v.bulge, a0.dist(*b0), v.p.dist(b1));
}
}
}
EntityKind::MLine(m) => m.vertices.iter_mut().for_each(|v| mv(&mut v.p)),
EntityKind::Arc(a) => {
// AutoCAD moves the ends inside the area and keeps the arc's height (bulge × chord / 2);
// the centre alone moves nothing. An end stretched onto the other leaves the arc as it
// was: AutoCAD collapses it into a zero-radius arc at that point (radius 6e-16, start
// 180°, end 0°), an object nothing can draw or pick, which CADCraft does not make.
let g = Arc::new(a.center.xy(), a.radius, a.start, a.end);
let (s0, e0) = (g.start_point(), g.end_point());
let (s_in, e_in) = (inside(s0), inside(e0));
let (s1, e1) = (if s_in { s0 + d } else { s0 }, if e_in { e0 + d } else { e0 });
if s_in && e_in {
// Both ends move: the arc moves whole (a full sweep has no chord to rebuild from).
(a.center.x, a.center.y) = (a.center.x + d.x, a.center.y + d.y);
} else if (s_in || e_in)
&& let Some((r, _)) =
cadcraft_geom::bulge_to_arc(s1, e1, keep_height(cadcraft_geom::arc_to_bulge(g.sweep()), s0.dist(e0), s1.dist(e1)))
{
(a.center.x, a.center.y) = (r.center.x, r.center.y);
(a.radius, a.start, a.end) = (r.radius, r.start, r.end);
}
}
// Control points inside the area move (AutoCAD).
EntityKind::Spline(sp) if sp.fit.is_empty() => sp.control.iter_mut().filter(|p| inside(**p)).for_each(|p| *p += d),
// A spline built from fit points: the fit points inside the area move and it is fitted
// through them again, its fit data kept (AutoCAD 2024). All of them inside, it moves.
EntityKind::Spline(sp) => {
if sp.fit.iter().all(|p| inside(*p)) {
sp.transform(&Mat3::translate(d));
} else if sp.fit.iter().any(|p| inside(*p)) {
let fit: Vec<Vec2> = sp.fit.iter().map(|p| if inside(*p) { *p + d } else { *p }).collect();
*sp = sp.refit(&fit, sp.closed);
// Arcs keep their shape: move when the centre is inside.
if inside(a.center.xy()) {
a.center.x += d.x;
a.center.y += d.y;
}
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),

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