Compare commits

..
237 changed files with 1006 additions and 29136 deletions
-16
View File
@@ -1,16 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
-107
View File
@@ -1,107 +0,0 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"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": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "cadcraft-nightly-20261124-initial",
"repository": "storytold/cadcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135820,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_cadcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_cadcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
-42
View File
@@ -1,42 +0,0 @@
name: CADCraft release-ref nightly signer
# 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:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: cadcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
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@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
-34
View File
@@ -1,34 +0,0 @@
name: CADCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/cadcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
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 #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+2 -30
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
workflow_dispatch:
permissions:
@@ -49,31 +49,3 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the nightly scripts without running them
run: |
for script in packaging/nightly-common.sh packaging/linux/nightly.sh packaging/macos/nightly.sh \
packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do
bash -n "$script"
done
shellcheck --version
shellcheck -x -P packaging packaging/nightly-common.sh packaging/linux/nightly.sh \
packaging/macos/nightly.sh packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh
- name: Enforce the nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Render the Arch Nightly handoff from stub binaries
run: bash packaging/linux/nightly-arch-tar-test.sh
-8
View File
@@ -9,11 +9,3 @@
*.swp
/apps/cadcraft-web/dist/
/.claude/worktrees/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions):
# nightly_init refuses to build from a tree where these show up as changes.
/.nightly-tools
/.nightly-input
/craft-i18n
/craft-fonts
__pycache__/
+69
View File
@@ -0,0 +1,69 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**CADCraft** (`storytold/cadcraft`) is an open-source computer-aided design and drafting application written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `cadcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/cadcraft`](https://github.com/storytold/cadcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/cadcraft`](https://github.com/storytold/cadcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/cadcraft`](https://github.com/storytold/cadcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
-42
View File
@@ -45,12 +45,6 @@ Generated-in-code assets are original and have no file to list:
| `assets/app-icon/cadcraft-256.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-1024.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-macos-512.png` | CADCraft contributors | generated (macOS margin variant) | MIT OR Apache-2.0 | |
| `assets/app-icon/README.md` | CADCraft contributors | original work for this repository | MIT OR Apache-2.0 | How each icon is generated and which mark each channel uses |
| `assets/app-icon/cadcraft-nightly.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | Nightly mark: same glyph, deeper background `#0c657b`; the Linux nightly tar's icon |
| `assets/app-icon/cadcraft-nightly-1024.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | 1024 master the nightly `.icns` is generated from |
| `assets/app-icon/cadcraft-nightly.ico` | CADCraft contributors | generated from `assets/app-icon/cadcraft-nightly-1024.png` | MIT OR Apache-2.0 | Windows nightly icon (16–256 px entries) for `build.rs` |
| `assets/app-icon/cadcraft-nightly.icns` | CADCraft contributors | generated from `assets/app-icon/cadcraft-nightly-1024.png` | MIT OR Apache-2.0 | macOS nightly bundle icon (`CFBundleIconFile cadcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | CADCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact background transform that produced the nightly set |
| `packaging/macos/dmg/background.svg` | @XusBadia | original work for this repository (2026-10-08), "CADCraft macOS DMG window background"; derived from the CADCraft app icon (`assets/app-icon/`, referenced via `<image>`, not copied); text is outlined Inter / JetBrains Mono glyph paths (OFL fonts the project already uses); no third-party material modified | MIT OR Apache-2.0 (same as the code: `LICENSE-MIT`, `LICENSE-APACHE`) | Finder window background of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` (see `packaging/macos/dmg/README.md`) |
| `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (same as the code: `LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
| `examples/apartment.dxf` | CADCraft contributors | sample drawing made with cadcraft-cli commands | MIT OR Apache-2.0 | Original |
@@ -89,39 +83,3 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
| `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
+6 -133
View File
@@ -156,34 +156,19 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib 2.0.4",
]
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib 3.0.0",
"alloc-no-stdlib",
]
[[package]]
@@ -607,35 +592,14 @@ dependencies = [
"piper",
]
[[package]]
name = "brotli"
version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
"brotli-decompressor 5.0.3",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
@@ -713,7 +677,6 @@ dependencies = [
"windows",
"winit",
"winresource",
"winsafe",
"zbus",
]
@@ -773,7 +736,6 @@ dependencies = [
"cadcraft-geom",
"cadcraft-io",
"cadcraft-render",
"craft-csv",
"craft-docpath",
"craft-dxf",
"craft-mime",
@@ -823,8 +785,6 @@ dependencies = [
"craft-pdf",
"craft-svg",
"image",
"kurbo",
"lyon_tessellation",
"miniz_oxide 0.9.1",
"serde",
"serde_json",
@@ -1228,14 +1188,6 @@ name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-csv"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
@@ -1369,7 +1321,7 @@ name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"brotli-decompressor 6.3.2",
"brotli-decompressor",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
@@ -1391,7 +1343,6 @@ name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"hayro-interpret",
"hayro-syntax",
"krilla",
"thiserror 2.0.21",
@@ -2535,39 +2486,11 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"brotli",
"hayro-postscript",
]
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
"hayro-syntax",
"kurbo",
"moxcms",
"phf 0.13.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.47.0",
"smallvec",
"yoke",
]
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"fearless_simd",
"hayro-ccitt",
]
@@ -2580,21 +2503,13 @@ dependencies = [
"fearless_simd",
]
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"flate2",
"hayro-ccitt",
"hayro-jbig2",
"hayro-jpeg2000",
"memchr",
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
@@ -3994,37 +3909,17 @@ dependencies = [
"phf_shared 0.11.3",
]
[[package]]
name = "phf"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros 0.13.1",
"phf_shared 0.13.1",
]
[[package]]
name = "phf"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_macros 0.14.0",
"phf_macros",
"phf_shared 0.14.0",
"serde",
]
[[package]]
name = "phf_generator"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared 0.13.1",
]
[[package]]
name = "phf_generator"
version = "0.14.0"
@@ -4035,26 +3930,13 @@ dependencies = [
"phf_shared 0.14.0",
]
[[package]]
name = "phf_macros"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator 0.13.1",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "phf_macros"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
dependencies = [
"phf_generator 0.14.0",
"phf_generator",
"phf_shared 0.14.0",
"proc-macro2",
"quote",
@@ -4070,15 +3952,6 @@ dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
-7
View File
@@ -39,8 +39,6 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
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"] }
@@ -120,9 +116,6 @@ debug = 0
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
-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.
+3 -9
View File
@@ -118,7 +118,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, 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
@@ -344,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.
@@ -383,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 {
-1
View File
@@ -49,7 +49,6 @@ fn install_io() {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
-4
View File
@@ -171,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
View File
@@ -2,7 +2,6 @@ mod cli;
mod drafting_spacing;
mod help;
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:?}");
-1
View File
@@ -123,7 +123,6 @@ mod web {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
+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;
-3
View File
@@ -77,9 +77,6 @@ windows = { version = "0.62", features = ["UI_ViewManagement"] }
# One CADCraft per sign-in: later launches hand their files over an AF_UNIX socket
# (single_instance.rs). Already in Cargo.lock through zbus.
uds_windows = "1.2.1"
# The Nightly build's own taskbar identity (process_identity.rs): the explicit
# AppUserModelID, which only a nightly launch sets.
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "linux")'.dependencies]
hidapi = { version = "2.6.7", default-features = false, features = ["linux-native-basic-udev"] }
+5 -46
View File
@@ -1,64 +1,23 @@
//! Windows only: embed the app icon and version info into `cadcraft.exe`. Elsewhere a no-op.
//!
//! The build channel comes from `CADCRAFT_BUILD_CHANNEL`: `nightly-v1` compiles a Nightly build
//! with its own icon and version, `stable`/unset is the stable build, and anything else is refused
//! rather than silently producing a stable binary with a nightly name.
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=src/build_channel.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=CADCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_SHA");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=CADCRAFT_VERSION");
println!("cargo:rustc-check-cfg=cfg(cadcraft_nightly_v1)");
let nightly = match std::env::var("CADCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=cadcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported CADCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
// The version the build reports: the prepared feed identity for a nightly (refused when it is
// missing or is not a nightly identity), the crate version otherwise.
let built_version = if nightly {
match std::env::var("CADCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit CADCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=CADCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "CADCraft Nightly" } else { "CADCraft" })
.set("FileDescription", if nightly { "CADCraft Nightly computer-aided design" } else { "CADCraft computer-aided design" })
if std::path::Path::new("../../assets/app-icon/cadcraft.ico").exists() {
res.set_icon("../../assets/app-icon/cadcraft.ico");
}
res.set("ProductName", "CADCraft")
.set("FileDescription", "CADCraft computer-aided design")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "cadcraft.exe")
.set("InternalName", "cadcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("CADCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
-53
View File
@@ -1,53 +0,0 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/cadcraft-nightly.ico" } else { "../../assets/app-icon/cadcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/cadcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/cadcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
for invalid in [
"",
"0.23.1",
"0.23.1-nightly",
"0.23.1-nightly.20261120",
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
-70
View File
@@ -1,70 +0,0 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
-29
View File
@@ -71,10 +71,6 @@ impl Env {
fn from_vars_and_exe(var: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&std::path::Path>) -> Env {
let mut vars = Env::from_vars(&var);
// The Nightly profile owns every data root before the first use (see [`apply_profile`]).
if Self::apply_profile(&mut vars, crate::launch_profile::current().root()) {
return vars;
}
// An explicit override (including blank, which disables settings) takes precedence.
if var(CONFIG_DIR).is_none()
&& let Some(exe) = exe_dir
@@ -91,17 +87,6 @@ impl Env {
vars
}
/// Point every data root this process resolves at the Nightly profile `root`: the settings folder
/// (logs, autosave and Drawing Recovery, workspace, plotters, LISP support, crash reports) and
/// eframe's own storage file, which would otherwise go to the stable user profile. `false` for a
/// stable launch, which then resolves its folders as before.
fn apply_profile(vars: &mut Env, root: Option<&std::path::Path>) -> bool {
let Some(root) = root else { return false };
vars.config_dir = Some(root.to_path_buf());
vars.portable_storage_file = Some(root.join("app.ron"));
true
}
/// [`Env::read`] with `var` looking a variable up.
pub(crate) fn from_vars(var: impl Fn(&str) -> Option<OsString>) -> Env {
let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty());
@@ -139,20 +124,6 @@ mod tests {
use super::*;
use std::cell::RefCell;
/// The Nightly profile is the settings folder and eframe's storage file, before any portable
/// or platform resolution: no stable folder is read or written by a nightly launch.
#[test]
fn a_launch_profile_owns_the_settings_folder_and_the_eframe_storage_file() {
let profile = std::path::PathBuf::from("/nightly-data/profile");
let mut vars = Env::from_vars(|_| None);
// A stable launch keeps the platform resolution.
assert!(!Env::apply_profile(&mut vars, None));
assert!(!vars.portable_storage_file.as_ref().is_some_and(|f| f.ends_with("app.ron")));
assert!(Env::apply_profile(&mut vars, Some(&profile)));
assert_eq!(vars.config_dir, Some(profile.clone()));
assert_eq!(vars.portable_storage_file, Some(profile.join("app.ron")));
}
#[test]
fn portable_eframe_storage_is_a_file_inside_the_settings_directory() {
let exe = std::env::temp_dir().join(format!("cadcraft-env-portable-{}", std::process::id()));
-211
View File
@@ -1,211 +0,0 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::portable::probe)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+18 -205
View File
@@ -16,23 +16,16 @@
#[cfg(any(target_os = "macos", test))]
mod apple_events;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod desktop_theme;
mod env;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod launch_args;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod portable;
mod process_identity;
mod profile_root;
#[cfg(target_os = "macos")]
mod sheet;
mod single_instance;
@@ -41,7 +34,6 @@ mod system_animations;
mod workspace;
use cadcraft_engine::Session;
use cadcraft_ui_egui::os_window::{self, LaunchIdentity};
use cadcraft_ui_egui::switch::Switch;
use cadcraft_ui_egui::{CadApp, Pick, Services, i18n};
@@ -159,11 +151,6 @@ impl eframe::App for App {
self.persist_workspace(None);
self.cad.cancel_screenshots();
self.cad.shutdown_autosave();
// The host's last step, once: on macOS Cmd+Q ends the process here, after this, so the
// Nightly session record is finished by this hook and never by the code after `run_native`.
if let Some(at_exit) = self.cad.services.at_exit.take() {
at_exit();
}
}
/// Preferences (the interface theme) survive restarts; eframe saves the window state itself
/// (`persist_window`); egui state is not kept.
@@ -188,7 +175,6 @@ pub fn install_io() {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
@@ -213,8 +199,6 @@ fn services() -> Services {
pick_pgp: Some(Box::new(|dir: Option<&str>| {
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
})),
// Set in `main` once the Nightly session record exists.
at_exit: None,
}
}
@@ -225,7 +209,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(),
@@ -267,8 +250,7 @@ fn saved_window(app_ron: &str) -> bool {
/// unusable) is dropped first, so the window opens at its default size. `portable_file`: the
/// portable copy's settings file, read instead of the user profile's.
fn restores_window(portable_file: Option<&std::path::Path>) -> bool {
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(os_window::app_id()).map(|dir| dir.join("app.ron")))
else {
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron"))) else {
return false;
};
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
@@ -305,14 +287,14 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_title("CADCraft")
.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()),
.with_app_id(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,
@@ -329,6 +311,8 @@ fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
}
}
const APP_ID: &str = "ai.storyteller.cadcraft";
/// The key eframe saves the main window state under in its storage.
const WINDOW_KEY: &str = "window";
@@ -352,118 +336,22 @@ fn app_icon() -> Option<egui::IconData> {
eframe::icon_data::from_png_bytes(APP_ICON_PNG).map_err(|e| log::warn!("app icon: {e}")).ok()
}
/// The version this build reports: the prepared nightly identity, or the workspace version.
fn built_version() -> &'static str {
env!("CADCRAFT_BUILT_VERSION")
}
/// The stable line, exactly what clap prints for `--version`: `cadcraft <workspace version>`.
fn version_string() -> String {
format!("cadcraft {}", cadcraft_engine::build_version())
}
/// The Nightly identity line every nightly script checks: `<App> <version> (nightly-v1)`, with the
/// prepared nightly version embedded at build time. The app name never gains a "Nightly".
fn nightly_version_line() -> String {
format!("CADCraft {}", build_flavor::version(build_flavor::BuildFlavor::NightlyV1, built_version()))
}
/// The identity this build reports in its log: the Nightly line on that channel, stable's otherwise.
fn reported_version() -> String {
match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => version_string(),
build_flavor::BuildFlavor::NightlyV1 => nightly_version_line(),
}
}
/// The reported line with the commit, for the log: a bug report's log names the build it came from.
fn log_version() -> String {
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
}
/// Whether this start runs the isolated Nightly flavor.
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// 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 build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
}
let _ = rfd::MessageDialog::new()
.set_title(os_window::name_for(LaunchIdentity::NightlyV1))
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer
/// the version query before any of that: `None` means the query has been answered and the process
/// should return success without opening a window.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
fn main() -> eframe::Result {
// A copy of this program started to read or write a DWG file does only that. It is started
// with `--dwg-worker` alone, so it is answered before the launch profile is required.
// A copy of this program started to read or write a DWG file does only that.
if let Some(code) = cadcraft_io::dwg_worker::serve_if_asked() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
cadcraft_io::dwg_worker::use_own_worker();
// First, so every start-up record is captured; see `logging`.
let logger = logging::install();
// The update helper relaunches this binary after a self-update; it runs and exits here. A
// nightly build is updated by the Launcher only, so it never finishes a stable helper.
// The update helper relaunches this binary after a self-update; it runs and exits here.
#[cfg(not(target_arch = "wasm32"))]
if !is_nightly()
&& let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &arguments)
{
if let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if let Err(e) = done {
eprintln!("CADCraft update helper failed: {e}");
std::process::exit(1);
@@ -473,25 +361,14 @@ fn main() -> eframe::Result {
// `--help` and `--version` print to standard output and exit 0. A usage error (an unknown or
// repeated flag, a missing or bad value, a bad CADCRAFT_CONTROL_PORT) names the argument on
// standard error and exits 2 before the window opens.
let launch = launch_args::parse(launch_args::command(), arguments).unwrap_or_else(|e| e.exit());
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
let vars = env::Env::read();
let (control_port, sample, files) = (launch.control, launch.sample, launch.files);
// A nightly launch accepts no control server: the inherited CADCRAFT_CONTROL_PORT and the
// Launcher's agent link belong to the stable app, and a second unauthenticated surface over
// the nightly profile is not part of the protocol.
let control_port = if is_nightly() {
if control_port.is_some() {
eprintln!("CADCraft Nightly: the control server is off in this channel; the option is ignored");
}
None
} else {
control_port
};
// The log file lives under the settings directory; opened after the arguments, so `--version`
// leaves no file behind. Records logged until now are written to it first.
if let Some(logger) = logger {
match vars.config_dir.as_ref().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", log_version(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", version_string(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
Some(Err(e)) => log::warn!("no log file: {e}"),
None => {
logger.stderr_only();
@@ -502,32 +379,13 @@ fn main() -> eframe::Result {
// A launch that only names files hands them to the CADCraft already running and exits.
let handed = single_instance::absolute(&files);
let may_hand_off = handed.is_some() && !launch.new_window && !files.is_empty() && control_port.is_none() && !sample;
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off, launch_profile::current().root()) {
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off) {
single_instance::Claim::HandedOff => return Ok(()),
single_instance::Claim::Primary(server) => Some(server),
single_instance::Claim::Alone => None,
};
install_io();
cadcraft_engine::settings_dir::set(vars.config_dir.clone());
// Nightly session health: the owner's lease and unclean-exit record live in the profile, and the
// record is finished on the way out (on macOS in `on_exit`, see `nightly_session`).
let (nightly_watch, previous_unclean) =
match nightly_session::Session::begin_with_health(launch_profile::current().root(), built_version(), option_env!("CADCRAFT_BUILD_SHA")) {
Ok((watch, unavailable)) => {
if unavailable {
log::warn!("another CADCraft Nightly holds this profile's session lease; this window keeps no health record");
}
let unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean);
(std::sync::Arc::new(std::sync::Mutex::new(watch)), unclean)
}
Err(error) => {
log::warn!("Nightly session state: {error}");
(std::sync::Arc::new(std::sync::Mutex::new(None)), false)
}
};
if previous_unclean {
log::warn!("the previous CADCraft Nightly ended without finishing its session record");
}
if let Some(dir) = &vars.config_dir {
cadcraft_ui_egui::fault::install_report_hook(dir.join(cadcraft_ui_egui::fault::REPORT_DIR));
}
@@ -544,16 +402,12 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
let persistence_path = vars
.portable_storage_file
.clone()
.or_else(|| std::env::var_os("CADCRAFT_CONFIG_DIR").and_then(|_| vars.config_dir.as_ref().map(|d| d.join("app.ron"))));
let mut options = eframe::NativeOptions {
// The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil)
persistence_path: vars.portable_storage_file.clone(),
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -598,19 +452,11 @@ fn main() -> eframe::Result {
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
// The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it.
let exit_watch = std::sync::Arc::clone(&nightly_watch);
let result = eframe::run_native(
os_window::name_for(os_window::identity()),
eframe::run_native(
"CADCraft",
options,
Box::new(move |cc| {
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.
app.services.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, previous_unclean)));
if previous_unclean {
app.set_status("CADCraft Nightly ended unexpectedly last time; your drawings were recovered where autosave had them.");
}
// File dialogs are sheets on macOS: a modal loop inside the event handler crashes the
// app when the dialog is resized (#1527).
#[cfg(target_os = "macos")]
@@ -622,17 +468,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);
@@ -654,10 +489,7 @@ fn main() -> eframe::Result {
// Autosave files (SAVEFILEPATH) default to `<settings dir>/autosave`.
if let Some(dir) = &vars.config_dir {
app.enable_autosave(&dir.join("autosave"));
// A nightly build is updated by the Launcher, never by the app's own update check.
if !is_nightly() {
app.enable_update_check();
}
app.enable_update_check();
// Startup LISP (acad.lsp, acaddoc.lsp) is read from `<settings>/support`; the
// folder is made so it is there to put them in.
let support = dir.join("support");
@@ -722,20 +554,12 @@ fn main() -> eframe::Result {
apple_events,
}))
}),
);
// The controlled return path: a start that created no window still finishes its record. On macOS
// a quit never reaches here, and the exit hook above has done it. No window ran, so no notice was
// shown: pass false and an unclean record survives for the next launch to report.
nightly_session::finish_once(&nightly_watch, false);
result
)
}
#[cfg(test)]
mod tests {
use super::{
STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
without_tiny_window,
};
use super::{STENCIL_BITS, filters_for_save, follow_desktop, saved_window, stencil_bits, window_options, without_tiny_window};
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -818,17 +642,6 @@ mod tests {
assert_eq!(without_tiny_window("not ron"), None);
}
/// The two identity lines. Nightly prints the kit's `<App> <version> (nightly-v1)` -- the app
/// name never gains a "Nightly" -- while stable keeps exactly the line clap prints, which
/// `launch_args` asserts against its own `-V` output.
#[test]
fn the_version_lines_name_the_app_and_its_channel() {
let nightly = nightly_version_line();
assert_eq!(nightly, format!("CADCraft {} (nightly-v1)", super::built_version()));
assert!(!nightly.contains("Nightly "), "the version line must not rename the app: {nightly}");
assert_eq!(version_string(), format!("cadcraft {}", cadcraft_engine::build_version()));
}
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
#[test]
+1 -2
View File
@@ -148,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);
}
}
-287
View File
@@ -1,287 +0,0 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write as _};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
/// Replace `path` with `bytes` without ever writing through a symbolic link at the destination.
///
/// The engine's [`cadcraft_engine::atomic_write`] resolves a destination link so that its target is
/// replaced; a profile entry is not ours to redirect, so here a link at the destination is refused,
/// and the bytes are written to a fresh temporary in the same folder (created exclusively, so a
/// planted temporary cannot be followed either) before it is renamed over the destination.
fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if !metadata.file_type().is_file() => {
return Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory"));
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let dir = path.parent().unwrap_or_else(|| Path::new("."));
for attempt in 0..32_u32 {
let temporary = dir.join(format!(".{}.{}-{attempt}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
let mut file = match OpenOptions::new().write(true).create_new(true).open(&temporary) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
};
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
return match std::fs::rename(&temporary, path) {
Ok(()) => Ok(()),
Err(error) => {
let _ = std::fs::remove_file(&temporary);
Err(error)
}
};
}
Err(io::Error::other("no free temporary name for the Nightly session state"))
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
// A raced destination link is refused, not followed ([`write_atomic_no_follow`]).
write_atomic_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("cadcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The CPU retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+10 -28
View File
@@ -3,39 +3,21 @@
use std::io::Write as _;
use std::path::{Path, PathBuf};
/// The marker file a portable copy ships beside `cadcraft.exe`.
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
/// The settings folder a portable copy keeps beside the executable.
pub(crate) const PORTABLE_DATA_DIR: &str = "CADCraftData";
/// The marker path, when `dir` holds a marker file (not a directory of that name).
pub(crate) fn portable_marker(dir: &Path) -> Option<PathBuf> {
let marker = dir.join(PORTABLE_MARKER);
marker.is_file().then_some(marker)
}
/// Prove `dir` is writable with the one exclusive probe this app uses: a fresh file holding a byte
/// (a full drive can still create an empty file and refuse its data) and its flush, removed again.
/// The nightly profile check and the portable check share it, so both test the same thing.
pub(crate) fn probe(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let probe = dir.join(format!(".portable-write-test-{}", std::process::id()));
/// A marker must be a file. Prove the data folder is writable before selecting it.
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
if !exe_dir.join("portable.txt").is_file() {
return Ok(None);
}
let data = exe_dir.join("CADCraftData");
std::fs::create_dir_all(&data)?;
let probe = data.join(format!(".portable-write-test-{}", std::process::id()));
// A byte, not just an empty file: a full drive can still make the file and refuse its data.
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
let written = file.write_all(&[0]).and_then(|()| file.sync_all());
drop(file);
let removed = std::fs::remove_file(&probe);
written?;
removed
}
/// A marker must be a file. Prove the data folder is writable before selecting it.
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
if portable_marker(exe_dir).is_none() {
return Ok(None);
}
let data = exe_dir.join(PORTABLE_DATA_DIR);
probe(&data)?;
removed?;
Ok(Some(data))
}
-70
View File
@@ -1,70 +0,0 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
-607
View File
@@ -1,607 +0,0 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
// Linux only, as the shared nightlies publish.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
// different names into the same replacement character and call them one folder.
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str();
match (platform.ignores_case(), value.to_str()) {
(true, Some(text)) => OsString::from(text.to_lowercase()),
_ => value.to_os_string(),
}
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// Every stable CADCraft data root of this platform, plus the install folders and the running
/// install ([`installation_boundary`]).
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
.collect::<Result<Vec<_>, _>>()?;
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
// here; the executable's own folder is fenced below.
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/CADCraft"),
library.join("Caches/CADCraft"),
library.join("Caches/ai.storyteller.cadcraft"),
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
// Support), beside the settings folder env.rs uses.
library.join("Application Support").join(EFRAME_APP_ID),
library.join("Preferences/CADCraft"),
library.join("Preferences/ai.storyteller.cadcraft.plist"),
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
home.join("Applications/CADCraft.app"),
PathBuf::from("/Applications/CADCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
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 {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
/// global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
let chosen = canonical_future(root)?;
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
// other value would redirect Nightly's settings folder, so it is refused.
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
if !configured.starts_with(&chosen) {
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
}
}
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
{
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
// other instance is the stable app's (or another app's), whose socket this profile must
// not inherit.
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
}
}
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
// private profile, including toward a stable portable directory not in our known roots.
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
/// bundle id differ on purpose, as they do for stable.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/cadcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("CADCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/cadcraft/autosave");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/cadcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
let storage = data.join(EFRAME_APP_ID);
std::fs::create_dir_all(&storage).unwrap();
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
for candidate in [storage.clone(), storage.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/CADCraft",
"Application Support/ai.storyteller.cadcraft",
"Caches/CADCraft",
"Caches/ai.storyteller.cadcraft",
"Preferences/CADCraft",
"Saved Application State/ai.storyteller.cadcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
// The bundle path and the Library fences fold case on macOS.
let cased = library.join("application support/cadcraft/nightly");
assert!(fixture.check(Platform::Mac, &cased).is_err());
}
#[test]
fn windows_fences_roaming_local_and_both_install_folders() {
let mut fixture = Fixture::new();
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
for stable in [
fixture.root.join("roaming/CADCraft"),
fixture.root.join("roaming/ai.storyteller.cadcraft"),
fixture.root.join("local/CADCraft"),
fixture.root.join("program files/ArtCraft/CADCraft"),
] {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
// Windows folder names ignore case.
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
}
#[test]
fn config_dir_and_flatpak_are_refused() {
let mut fixture = Fixture::new();
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
let private = fixture.root.join("nightly-config");
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
assert!(!private.exists());
fixture.env.remove("CADCRAFT_CONFIG_DIR");
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
assert!(!private.exists());
}
}
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
/// channel's data root; that one instance is accepted, and its profile stays inside it.
#[test]
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
let mut fixture = Fixture::new();
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
// Stable's Flatpak folder is still fenced even inside the nightly instance.
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
}
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
/// still a redirect.
#[test]
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
let mut fixture = Fixture::new();
let private = fixture.root.join("nightly-wrapper");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
let inside = private.join("nested");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
}
#[test]
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-unwritable");
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
assert!(!fixture.home().join(".config/cadcraft").exists());
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let fixture = Fixture::new();
let outside = fixture.root.join("outside");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err());
assert!(!probed.get());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}
+5 -10
View File
@@ -100,30 +100,25 @@ pub fn absolute(paths: &[PathBuf]) -> Option<Vec<String>> {
/// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false
/// when the launch asked for anything besides opening files, so it gets its own window.
/// `profile` is the Nightly profile root: its socket then lives in the profile, so a nightly launch
/// can never hand its files to a running stable CADCraft (and the reverse).
pub fn claim(files: &[String], may_hand_off: bool, profile: Option<&std::path::Path>) -> Claim {
pub fn claim(files: &[String], may_hand_off: bool) -> Claim {
#[cfg(windows)]
{
match socket_path(profile) {
match socket_path() {
Some(path) => claim_at(&path, files, may_hand_off),
None => Claim::Alone,
}
}
#[cfg(not(windows))]
{
let _ = (files, may_hand_off, profile);
let _ = (files, may_hand_off);
Claim::Alone
}
}
/// The socket in `%LOCALAPPDATA%\CADCraft`, or `<profile>\single-instance` for a Nightly launch.
/// The socket in `%LOCALAPPDATA%\CADCraft`.
#[cfg(windows)]
fn socket_path(profile: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
fn socket_path() -> Option<std::path::PathBuf> {
let name = socket_name(std::env::var("SESSIONNAME").ok().as_deref());
if let Some(root) = profile {
return Some(root.join("single-instance").join(name));
}
std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("CADCraft").join(name))
}
-28
View File
@@ -1,28 +0,0 @@
# App icons
The stable icon is `cadcraft-1024.png` (the padded master). The packaging scripts derive the other
sizes from it:
| File | Where it goes |
|---|---|
| `cadcraft.ico` | `cadcraft.exe` resources and the MSI shortcuts (Windows) |
| `cadcraft.icns` | `CADCraft.app/Contents/Resources` (macOS) |
| `cadcraft-256.png` | the window and About icon on Linux, and the AppImage/menu entry |
| `hicolor/<size>/apps/ai.storyteller.cadcraft.png` | the freedesktop icon theme, so docks and menus find the app by its id |
## Nightly
The Nightly channel has its own icon, so a nightly window, taskbar button and bundle are not
mistaken for the stable app. It is the same mark — foreground unchanged, no badge — on a deeper
background, derived from the stable 1024 master (never an upscale):
| File | Where it goes |
|---|---|
| `cadcraft-nightly-1024.png` | the master the `.icns` is generated from |
| `cadcraft-nightly.png` | the Linux nightly tar (`cadcraft-nightly.png` beside the executable) |
| `cadcraft-nightly.ico` | `cadcraft.exe` of a nightly build (`build.rs`) |
| `cadcraft-nightly.icns` | `CADCraft Nightly.app/Contents/Resources`, `CFBundleIconFile cadcraft-nightly` |
`nightly-provenance.json` records the exact transform (which pixels changed, and from which
colour), so the nightly icon can be regenerated or reviewed against the stable one. Regenerating
either set is a deliberate change: check the result at 16 px before replacing a file.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

-24
View File
@@ -1,24 +0,0 @@
{
"schema": "craft-nightly-icon-provenance/v1",
"app": "cadcraft",
"channel": "nightly-v1",
"source": {
"master": "assets/app-icon/cadcraft-1024.png",
"note": "The stable 1024 master, padded as its designer made it; the nightly files are derived from it, never upscaled from a smaller icon."
},
"transform": {
"summary": "The app mark (near-black strokes, cream highlights and their antialiasing) is copied unchanged; only the background square is deepened.",
"background": {
"from": "#14a3c7",
"to": "#0c657b",
"rule": "A pixel whose channel distance from the stable background is at most 180 is scaled by 0.62; fully transparent pixels and every other colour are left as they were."
}
},
"outputs": {
"cadcraft-nightly.png": "256 px PNG of the icon the Linux tar carries as cadcraft-nightly.png",
"cadcraft-nightly-1024.png": "the padded 1024 master the icns is generated from",
"cadcraft-nightly.ico": "16, 24, 32, 48, 64, 128 and 256 px PNG entries, the Windows executable and window icon",
"cadcraft-nightly.icns": "icp4 icp5 icp6 ic07 ic08 ic09 ic10 PNG entries for the macOS bundle (CFBundleIconFile cadcraft-nightly)"
},
"not_done_here": "No badge, crescent or N was added, and the stable cadcraft.png/.ico/.icns files are untouched."
}
-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
+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");
}
}
+3 -5
View File
@@ -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(),
}
}
@@ -627,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(),
-6
View File
@@ -191,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())
+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
+28 -75
View File
@@ -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)
}
@@ -292,72 +291,6 @@ fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -
})
}
/// 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.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
}
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 {
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(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() };
// 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,
}
}
/// A text that draws no glyph (empty, or only blanks and non-breaking spaces) takes no room.
fn blank(s: &str) -> bool {
s.replace("\\~", " ").chars().all(char::is_whitespace)
@@ -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,
@@ -489,7 +422,17 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
let mut b = Bounds2::EMPTY;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = contents(d, blk, depth, blocks, off_counts).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).
@@ -548,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();
-9
View File
@@ -111,8 +111,6 @@ pub struct Drawing {
pub mline_styles: Vec<MLineStyle>,
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>,
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.
@@ -160,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 {
@@ -208,7 +201,6 @@ impl Drawing {
mline_styles: vec![MLineStyle::default()],
blocks: BTreeMap::new(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
active_layout: None,
views: Vec::new(),
@@ -229,7 +221,6 @@ impl Drawing {
skipped_records: BTreeMap::new(),
portable_fonts: false,
rasters: Rasters::default(),
proxy_layers: Vec::new(),
}
}
+1 -15
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 {
-126
View File
@@ -520,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"));
@@ -779,114 +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");
}
-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>,
}
+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;
+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>,
-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();
+9 -149
View File
@@ -368,19 +368,6 @@ 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}")
@@ -705,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 {
@@ -756,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"
}
@@ -1058,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);
@@ -1151,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"
}
@@ -1389,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,
+10 -39
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"])
@@ -858,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,
@@ -899,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");
}
@@ -907,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())?;
@@ -958,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 {
@@ -974,7 +962,6 @@ impl InsertM {
})
.collect()
};
self.asked = 0;
self.name = Some(b.name.clone());
self.stage = InsStage::Point;
Ok(())
@@ -1064,7 +1051,7 @@ impl Interactive for InsertM {
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
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) }
@@ -1271,16 +1258,12 @@ impl Interactive for InsertM {
}
}
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.
@@ -1318,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;
+22 -72
View File
@@ -1,7 +1,7 @@
//! 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};
@@ -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).
@@ -117,11 +102,7 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
_ => 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
}
@@ -133,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"
@@ -153,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;
@@ -182,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
@@ -213,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(),
}
@@ -222,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();
@@ -232,19 +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(())
}
}
-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)),
_ => {}
}
}
+5 -3
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};
+22 -34
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,25 +96,21 @@ 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) => {
self.pts.push(p);
@@ -160,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();
+2 -3
View File
@@ -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)
}
+17 -185
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,11 +35,7 @@ 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"])
@@ -139,158 +135,28 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- 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
@@ -726,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()))
}
+4 -9
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};
@@ -382,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.
-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()
+4 -6
View File
@@ -253,16 +253,14 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = base_point(s, "grip.scale", p, &hs)?;
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
let f = base.dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
}
};
let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
apply(s, &hs, &m, bool_or(p, "copy", false))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+19 -48
View File
@@ -14,7 +14,7 @@ use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips;
use super::helpers::line;
use super::machines::number;
use super::modify::{at_elevation, scale_entities, transform_entities};
use super::modify::transform_entities;
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -220,7 +220,14 @@ impl GripEdit {
}
}
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -233,27 +240,6 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -300,20 +286,12 @@ impl GripEdit {
Ok(Step::Continue)
}
Input::Point(p) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
let m = self.matrix(p);
self.edit(s, p, m)
}
Input::Deferred(d) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -322,7 +300,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit_scale(s, f)
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -349,21 +327,14 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
+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");
}
}
+6 -63
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
}
@@ -262,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);
}
@@ -307,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));
@@ -780,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"));
+3 -7
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;
@@ -36,15 +35,12 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, 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,
};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{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"])
-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 {
+58 -101
View File
@@ -2,8 +2,7 @@ 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 ----------------
@@ -27,11 +26,12 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// ROTATE Reference: the reference angle (radians), once known.
/// ROTATE Reference: the reference angle (radians), once known. Its first point, and the
/// first of the two new-angle points, are kept in `ref_from`.
ref_angle: Option<f64>,
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
ref_points: bool,
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
/// SCALE Reference: first point of a reference length given by two points.
ref_from: Option<Vec2>,
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
@@ -126,47 +126,30 @@ impl SelectThen {
}
}
/// SCALE Reference: reference length (typed, or two points), then new length (typed, a point
/// measured from the base point, or two points after `Points`). The scale factor is new length /
/// reference length.
/// SCALE Reference: reference length (typed, or two points), then new length (typed, or a
/// point measured from the base point). The scale factor is new length / reference length.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
if matches!(&i, Input::Keyword(k) if k == "Copy") {
self.copy_mode = true;
s.echo("Scaling a copy of the selected objects.");
return Ok(Step::Continue);
}
let Some(r) = self.ref_len else {
match (self.ref_from, i) {
(None, Input::Point(p)) => self.ref_from = Some(p),
(None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?),
(None, Input::Enter) => self.ref_len = Some(1.0),
(Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
self.ref_from = None;
}
(_, Input::Enter) => return Ok(Step::Done),
_ => {}
}
return Ok(Step::Continue);
};
match (self.ref_points, self.ref_from, i) {
(false, _, Input::Keyword(k)) if k == "Points" => {
self.ref_points = true;
self.ref_from = None;
Ok(Step::Continue)
}
(false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(false, _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(true, None, Input::Point(p)) => {
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
(None, None, Input::Text(t)) => {
self.ref_len = Some(require_length(number(&t))?);
Ok(Step::Continue)
}
(None, None, Input::Enter) => {
self.ref_len = Some(1.0);
Ok(Step::Continue)
}
(None, Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
Ok(Step::Continue)
}
(Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(Some(r), _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -174,26 +157,6 @@ impl SelectThen {
}
}
/// The prompt while SCALE Reference collects its lengths.
fn scale_reference_prompt(&self) -> Prompt {
let base = self.pts.first().copied();
match (self.ref_len, self.ref_points, self.ref_from) {
(None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"),
(None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(),
(Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT),
}
}
/// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`.
fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> {
match (self.ref_len, self.ref_points, self.ref_from) {
(Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)),
(Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)),
_ => None,
}
}
/// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a
/// point measured from the base point, or two points after `Points`). The objects turn by the
/// new angle minus the reference angle.
@@ -285,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(_)
@@ -303,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> {
@@ -352,7 +314,11 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
return self.scale_reference_prompt();
return match (self.ref_len, self.ref_from) {
(Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base),
(None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"),
};
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -381,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)? {
@@ -399,7 +364,7 @@ impl Interactive for SelectThen {
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);
}
@@ -491,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);
@@ -500,15 +464,16 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
let m = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) {
Some(f) => Mat3::scale_about(base, f),
None if self.ref_len.is_some() => return Vec::new(),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -519,51 +484,43 @@ 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(rubber_from, c));
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;
}
let base = self.pts.first().copied()?;
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
let matrix = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
_ => return None,
};
let mut extra = vec![line(rubber_from, c)];
let mut extra = vec![line(base, c)];
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);
}
}
+1 -26
View File
@@ -1,4 +1,3 @@
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec3;
use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets};
@@ -10,29 +9,6 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy:
edit_entities(s, hs, copy, |e| e.kind.transform(m))
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
/// Keep this in the command layer: a reflection of an entire inserted block still transforms
/// all of its contents, rather than applying the policy for individually selected hatches.
pub(super) fn mirror_kind(k: &mut EntityKind, m: &Mat3) {
let angles = match k {
EntityKind::Hatch(h) => Some((h.angle, h.gradient.as_ref().map(|g| g.angle))),
_ => None,
};
k.transform(m);
if let (EntityKind::Hatch(h), Some((angle, gradient_angle))) = (k, angles) {
h.angle = angle;
if let (Some(g), Some(angle)) = (&mut h.gradient, gradient_angle) {
g.angle = angle;
}
}
}
/// Reflect selected entities with the command policy that retains individual hatch fill directions.
pub(super) fn mirror_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| mirror_kind(&mut e.kind, m))
}
/// Scale `hs` by `f` about `base` in 3D, as AutoCAD 2024's SCALE does: about the base point's XY,
/// and every height of the objects about its Z, their thickness too.
pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result<Vec<Handle>> {
@@ -175,7 +151,6 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
/// Validate MIRROR parameters and apply the reflection, optionally replacing the source entities.
pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let a = point_req("mirror", p, "p1")?;
@@ -184,6 +159,6 @@ pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("mirror", "mirror line points coincide"));
}
let erase_src = bool_or(p, "erase", false);
let r = mirror_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
let r = transform_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+30 -83
View File
@@ -18,51 +18,28 @@ pub(crate) struct Edges<'a> {
}
/// All primitives of the cutting edges (excluding `exclude`).
pub(crate) fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result<Vec<Segment>> {
edge_segments_over(s, edges, exclude, &Overlay::new())
}
/// Objects as a run of trims would have left them, without changing the drawing: for each object
/// of the drawing it names, the pieces in its place, each with its handle (the first keeps the
/// object's, as [`replace_with_pieces`] does; none: the object is gone). TRIM's Fence and
/// Crossing preview works a whole run out this way.
pub(crate) type Overlay = std::collections::HashMap<Handle, Vec<(Handle, EntityKind)>>;
/// [`edge_segments`] with the objects `overlay` names in their pieces' place.
pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, overlay: &Overlay) -> Result<Vec<Segment>> {
fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result<Vec<Segment>> {
let d = s.doc()?;
let space = s.space();
let store = d.space(&space).ok_or(EngineError::NoDocument)?;
let mut out = Vec::new();
let mut add = |kind: &EntityKind| {
if edges.implied
&& let Some(segs) = implied_edge(kind)
{
out.extend(segs);
return;
}
for p in kind.prims() {
out.extend(prim_to_segments(&p));
}
};
// An object is an edge when it is one of `edges.only` (all of them: `None`). A trim leaves
// its first piece under the object's handle and the others under new ones, so only the first
// stays one of the picked edges, as in a run of trims on the drawing itself.
let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h));
for e in store.iter() {
if !d.is_visible(e) {
if e.handle == exclude || !d.is_visible(e) {
continue;
}
match overlay.get(&e.handle) {
Some(pieces) => {
for (h, k) in pieces {
if *h != exclude && is_edge(h) {
add(k);
}
}
}
None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind),
None => {}
if let Some(es) = edges.only
&& !es.contains(&e.handle)
{
continue;
}
if edges.implied
&& let Some(segs) = implied_edge(&e.kind)
{
out.extend(segs);
continue;
}
for p in e.kind.prims() {
out.extend(prim_to_segments(&p));
}
}
Ok(out)
@@ -160,36 +137,19 @@ pub(crate) fn json_pick_error(s: &Session, h: Handle, pick: Vec2, edges: Edges,
EngineError::Other(message.into())
}
/// Trim `h` at the piece containing `pick`. Returns the handles that replace it.
/// Trim `h` at the piece containing `pick`. Returns what it became: its pieces, `h` first
/// ([`replace_with_pieces`]).
pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<Vec<Handle>> {
let cut = edge_segments(s, edges, h)?;
match trimmed(s, h, pick, edges, &cut)? {
Some(pieces) => replace_with_pieces(s, h, pieces),
None => Ok(vec![h]),
}
}
/// What a trim of `h` at `pick` against `cut` (its cutting edges, [`edge_segments`]) leaves of
/// it, without changing the drawing: the pieces that stay, in [`replace_with_pieces`]'s order
/// (none: the object goes). `None`: the pick is on one of a polyline's own cuts, which trims
/// nothing. TRIM's preview and the trim itself both come from here, so they can't disagree.
pub(crate) fn trimmed(s: &Session, h: Handle, pick: Vec2, edges: Edges, cut: &[Segment]) -> Result<Option<Vec<EntityKind>>> {
if crate::cmd::curves::is_locked(s, h) {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| EngineError::Other("no such object".into()))?;
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let cut = edge_segments(s, edges, h)?;
// A polyline that is one of the edges (picked, or with every object in either mode) cuts
// itself too.
let itself = edges.only.is_none_or(|o| o.contains(&h));
trim_kind(&e.kind, pick, itself, cut)
}
/// [`trimmed`] for an object of shape `kind` (not on a locked layer); `itself`: it is one of the
/// cutting edges, so a polyline cuts itself too.
pub(crate) fn trim_kind(kind: &EntityKind, pick: Vec2, itself: bool, cut: &[Segment]) -> Result<Option<Vec<EntityKind>>> {
let pieces: Vec<EntityKind> = match kind {
let pieces: Vec<EntityKind> = match &e.kind {
EntityKind::Line(l) => {
let ln = Line::new(l.a.xy(), l.b.xy());
let mut ts: Vec<f64> = cut
@@ -269,13 +229,13 @@ pub(crate) fn trim_kind(kind: &EntityKind, pick: Vec2, itself: bool, cut: &[Segm
}
keep.into_iter().collect()
}
EntityKind::LwPolyline(p) => match trim_polyline(p, cut, pick, itself)? {
EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? {
Some(pieces) => pieces,
None => return Ok(None),
None => return Ok(vec![h]),
},
k => crate::cmd::modify2::trim_other(k, cut, pick)?,
k => crate::cmd::modify2::trim_other(k, &cut, pick)?,
};
Ok(Some(pieces))
replace_with_pieces(s, h, pieces)
}
/// Put `pieces` in place of object `h` as AutoCAD 2024's BREAK and TRIM leave them: the first
@@ -604,26 +564,12 @@ fn extend_arc_segment(ga: &Arc, end: Vec2, sweep: f64, cut: &[Segment]) -> Optio
/// Extend the end of `h` nearest `pick` to the nearest boundary edge.
pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<()> {
let cut = edge_segments(s, edges, h)?;
let new_kind = extended(s, h, pick, &cut)?;
s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?;
Ok(())
}
/// The object `h` as an extend at `pick` to `cut` (its boundary edges, [`edge_segments`]) leaves
/// it, without changing the drawing. EXTEND's preview and the extend itself both come from here.
pub(crate) fn extended(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> Result<EntityKind> {
if crate::cmd::curves::is_locked(s, h) {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| EngineError::Other("no such object".into()))?;
extend_kind(&e.kind, pick, cut)
}
/// [`extended`] for an object of shape `kind` (not on a locked layer).
pub(crate) fn extend_kind(kind: &EntityKind, pick: Vec2, cut: &[Segment]) -> Result<EntityKind> {
let new_kind = match kind {
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let cut = edge_segments(s, edges, h)?;
let new_kind = match &e.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let from_b = pick.dist(b) < pick.dist(a);
@@ -671,7 +617,7 @@ pub(crate) fn extend_kind(kind: &EntityKind, pick: Vec2, cut: &[Segment]) -> Res
let none = || EngineError::Other("Object does not intersect an edge.".into());
if let Some((ga, _)) = cadcraft_geom::bulge_to_arc(prev, end, bulge) {
// An arc end segment runs on round its circle, as an arc does.
let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), cut).ok_or_else(none)?;
let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), &cut).ok_or_else(none)?;
if let Some(v) = vs.get_mut(i_end) {
v.p = np;
}
@@ -694,7 +640,8 @@ pub(crate) fn extend_kind(kind: &EntityKind, pick: Vec2, cut: &[Segment]) -> Res
// Width, elevation and linetype generation stay as they were.
EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices: vs, ..p.clone() })
}
k => crate::cmd::modify2::extend_other(k, cut, pick)?,
k => crate::cmd::modify2::extend_other(k, &cut, pick)?,
};
Ok(new_kind)
s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?;
Ok(())
}
-4
View File
@@ -4,10 +4,8 @@
mod breaks;
mod cells;
pub(crate) mod formula;
mod paste;
pub(crate) use cells::{recalc, tablestyle_cell_style};
pub use paste::{MAX_PASTE_CELLS, is_tsv_table, parse_tsv};
use cadcraft_doc::{EntityKind, Handle, Table, TableCell};
use cadcraft_geom::Vec2;
@@ -37,8 +35,6 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("table.deletecol", "Delete Column", run_delete_col).params("{handle, col}"),
CommandSpec::new("table.merge", "Merge Cells", run_merge).params("{handle, row, col, rows, cols}"),
CommandSpec::new("table.unmerge", "Unmerge Cells", run_unmerge).params("{handle, row, col}"),
CommandSpec::new("pastetable", "Paste Table", paste::run_pastetable)
.params("{tsv: string, at?: [x,y], text_height?: number} → {handle, rows, cols}"),
]
.into_iter()
.chain(cells::specs())
-304
View File
@@ -1,304 +0,0 @@
//! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`.
use cadcraft_doc::{EntityKind, Table, TableCell, TableStyle};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use super::{MAX_COLS, MAX_ROWS, style_of};
use crate::cmd::helpers::{line, v3};
use crate::cmd::{bad, point_param, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// Maximum UTF-8 byte length accepted for a pasted TSV payload (16 MiB).
pub const MAX_TSV_BYTES: usize = 16 << 20;
/// Maximum total grid cells created from pasted TSV (`rows * cols`).
pub const MAX_PASTE_CELLS: usize = 20_000;
/// Above this many cells, interactive cursor preview draws the outer table box instead of laying
/// out every cell each frame.
const PREVIEW_CELL_LIMIT: usize = 200;
/// Parse RFC-4180 tab-delimited text into a uniform rectangular grid of cells via [`craft_csv`].
///
/// Supports quoted fields (`"..."`), escaped doubled quotes (`""`), and multiline cells inside
/// quotes (`\n` / `\r\n` normalized to `\n`). Enforces [`MAX_TSV_BYTES`], [`MAX_ROWS`],
/// [`MAX_COLS`], and the total cell budget [`MAX_PASTE_CELLS`]. Requires at least 2 cells
/// (`rows * cols >= 2`) and at least one non-whitespace cell.
pub fn parse_tsv(text: &str) -> std::result::Result<Vec<Vec<String>>, String> {
if text.len() > MAX_TSV_BYTES {
return Err(format!("pasted table exceeds {} MB limit", MAX_TSV_BYTES >> 20));
}
let clean = text.strip_prefix('\u{feff}').unwrap_or(text);
let mut rows: Vec<Vec<String>> = Vec::new();
let mut max_cols = 0usize;
let mut err: Option<String> = None;
craft_csv::parse_records(clean, '\t', '"', MAX_COLS + 1, |mut rec| {
if rec.len() > MAX_COLS {
err = Some(format!("pasted table exceeds {MAX_COLS} columns"));
return false;
}
if rows.len() >= MAX_ROWS {
err = Some(format!("pasted table exceeds {MAX_ROWS} rows"));
return false;
}
max_cols = max_cols.max(rec.len());
if (rows.len() + 1).saturating_mul(max_cols) > MAX_PASTE_CELLS {
err = Some(format!("pasted table exceeds {MAX_PASTE_CELLS} cell limit"));
return false;
}
for cell in &mut rec {
if cell.contains('\r') {
*cell = cell.replace("\r\n", "\n").replace('\r', "\n");
}
}
rows.push(rec);
true
});
if let Some(msg) = err {
return Err(msg);
}
let total = rows.len().saturating_mul(max_cols);
if rows.is_empty() || max_cols == 0 || total < 2 {
return Err("pasted text must contain at least 2 table cells".into());
}
if rows.iter().all(|r| r.iter().all(|c| c.trim().is_empty())) {
return Err("pasted table contains no text".into());
}
for r in &mut rows {
r.resize(max_cols, String::new());
}
Ok(rows)
}
/// Whether `text` looks like non-DXF tab-delimited spreadsheet data containing at least 2 cells.
pub fn is_tsv_table(text: &str) -> bool {
if text.is_empty() || text.len() > MAX_TSV_BYTES || !text.contains('\t') {
return false;
}
let mut lines = text.lines().map(str::trim);
if lines.next() == Some("0") && lines.next() == Some("SECTION") {
return false;
}
parse_tsv(text).is_ok()
}
/// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly.
fn build_table(st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> Table {
let cols = data.first().map_or(1, Vec::len).max(1);
let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 });
let margin = if st.text_height.is_finite() && st.text_height > 0.0 { st.margin * (th / st.text_height) } else { th * 0.5 };
let mut col_chars = vec![1usize; cols];
let mut row_heights = Vec::with_capacity(data.len());
let mut cells = Vec::with_capacity(data.len());
for row in data {
let mut max_lines = 1usize;
let mut table_row = Vec::with_capacity(cols);
for (c, raw) in row.iter().enumerate() {
let line_count = raw.split('\n').count().clamp(1, 50);
max_lines = max_lines.max(line_count);
let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60);
if let Some(slot) = col_chars.get_mut(c) {
*slot = (*slot).max(max_chars);
}
table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() });
}
row_heights.push(th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin);
cells.push(table_row);
}
let min_col_w = (th * 4.0 + 2.0 * margin).max(th * 5.0);
let col_widths: Vec<f64> = col_chars.into_iter().map(|chars| (0.75 * th * chars as f64 + 2.0 * margin + 0.5 * th).max(min_col_w)).collect();
Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() }
}
fn parse_text_height(p: &Value) -> Result<Option<f64>> {
let val = match p.get("text_height").or_else(|| p.get("textHeight")) {
None | Some(Value::Null) => return Ok(None),
Some(v) => v,
};
val.as_f64()
.filter(|h| h.is_finite() && *h > 0.0 && *h <= 1e9)
.map(Some)
.ok_or_else(|| bad("pastetable", "`text_height` must be a finite positive number"))
}
fn parse_at(p: &Value) -> Result<Vec2> {
match p.get("at") {
None | Some(Value::Null) => Ok(Vec2::ZERO),
Some(_) => point_param(p, "at").ok_or_else(|| bad("pastetable", "`at` must be a point [x, y]")),
}
}
pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result<Value> {
let tsv = str_param(p, "tsv").ok_or_else(|| bad("pastetable", "`tsv` string is required"))?;
let at = parse_at(p)?;
let th = parse_text_height(p)?;
let data = parse_tsv(tsv).map_err(|m| bad("pastetable", m))?;
let rows = data.len();
let cols = data.first().map_or(0, Vec::len);
let st = style_of(s);
let table = build_table(&st, at, &data, th);
let h = s.add_entity(EntityKind::Table(table))?;
s.set_selection(vec![h]);
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
}
struct PasteTableM {
table: Table,
rows: usize,
cols: usize,
}
impl Interactive for PasteTableM {
fn name(&self) -> &'static str {
"PASTETABLE"
}
fn begin(&mut self, _s: &mut Session) -> Result<Step> {
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Specify insertion point", Accept::POINT)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Cancel | Input::Enter => Ok(Step::Cancel),
Input::Point(p) => {
let mut t = self.table.clone();
t.insert = v3(p);
let h = s.add_entity(EntityKind::Table(t))?;
s.set_selection(vec![h]);
s.echo(format!("Pasted {}x{} table.", self.rows, self.cols));
Ok(Step::Done)
}
_ => Ok(Step::Continue),
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
if self.rows.saturating_mul(self.cols) <= PREVIEW_CELL_LIMIT {
let mut t = self.table.clone();
t.insert = v3(c);
return vec![EntityKind::Table(t)];
}
let w: f64 = self.table.col_widths.iter().sum();
let h: f64 = self.table.row_heights.iter().sum();
let a = c;
let b = c + Vec2::new(w, 0.0);
let d = c + Vec2::new(w, -h);
let e = c + Vec2::new(0.0, -h);
vec![line(a, b), line(b, d), line(d, e), line(e, a)]
}
}
impl Session {
/// Start interactive placement of a native `ACAD_TABLE` parsed from tab-delimited clipboard
/// text (`tsv`), asking for an insertion point through the standard interactive command path.
pub fn start_paste_table(&mut self, tsv: &str, text_height: Option<f64>) -> Result<()> {
if let Some(h) = text_height
&& !(h.is_finite() && h > 0.0 && h <= 1e9)
{
return Err(bad("pastetable", "`text_height` must be a finite positive number"));
}
let data = parse_tsv(tsv).map_err(|m| bad("pastetable", m))?;
let rows = data.len();
let cols = data.first().map_or(0, Vec::len);
let st = style_of(self);
let table = build_table(&st, Vec2::ZERO, &data, text_height);
let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled);
self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_rfc4180_tsv_with_multiline_and_quoted_cells() {
let input = "\u{feff}Item\tDescription\tQty\r\n\"Bolt M8\"\t\"Line 1\r\nLine 2\"\t10\r\n\"Say \"\"Hi\"\"\"\tPlain\t20\r\n";
let got = parse_tsv(input).unwrap();
assert_eq!(got, vec![vec!["Item", "Description", "Qty"], vec!["Bolt M8", "Line 1\nLine 2", "10"], vec!["Say \"Hi\"", "Plain", "20"],]);
}
#[test]
fn rejects_invalid_single_cell_empty_dxf_and_over_budget_inputs() {
assert!(parse_tsv("SingleCell").is_err());
assert!(parse_tsv("\"quoted\ttab\"").is_err());
assert!(parse_tsv("\t\n\t\n").is_err());
assert!(!is_tsv_table("SingleCell"));
assert!(!is_tsv_table("\"quoted\ttab\""));
assert!(!is_tsv_table("just plain text\non two lines"));
assert!(!is_tsv_table("0\nSECTION\n2\tTAB"));
assert!(is_tsv_table("A\tB"));
assert!(is_tsv_table("A\t\n1\t"));
// Column budget > MAX_COLS rejected during parse.
let too_wide = vec!["x"; MAX_COLS + 1].join("\t");
let err = parse_tsv(&too_wide).unwrap_err();
assert!(err.contains("columns"), "{err}");
// Cell budget > MAX_PASTE_CELLS rejected during parse.
let wide_row = vec!["x"; MAX_COLS].join("\t");
let over_rows = (MAX_PASTE_CELLS / MAX_COLS) + 2;
let oversized = vec![wide_row; over_rows].join("\n");
let err = parse_tsv(&oversized).unwrap_err();
assert!(err.contains("cell limit") || err.contains("rows"), "{err}");
}
#[test]
fn pads_ragged_rows_to_uniform_columns() {
let got = parse_tsv("A\tB\tC\n1\n2\t3\n").unwrap();
assert_eq!(got, vec![vec!["A", "B", "C"], vec!["1", "", ""], vec!["2", "3", ""]]);
}
#[test]
fn pastetable_command_creates_scaled_multiline_table() {
let mut s = Session::new();
let res =
s.execute("pastetable", &json!({ "tsv": "ColA\tLong Header Value\n\"Row 1\nRow 2\"\t42", "at": [10, 20], "text_height": 2.0 })).unwrap();
assert_eq!(res["rows"], 2);
assert_eq!(res["cols"], 2);
let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
let EntityKind::Table(t) = &e.kind else { panic!("expected table") };
assert_eq!(t.insert.xy(), Vec2::new(10.0, 20.0));
assert_eq!(t.text_height, 2.0);
assert!(!t.title && !t.header);
assert_eq!(t.cells[1][0].text, "Row 1\\PRow 2");
assert!(t.row_heights[1] > t.row_heights[0], "multiline row gets extra height");
assert!(t.col_widths[1] > t.col_widths[0], "wider column gets extra width");
}
#[test]
fn interactive_start_paste_table_places_on_point_and_supports_undo() {
let mut s = Session::new();
s.start_paste_table("A\tB\n1\t2\n", None).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("pastetable"));
assert!(!s.preview(Vec2::new(5.0, 5.0)).is_empty());
s.input(Input::Point(Vec2::new(100.0, 50.0))).unwrap();
assert!(s.running.is_none());
assert_eq!(s.doc().unwrap().model.len(), 1);
let e = s.doc().unwrap().model.iter().next().unwrap();
let EntityKind::Table(t) = &e.kind else { panic!("expected table") };
assert_eq!(t.insert.xy(), Vec2::new(100.0, 50.0));
assert_eq!(t.cells.len(), 2);
s.undo().unwrap();
assert!(s.doc().unwrap().model.is_empty());
}
#[test]
fn start_paste_table_uses_standard_command_lifecycle() {
let mut empty = Session::empty();
assert!(matches!(empty.start_paste_table("A\tB\n1\t2\n", None), Err(crate::EngineError::Disabled(_, _))));
let mut s = Session::new();
let before_started = s.commands_started;
s.start_paste_table("A\tB\n1\t2\n", None).unwrap();
assert_eq!(s.commands_started, before_started + 1);
assert_eq!(s.last_command.as_deref(), Some("pastetable"));
}
}
+6 -260
View File
@@ -2,28 +2,20 @@
//! (TRIMEXTENDMODE), cutting/boundary edges, Fence, Crossing, Project (PROJMODE), Edge (EDGEMODE),
//! eRase and Undo. The geometry of one trim or extend is in modify.rs.
use std::cell::RefCell;
use std::sync::Arc;
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
use cadcraft_geom::{Bounds2, Line, Segment, Vec2, line_line};
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Bounds2, Line, Vec2, line_line};
use serde_json::{Value, json};
use super::curves::KW;
use super::helpers::{line, lwpoly, rect_vertices};
use super::modify::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
};
use super::modify::{CUT_ONCE, Edges, extend, json_pick_error, trim};
use super::{bad, point_param, points_param};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
/// Most fence points the JSON form takes.
const MAX_FENCE: usize = 10_000;
/// Most picks a Fence or Crossing preview works out ([`TrimM`]'s `highlight_all`). Each pick
/// gathers the cutting edges over the whole drawing again, on every cursor move, so a fence across
/// a crowded drawing shows no part highlight at all rather than slow the drawing area down; the
/// fence itself still trims everything it crosses.
pub const PREVIEW_MAX_PICKS: usize = 64;
/// TRIMEXTENDMODE: 1 (default) Quick, 0 Standard.
fn quick_mode(s: &Session) -> bool {
@@ -65,13 +57,6 @@ fn apply(s: &mut Session, h: Handle, at: Vec2, extending: bool, edges: Edges, qu
/// Trim (or extend) every object the fence `pts` crosses, at each crossing (extend: at the first).
/// Returns how many trims or extends were made.
fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bool) -> Result<usize> {
let (work, tol) = fence_work(s, pts)?;
run_picks(s, work, extending, edges, quick, tol)
}
/// What a fence through `pts` trims or extends: each object it crosses with its crossings, in
/// fence order, and the tolerance they were found to.
fn fence_work(s: &Session, pts: &[Vec2]) -> Result<(Vec<(Handle, Vec<Vec2>)>, f64)> {
let space = s.space();
let d = s.doc()?;
let fb = Bounds2::from_points(pts.iter().copied());
@@ -96,7 +81,7 @@ fn fence_work(s: &Session, pts: &[Vec2]) -> Result<(Vec<(Handle, Vec<Vec2>)>, f6
}
work.push((h, xs));
}
Ok((work, tol))
run_picks(s, work, extending, edges, quick, tol)
}
/// How far along a segment from its end a crossing window's pick is kept: past the 5e-7 within
@@ -107,13 +92,6 @@ const OFF_VERTEX: f64 = 1e-6;
/// Trim (or extend) every object a crossing window from `a` to `b` touches, picked at its point
/// in the window nearest the first corner `a`.
fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, quick: bool) -> Result<usize> {
let (work, tol) = crossing_work(s, a, b)?;
run_picks(s, work, extending, edges, quick, tol)
}
/// What a crossing window from `a` to `b` trims or extends: each object it touches with its pick
/// point, and the tolerance they were found to.
fn crossing_work(s: &Session, a: Vec2, b: Vec2) -> Result<(Vec<(Handle, Vec<Vec2>)>, f64)> {
let space = s.space();
let d = s.doc()?;
let bx = Bounds2::new(a, b);
@@ -152,82 +130,7 @@ fn crossing_work(s: &Session, a: Vec2, b: Vec2) -> Result<(Vec<(Handle, Vec<Vec2
work.push((h, vec![p]));
}
}
Ok((work, tol))
}
/// What [`run_picks`] would change, worked out without changing the drawing: for each trim, the
/// piece it removes (a whole object Quick mode erases), and for each extend the stretch it adds,
/// with the handle of the object it belongs to. Each object is trimmed at its picks in turn, as
/// `run_picks` does, against edges that include what the run has already made of other objects
/// ([`Overlay`]), so the preview of a fence or a crossing window is what it will do. `px`: the
/// tolerance the changes are drawn to.
fn picks_preview(
s: &Session,
work: &[(Handle, Vec<Vec2>)],
extending: bool,
edges: Edges,
quick: bool,
tol: f64,
px: f64,
) -> Vec<(Handle, EntityKind)> {
let Ok(d) = s.doc() else { return Vec::new() };
let mut overlay = Overlay::new();
let mut out = Vec::new();
// Handles for the pieces a trim makes, apart from any in the drawing.
let mut next = u64::MAX;
let mut fresh = || {
next -= 1;
Handle(next)
};
for (h, picks) in work {
let Some(orig) = d.entity(*h) else { continue };
if crate::cmd::curves::is_locked(s, *h) {
continue;
}
let entity = |handle: Handle, kind: &EntityKind| Entity { handle, common: orig.common.clone(), kind: kind.clone() };
let mut live: Vec<(Handle, EntityKind)> = vec![(*h, orig.kind.clone())];
for x in picks {
let target = live
.iter()
.enumerate()
.map(|(i, (ph, k))| (i, crate::select::entity_distance(d, &entity(*ph, k), *x, tol)))
.filter(|(_, dist)| *dist <= 3.0 * tol)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i);
let Some(i) = target else { continue };
let Some((ph, piece)) = live.get(i).cloned() else { continue };
overlay.insert(*h, live.clone());
let Ok(cut) = edge_segments_over(s, edges, ph, &overlay) else { continue };
if extending {
if let Ok(grown) = extend_kind(&piece, *x, &cut) {
out.extend(uncovered(d, &entity(ph, &grown), std::slice::from_ref(&piece), px).into_iter().map(|k| (*h, k)));
if let Some(slot) = live.get_mut(i) {
slot.1 = grown;
}
}
break;
}
let itself = edges.only.is_none_or(|o| o.contains(&ph));
match trim_kind(&piece, *x, itself, &cut) {
Ok(Some(kept)) => {
out.extend(uncovered(d, &entity(ph, &piece), &kept, px).into_iter().map(|k| (*h, k)));
live.remove(i);
let mut kept = kept.into_iter();
if let Some(first) = kept.next() {
live.insert(i, (ph, first));
}
live.extend(kept.map(|k| (fresh(), k)));
}
Err(err) if quick && misses_edges(&err) => {
out.push((*h, piece));
live.remove(i);
}
Ok(None) | Err(_) => {}
}
}
overlay.insert(*h, live);
}
out
run_picks(s, work, extending, edges, quick, tol)
}
/// Trim (or extend) each object at its pick points. A trim leaves the object in pieces, so later
@@ -361,54 +264,11 @@ pub(crate) struct TrimM {
stage: Stage,
/// The drawing before each trim, extend or erase, for Undo.
undo: Vec<Arc<Drawing>>,
/// The edges of the object under the cursor, for the rollover highlight ([`CutCache`]).
cut: RefCell<Option<CutCache>>,
}
/// The cutting or boundary edges of the object under the cursor, kept while the drawing, the
/// object and the modes stay the same. The rollover highlight works a trim out at every cursor
/// move, and in Quick mode the edges are every object in the drawing: gathering them once keeps
/// moving the cursor along one object cheap.
struct CutCache {
doc: usize,
h: Handle,
quick: bool,
implied: bool,
cut: Vec<Segment>,
}
impl TrimM {
pub(crate) fn new(extend: bool) -> Self {
TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new(), cut: RefCell::new(None) }
}
/// What a click on `h` at `cursor` changes: the piece a trim removes (the whole object when a
/// Quick-mode trim erases it), or the stretch an extend adds. `None` when the click would
/// change nothing or can't be worked out; the rollover highlight then shows the whole object.
fn change(&self, s: &Session, h: Handle, cursor: Vec2) -> Option<Vec<EntityKind>> {
let (quick, implied) = (quick_mode(s), edge_mode(s));
let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize;
let mut cache = self.cut.borrow_mut();
if !cache.as_ref().is_some_and(|c| c.doc == doc && c.h == h && c.quick == quick && c.implied == implied) {
let cut = edge_segments(s, self.edges(quick, implied), h).ok()?;
*cache = Some(CutCache { doc, h, quick, implied, cut });
}
let cut = &cache.as_ref()?.cut;
let d = s.doc().ok()?;
let e = d.entity(h)?;
// Half a pixel: finer than the eye can tell apart, coarse enough to stay quick.
let tol = (s.pixel_size() / 2.0).max(1e-9);
let part = if self.extend {
let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() };
uncovered(d, &grown, std::slice::from_ref(&e.kind), tol)
} else {
match trimmed(s, h, cursor, self.edges(quick, implied), cut) {
Ok(Some(kept)) => uncovered(d, e, &kept, tol),
Ok(None) => return None,
Err(err) if quick && misses_edges(&err) => vec![e.kind.clone()],
Err(_) => return None,
}
};
(!part.is_empty()).then_some(part)
TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new() }
}
fn edges(&self, quick: bool, implied: bool) -> Edges<'_> {
Edges { only: self.edges.as_deref(), implied: !quick && implied }
@@ -547,8 +407,6 @@ impl Interactive for TrimM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
// The edges may change (picked again, Undo): gather them afresh for the highlight.
self.cut.take();
let quick = quick_mode(s);
let implied = edge_mode(s);
let extending = self.extend;
@@ -697,30 +555,6 @@ impl Interactive for TrimM {
},
}
}
fn highlight(&self, s: &Session, h: Handle, cursor: Vec2) -> Option<Vec<EntityKind>> {
if self.stage != Stage::Pick {
return None;
}
self.change(s, h, cursor)
}
fn highlight_all(&self, s: &Session, cursor: Vec2) -> Option<Vec<(Handle, EntityKind)>> {
let (quick, implied) = (quick_mode(s), edge_mode(s));
let found = match &self.stage {
Stage::Fence(pts) if !pts.is_empty() => {
let pts: Vec<Vec2> = pts.iter().copied().chain(std::iter::once(cursor)).collect();
fence_work(s, &pts)
}
Stage::QuickFence(a) => fence_work(s, &[*a, cursor]),
Stage::Crossing(Some(a)) => crossing_work(s, *a, cursor),
_ => return None,
};
let (work, tol) = found.ok()?;
if work.iter().map(|(_, picks)| picks.len()).sum::<usize>() > PREVIEW_MAX_PICKS {
return None;
}
let px = (s.pixel_size() / 2.0).max(1e-9);
Some(picks_preview(s, &work, self.extend, self.edges(quick, implied), quick, tol, px))
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
match &self.stage {
Stage::Fence(pts) if !pts.is_empty() => pts
@@ -737,91 +571,3 @@ impl Interactive for TrimM {
}
}
}
/// The stretches of `e`'s outline that none of `others` runs along, as polylines flattened to
/// `tol`: what a trim takes away (the object less the pieces it keeps), or what an extend adds
/// (the object as extended less the object as it was). Each segment of the outline is first split
/// where one of `others` ends on it, so a stretch is either all on them or all off them.
fn uncovered(d: &Drawing, e: &Entity, others: &[EntityKind], tol: f64) -> Vec<EntityKind> {
// Two flattenings of one curve, each within `tol` of it, lie within twice that of each other.
let near = 3.0 * tol;
let theirs: Vec<Vec<Vec2>> =
chains(others.iter().flat_map(|k| crate::select::hit_polylines(d, &Entity { kind: k.clone(), ..e.clone() }, tol)).collect());
let ends: Vec<Vec2> = theirs.iter().flat_map(|pl| [pl.first().copied(), pl.last().copied()]).flatten().collect();
// Their segments, each with its box and the ends of the piece it belongs to, worked out once:
// the test below runs for every stretch of the outline.
let spans: Vec<(Line, Bounds2, Vec2, Vec2)> = theirs
.iter()
.flat_map(|pl| {
let ends = (pl.first().copied(), pl.last().copied());
pl.windows(2).filter_map(move |w| {
let (a, b) = (*w.first()?, *w.get(1)?);
Some((Line::new(a, b), Bounds2::from_points([a, b]), ends.0?, ends.1?))
})
})
.collect();
// On them: near one of them, and not only near one of their ends (a point just past where a
// piece ends is near that end, yet off the piece). A segment whose box is farther than `near`
// from the point can't be that near it, so it is passed over without working out its distance.
let on_theirs = |p: Vec2| {
spans.iter().any(|(l, b, first, last)| {
if p.x < b.min.x - near || p.x > b.max.x + near || p.y < b.min.y - near || p.y > b.max.y + near {
return false;
}
let c = l.closest(p);
c.dist(p) <= near && !(c.near(*first, 1e-12 * (1.0 + c.len())) || c.near(*last, 1e-12 * (1.0 + c.len())))
})
};
let mut out = Vec::new();
let mut run: Vec<Vec2> = Vec::new();
let mut flush = |run: &mut Vec<Vec2>| {
if run.len() >= 2 {
out.push(lwpoly(std::mem::take(run).into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false));
}
run.clear();
};
for pl in chains(crate::select::hit_polylines(d, e, tol)) {
for w in pl.windows(2) {
let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue };
let ab = Line::new(a, b);
let len = ab.len();
if len <= 0.0 {
continue;
}
let mut ts: Vec<f64> = ends.iter().filter(|p| ab.closest(**p).dist(**p) <= near).map(|p| ab.param_of(*p).clamp(0.0, 1.0)).collect();
ts.extend([0.0, 1.0]);
ts.sort_by(f64::total_cmp);
ts.dedup_by(|x, y| (*x - *y).abs() * len <= 1e-9 * (1.0 + a.len()));
for t in ts.windows(2) {
let (Some(&t0), Some(&t1)) = (t.first(), t.get(1)) else { continue };
let (p, q) = (ab.at(t0), ab.at(t1));
if on_theirs(ab.at((t0 + t1) / 2.0)) {
flush(&mut run);
} else {
if run.last().is_none_or(|l| !l.near(p, 1e-12 * (1.0 + p.len()))) {
flush(&mut run);
run.push(p);
}
run.push(q);
}
}
}
flush(&mut run);
}
out
}
/// `pls` with each one that starts where the one before it ends joined onto it: a curve's
/// flattening may come as many short pieces, one after the other.
fn chains(pls: Vec<Vec<Vec2>>) -> Vec<Vec<Vec2>> {
let mut out: Vec<Vec<Vec2>> = Vec::new();
for pl in pls {
match (out.last_mut(), pl.first()) {
(Some(last), Some(&first)) if last.last().is_some_and(|l| l.near(first, 1e-12 * (1.0 + first.len()))) => {
last.extend(pl.into_iter().skip(1));
}
_ => out.push(pl),
}
}
out
}
@@ -41,7 +41,6 @@ pub const FILES: &[&str] = &[
"options",
"pagesetup",
"pdfbook",
"pdfimport",
"plot",
"plotstyle",
"plottermanager",
@@ -101,7 +100,6 @@ pub const NO_FILES: &[&str] = &[
"pasteclip",
"pasteblock",
"pasteorig",
"pastetable",
"erase.selection",
"selectall",
"ai_deselect",
@@ -280,7 +278,6 @@ pub const NO_FILES: &[&str] = &[
"stretch",
"offset",
"trim",
"extrim",
"extend",
"fillet",
"chamfer",
+1 -4
View File
@@ -170,16 +170,13 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
if index == 0 {
return Some(translated(kind, delta));
}
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
let a = i.attribs.get_mut(k)?;
let a = i.attribs.get_mut(index - 1)?;
let ip = a.text.insert.xy() + delta;
set_xy(&mut a.text.insert, ip);
if let Some(al) = &mut a.text.align_pt {
let q = al.xy() + delta;
set_xy(al, q);
}
// A multiline attribute is drawn from its multiline text: it moves too.
a.transform_multiline(&Mat3::translate(delta));
}
EntityKind::Dimension(d) => {
match index {
-69
View File
@@ -92,33 +92,6 @@ impl Interactive for Guarded {
Vec::new()
})
}
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn highlight(&self, s: &Session, h: cadcraft_doc::Handle, cursor: Vec2) -> Option<Vec<EntityKind>> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.highlight(s, h, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn highlight_all(&self, s: &Session, cursor: Vec2) -> Option<Vec<(cadcraft_doc::Handle, EntityKind)>> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.highlight_all(s, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
if self.broken.get().is_some() {
return None;
@@ -155,48 +128,6 @@ impl Interactive for Guarded {
None
})
}
fn attribute_entry(&self) -> Option<crate::prompt::AttribEntry> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.attribute_entry())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
None
})
}
fn array_live(&self) -> Option<crate::ArrayLive> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.array_live())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
None
})
}
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
if let Some(m) = self.broken.get() {
return Err(EngineError::Internal(self.inner.name().to_ascii_lowercase(), m.into()));
}
catch_unwind(AssertUnwindSafe(|| self.inner.set_array_live(s, v))).unwrap_or_else(|p| Err(self.internal(&*p)))
}
fn array_set_main(&mut self) -> bool {
if self.broken.get().is_some() {
return false;
}
catch_unwind(AssertUnwindSafe(|| self.inner.array_set_main())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
false
})
}
fn array_pick_center(&mut self) -> bool {
if self.broken.get().is_some() {
return false;
}
catch_unwind(AssertUnwindSafe(|| self.inner.array_pick_center())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
false
})
}
}
#[cfg(test)]
+1 -30
View File
@@ -7,7 +7,6 @@
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod array_live;
pub mod assoc;
#[cfg(not(target_arch = "wasm32"))]
@@ -49,7 +48,6 @@ use cadcraft_geom::{Bounds2, Vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub use array_live::{ArrayLive, ArrayLiveKind};
pub use cadcraft_doc as doc;
pub use cadcraft_fonts as fonts;
pub use cadcraft_geom as geom;
@@ -57,7 +55,7 @@ pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
mod doc_state;
mod error;
@@ -82,18 +80,6 @@ pub fn build_version() -> &'static str {
&VERSION
}
/// Who started the command running now ([`Session::start`]): a person at the command line or
/// from a menu, toolbar or palette, or a program (a script, an AutoLISP `(command …)`, a JSON
/// call). The origin is fixed when the command starts and kept for its whole life: only a
/// person's INSERT opens the Edit Attributes dialog, since nobody is there to answer one that a
/// program opened, and nobody has seen it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Origin {
#[default]
Person,
Program,
}
/// The editor session: open drawings, settings, the running command and the command log.
pub struct Session {
pub docs: Vec<DocState>,
@@ -105,23 +91,11 @@ pub struct Session {
pub running: Option<Running>,
/// How many commands were started, nested transparent ones left out.
pub commands_started: u64,
/// How many inputs the session was given ([`Session::input`]): answers to a running command or
/// to a LISP routine waiting for one, and the Enter that repeats the last command.
pub inputs: u64,
/// Who started the command running now ([`Origin`]): a command keeps the origin it started
/// with, so a scripted or LISP-started INSERT never opens a dialog, even when the user then
/// answers its prompts by hand.
command_origin: Origin,
/// The last command that ended by itself, not cancelled: its number in `commands_started`, and
/// whether it took new handles (it added to the drawing, and nothing took that back).
pub last_finished: Option<(u64, bool)>,
/// A script is running ([`Session::script`]); a SCRIPT command inside it is refused.
in_script: bool,
/// The LISP evaluator is running ([`Session::lisp_drive`]): what a routine feeds the command
/// line — the command it starts, or a `'command` token it types into a running one — is the
/// program's input, so [`Session::start`] records [`Origin::Program`] for it. Saved and
/// restored around each slice of a routine, so nesting keeps the outer answer.
program_input: bool,
/// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it;
/// it resumes when that command ends. One level, as in AutoCAD.
pub suspended: Option<Running>,
@@ -218,11 +192,8 @@ impl Session {
settings: Settings::default(),
running: None,
commands_started: 0,
inputs: 0,
command_origin: Origin::Person,
last_finished: None,
in_script: false,
program_input: false,
suspended: None,
log: Vec::new(),
last_command: None,
-6
View File
@@ -363,17 +363,11 @@ impl Session {
let mut env = self.lisp_env_take();
value::set_string_budget(run.string_bytes, self.lisp.limits.string_bytes);
value::set_cell_limit(self.lisp.limits.cells.max(run.cells_at_start));
// What the routine feeds the command line is the program's input: the command it
// starts, even when another one is running and the token reaches
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
// in it included, so a person's later command keeps its own origin.
let program_input = std::mem::replace(&mut self.program_input, true);
let outcome = {
let machine = &mut run.machine;
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| machine.run(&mut ctx, SLICE)))
};
self.program_input = program_input;
run.string_bytes = value::string_bytes_used();
let outcome = match outcome {
Ok(o) => o,
+3 -5
View File
@@ -70,9 +70,7 @@ fn items(p: &PickSet) -> Vec<Handle> {
/// selection set picks objects (a name, alone or with a point as `entsel` gives it, also answers
/// a prompt picking one object: [`Session::input_object`]), and `pause` waits for the user. A
/// command not finished by the arguments stays active for the next `command` call. No
/// arguments: cancel the active command. Whatever it feeds is the program's input
/// ([`crate::Origin::Program`]): the command it starts here, and the one a `'command` token
/// starts while another command runs, never open a dialog.
/// arguments: cancel the active command.
pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
if a.is_empty() {
if ctx.s.running.is_some() {
@@ -93,7 +91,7 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
}
Value::Str(s) => {
let r = if ctx.s.running.is_none() {
if s.trim().is_empty() { Ok(()) } else { ctx.s.start_programmatic(s) }
if s.trim().is_empty() { Ok(()) } else { ctx.s.start(s) }
} else if s.is_empty() {
ctx.s.input(Input::Enter)
} else {
@@ -815,7 +813,7 @@ fn interactive_ssget(ctx: &mut Ctx<'_>, filter: Option<Value>) -> Result<Flow, L
if ctx.s.running.is_some() {
return Ok(Flow::Value(Value::Nil));
}
if let Err(e) = ctx.s.start_programmatic("select") {
if let Err(e) = ctx.s.start("select") {
return Err(LispError::new(e.to_string()));
}
let f = super::eval::lookup(ctx.env, &super::value::Sym::new("SSGET"));
-91
View File
@@ -103,10 +103,6 @@ pub struct Prompt {
/// the routine writes, so it cannot be read for the word "Select" (#1598).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub picks_one: bool,
/// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
/// angle box, with the command's live value ([`Interactive::live_value`]).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub angle: bool,
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
/// block's name is that block, not a keyword read from its Latin keys.
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -158,11 +154,6 @@ impl Prompt {
self.grip = Some(g);
self
}
/// An angle about the base is asked for (the `angle` field).
pub fn angle(mut self) -> Self {
self.angle = true;
self
}
/// The visual chooser the UI can show (the `picker` field).
pub fn picker(mut self, p: Picker) -> Self {
self.picker = Some(p);
@@ -335,24 +326,6 @@ pub trait Interactive: Send {
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
Vec::new()
}
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
/// shows angles): what Dynamic Input shows in its box before anything is typed.
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
None
}
/// What the rollover highlight shows of the object `h` under the cursor, when it is not the
/// whole object (TRIM: the piece a click there removes; EXTEND: what it adds). `None`: the
/// whole object, as for any other command.
fn highlight(&self, _s: &Session, _h: cadcraft_doc::Handle, _cursor: Vec2) -> Option<Vec<EntityKind>> {
None
}
/// What the running command will change wherever the cursor is, highlighted in place of the
/// object under it (TRIM's Fence and Crossing: every piece the fence or the window will
/// remove), each with the handle of the object it is part of. `None`: nothing of the kind,
/// and the object under the cursor is highlighted as [`Interactive::highlight`] says.
fn highlight_all(&self, _s: &Session, _cursor: Vec2) -> Option<Vec<(cadcraft_doc::Handle, EntityKind)>> {
None
}
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
@@ -375,28 +348,6 @@ pub trait Interactive: Send {
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
None
}
/// The attribute values the command waits for, all at once, when the UI should ask for them
/// in the Edit Attributes dialog (INSERT with ATTDIA 1). Typed answers still work.
fn attribute_entry(&self) -> Option<AttribEntry> {
None
}
/// The live parameters of the running array (ARRAYRECT / ARRAYPOLAR), for the array window.
fn array_live(&self) -> Option<crate::ArrayLive> {
None
}
/// Replace the running array's live parameters, as the array window's fields change them.
fn set_array_live(&mut self, _s: &mut Session, _v: &crate::ArrayLive) -> Result<()> {
Err(crate::EngineError::Other("this command has no live array parameters".into()))
}
/// Put the command back at its Main option loop (the state eXit/Enter finishes from).
/// False when the command cannot commit yet (e.g. the polar centre is still unspecified).
fn array_set_main(&mut self) -> bool {
false
}
/// Ask the next canvas point to be the polar centre. False when the command has no centre.
fn array_pick_center(&mut self) -> bool {
false
}
}
/// See [`Interactive::display_only`]: the only things drawn in the current view while a command
@@ -438,48 +389,6 @@ pub enum EditorKind {
Dimension { measured: String },
}
/// See [`Interactive::attribute_entry`]: the block being inserted and the attributes asked for,
/// in order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AttribEntry {
pub block: String,
pub rows: Vec<AttribAsk>,
/// The drawing the command runs in ([`crate::DocState::uid`]) and its number in
/// [`Session::commands_started`], stamped by [`Session::attribute_entry`]: a dialog draft
/// belongs to one command, so a command started afterwards never takes it.
pub drawing: u64,
pub command: u64,
}
/// One attribute an INSERT asks for: its tag, prompt and default value; the value of a Verify
/// one is asked again once every value is in.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AttribAsk {
pub tag: String,
pub prompt: String,
pub default: String,
pub verify: bool,
}
impl AttribEntry {
/// An entry as the command builds it, before [`Session::attribute_entry`] stamps the drawing
/// and command number it belongs to.
pub(crate) fn idle(block: String, rows: Vec<AttribAsk>) -> Self {
AttribEntry { block, rows, drawing: 0, command: 0 }
}
/// The answers that give the attributes `values` (one per row, in order; a missing one is
/// the default) when typed in turn: every value, then each Verify attribute's again, as
/// INSERT asks them once the dialog has shown the values.
pub fn answers(&self, values: &[String]) -> Vec<String> {
let value = |i: usize| values.get(i).cloned().unwrap_or_else(|| self.rows.get(i).map(|r| r.default.clone()).unwrap_or_default());
let mut out: Vec<String> = (0..self.rows.len()).map(value).collect();
let verify: Vec<String> = self.rows.iter().enumerate().filter(|(_, r)| r.verify).map(|(i, _)| value(i)).collect();
out.extend(verify);
out
}
}
/// See [`Interactive::drag`].
#[derive(Clone, Debug)]
pub struct Drag {
+12 -630
View File
@@ -6,64 +6,26 @@ use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
use crate::spatial::{self, SpatialIndex};
use crate::{Accept, Prompt};
/// A dimension kept as read whose graphics are a reference to its `*D` block (#3438).
fn draws_a_block(e: &Entity) -> bool {
matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))))
}
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
if matches!(e.kind, EntityKind::Insert(_)) {
let list = insert_geometry(d, e, tol);
return list
.prims
.iter()
.flat_map(|p| match p.kind {
cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask => {
list.points(p).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect()
}
cadcraft_render::Kind::Infinite { ray } => match list.points(p) {
[base, dir] => {
let far = 1e9;
vec![vec![if ray { *base } else { *base - *dir * far }, *base + *dir * far]]
}
_ => Vec::new(),
},
// An image's points are its unclipped corners: it is hit on the outline of what
// it shows, so a clipped-away part doesn't pick the reference.
cadcraft_render::Kind::Image { index } => match list.images.get(index as usize) {
Some(img) if img.clips.is_empty() => {
let [a, b, c, d] = img.corners();
vec![vec![a, b, c, d, a]]
}
Some(img) => shown_image_tris(img).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect(),
None => Vec::new(),
},
_ => vec![list.points(p).to_vec()],
})
.collect();
}
match &e.kind {
EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::AttDef(_)
| EntityKind::Table(_)
| EntityKind::Tolerance(_)
| EntityKind::MLeader(_)
| EntityKind::Image(_)
| EntityKind::Unknown(_)
if !matches!(e.kind, EntityKind::Unknown(_)) || draws_a_block(e) =>
{
// Text-like objects are hit inside their box; a dimension kept as read that draws its
// block, like a dimension.
| EntityKind::Image(_) => {
// Text-like objects are hit inside their box.
let b = entity_bounds(d, e, 0);
if b.is_empty() {
return Vec::new();
}
let c = b.corners();
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) {
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) {
let list = cadcraft_render::build_entities(
d,
std::iter::once(e),
@@ -122,44 +84,6 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
}
}
fn insert_geometry(d: &Drawing, e: &Entity, tol: f64) -> cadcraft_render::DisplayList {
cadcraft_render::build_entities(d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() })
}
/// The part of an image its clips leave showing, as triangles (three points each); empty when a
/// clip has no outline to cut with.
fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec<Vec2> {
let [a, b, c, d] = img.corners();
let mut tris = vec![a, b, c, a, c, d];
for outline in &img.clips {
let Some(clip) = cadcraft_render::clip::PolyClip::new(outline) else { return Vec::new() };
tris = clip.clip_triangles(&tris);
if tris.is_empty() {
break;
}
}
tris
}
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool {
let list = insert_geometry(d, e, tol);
list.prims.iter().any(|p| {
if let cadcraft_render::Kind::Image { index } = p.kind {
let Some(img) = list.images.get(index as usize) else { return false };
return !cadcraft_render::clip::clip_triangles(&shown_image_tris(img), bx).is_empty();
}
if !matches!(p.kind, cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask) {
return false;
}
list.points(p).as_chunks::<3>().0.iter().any(|t| {
let triangle = [t[0], t[1], t[2]];
bx.corners().iter().any(|q| point_in_polygon(&triangle, *q))
|| triangle.iter().any(|q| bx.contains(*q))
|| (0..3).any(|i| seg_hits_box(triangle[i], triangle[(i + 1) % 3], bx))
})
})
}
fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
if pts.len() == 1 {
return pts.first().map(|q| q.dist(p)).unwrap_or(f64::INFINITY);
@@ -173,7 +97,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_))
|| matches!(e.kind, EntityKind::Tolerance(_));
if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) {
if (filled && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, p) {
best = 0.0;
}
// A solid hatch fills its loops with odd parity under its island style, as it is drawn, not
@@ -261,125 +185,10 @@ pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
/// Entities to test, in the order to test them, each with its bounds when already known.
pub(crate) type Cands<'a> = Box<dyn Iterator<Item = (&'a Entity, Option<Bounds2>)> + 'a>;
/// Whether an MTEXT's contents draw nothing (empty, or only spaces and `\~`): it has no glyph
/// strokes, and the document's bounds for it are empty so it stays out of the drawing extents.
/// Called for every MTEXT when the spatial index is built, so it does not allocate.
fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool {
t.contents.split(r"\~").all(|s| s.chars().all(char::is_whitespace))
}
/// The frame a blank MTEXT is picked in (#2810), for a top-level MTEXT and for a multileader's
/// MTEXT content: its insertion point, rotation and the box before turning (`x0, x1, y0, y1`
/// about the insertion point): its width (the text height when it has none) by its text height,
/// placed by its attachment point, at the size it draws at the current annotation scale (the
/// shared `anno_scaled`, which also moves a multileader's text about its landing). `None` for any
/// other entity, a multileader without text content, a blank MTEXT without a usable size or
/// position, or an annotative one the current annotation scale hides.
fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
// Kind and blankness first: scaling clones the entity, so only blank text pays for it.
let text = match &e.kind {
EntityKind::MText(t) => t,
EntityKind::MLeader(m) => m.text.as_ref()?,
_ => return None,
};
if !is_blank_mtext(text) {
return None;
}
let f = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => 1.0,
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
cadcraft_doc::AnnoDraw::Hidden => return None,
};
let scaled;
let e = if f != 1.0 {
scaled = cadcraft_doc::anno_scaled(e, f);
&scaled
} else {
e
};
let t = match &e.kind {
EntityKind::MText(t) => t,
EntityKind::MLeader(m) => m.text.as_ref()?,
_ => return None,
};
if !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() {
return None;
}
let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height };
let h = t.height;
let insert = t.insert.xy();
if !w.is_finite() || !h.is_finite() || !insert.is_finite() {
return None;
}
let dx = match t.attach {
2 | 5 | 8 => -w / 2.0,
3 | 6 | 9 => -w,
_ => 0.0,
};
let top = match t.attach {
4..=6 => h / 2.0,
7..=9 => h,
_ => 0.0,
};
// A top-level MTEXT that matches the layout orientation is drawn upright (the renderer draws
// non-blank text that way), so its blank frame is too; a multileader keeps its text's stored rotation.
let rotation = if matches!(e.kind, EntityKind::MText(_)) && e.common.matches_layout_orientation() { 0.0 } else { t.rotation };
Some((insert, rotation, [dx, dx + w, top - h, top]))
}
/// The box around a blank MTEXT's turned frame (a top-level MTEXT or a multileader's MTEXT
/// content), for the spatial index and windows (a crossing window may catch a little extra near a
/// corner, as it does for other text).
fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option<Bounds2> {
let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?;
let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)];
Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot))))
}
/// Whether `p` is on a blank MTEXT or a multileader's blank MTEXT content: inside its box turned
/// with the text, not the larger box around it.
fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool {
let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(d, e) else { return false };
let q = (p - o).rotate(-rot);
q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1
}
/// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content.
/// Use the same bounds for a scan and for the spatial index.
pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 {
match blank_mtext_box(d, e) {
Some(frame) => drawn.union(&frame),
None => drawn,
}
}
/// The insertion points snap's INS mode offers for a blank MTEXT or multileader (the stored
/// points); empty for any other entity.
fn blank_snap_points(e: &Entity) -> Vec<Vec2> {
// select.rs blank_snap_points must offer the same points as snap.rs's INS arms.
match &e.kind {
EntityKind::MText(t) if is_blank_mtext(t) => vec![t.insert.xy()],
EntityKind::MLeader(m) if m.text.as_ref().is_some_and(is_blank_mtext) => {
m.text.iter().map(|t| t.insert.xy()).chain(m.block.iter().map(|b| b.insert.xy())).collect()
}
_ => Vec::new(),
}
}
/// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn
/// geometry (expanded by `aperture`) misses `probe`, and no insertion point INS would offer (text
/// or block content) is a candidate: one counts only when `ins` is on and it is within `aperture`
/// of `cursor`, the distance snap accepts a candidate by (a corner of the square probe is not).
/// Such an entity is for picking and selection, not a snap candidate.
pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor: Vec2, aperture: f64, ins: bool) -> bool {
let points = blank_snap_points(e);
!points.is_empty() && !(ins && points.iter().any(|p| p.dist(cursor) <= aperture)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe)
}
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0)))
known.unwrap_or_else(|| entity_bounds(d, e, 0))
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -535,15 +344,8 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
pl.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| seg_hits_box(*a, *b, bx)))
}
});
// A crossing box inside a text bounding rectangle selects the text.
if hit
|| (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_)))
|| (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol))
{
return true;
}
// Likewise inside a blank MTEXT's frame (a multileader's too), where picking also selects it.
if blank_mtext_box(d, e).is_some_and(|frame| frame.contains_box(bx)) {
// A crossing box entirely inside a text/block bounding rectangle also selects it.
if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) {
return true;
}
// SOLID/TRACE are filled polygons. A crossing window wholly within the
@@ -755,7 +557,7 @@ impl SelectMode {
#[cfg(test)]
mod tests {
use super::*;
use cadcraft_doc::{Common, Image, Raster, RayLine};
use cadcraft_doc::{Common, RayLine};
use cadcraft_geom::Vec3;
fn fence_hits(kind: EntityKind, fence: [(f64, f64); 2]) -> usize {
@@ -798,272 +600,6 @@ mod tests {
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
}
fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind {
EntityKind::MText(cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
height: 2.5,
width: 10.0,
attach,
rotation,
style: "Standard".into(),
contents: contents.into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
})
}
/// A blank MTEXT has no strokes and empty drawn bounds, but it is still an object: a click
/// inside its width x height box picks it, and a click outside does not (#2810).
#[test]
fn a_blank_mtext_is_picked_inside_its_box() {
let blank = |c: &str| matches!(mtext_at(c, 1, 0.0), EntityKind::MText(t) if is_blank_mtext(&t));
assert!(!blank(r"a\~"));
assert!(blank(r"\~ \~"));
for contents in ["", " ", r"\~ "] {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(contents, 1, 0.0)).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.1);
assert_eq!(at(5.0, -1.0), Some(h), "{contents:?}");
assert_eq!(at(0.5, -2.0), Some(h), "{contents:?}");
assert_eq!(at(5.0, 3.0), None, "above the box, {contents:?}");
assert_eq!(at(12.0, -1.0), None, "right of the box, {contents:?}");
assert_eq!(pick_all(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), vec![h]);
let w = Bounds2::new(Vec2::new(4.0, -2.0), Vec2::new(6.0, -1.0));
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing {contents:?}");
}
}
#[test]
fn a_blank_mleader_text_is_picked_inside_its_box() {
for contents in [" ", ""] {
let mut s = crate::Session::new();
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
// The command omits the text object for an empty string. Preserve the box here to
// exercise a stored empty MTEXT, which can still exist in an imported MLEADER.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
m.text.as_mut().unwrap().contents = contents.into();
})
.unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let t = m.text.as_ref().unwrap();
let p = t.insert.xy() + Vec2::new(t.height / 2.0, -t.height / 4.0);
let aperture = t.height / 100.0;
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "{contents:?}");
let d = s.doc_mut().unwrap();
for i in 0..spatial::MIN_INDEXED {
let y = 100.0 + i as f64;
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
d.add(&Space::Model, Common::default(), line).unwrap();
}
assert!(spatial::index(d, &Space::Model).is_some());
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "indexed {contents:?}");
}
}
#[test]
fn a_pick_away_from_normal_mleader_text_and_lines_misses() {
let mut s = crate::Session::new();
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
assert_eq!(pick(s.doc().unwrap(), &Space::Model, Vec2::new(2.0, 8.0), 0.05), None);
// Give the text a wide box: a click inside it, right of the glyphs and off the leader, is
// still a miss, since only blank text is picked by its frame.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
m.text.as_mut().unwrap().width = 5.0;
})
.unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let t = m.text.as_ref().unwrap();
let p = t.insert.xy() + Vec2::new(t.width * 0.8, 0.0);
assert_eq!(pick(d, &Space::Model, p, 0.02), None, "right of the glyphs, inside the frame");
assert_eq!(pick(d, &Space::Model, t.insert.xy() + Vec2::new(0.3, 0.0), 0.02), Some(h), "on the glyphs");
}
/// Only blank MTEXT has a frame: an annotative non-blank MTEXT and an annotative LINE have none
/// (and the kind and blankness are decided before any annotation scaling).
#[test]
fn only_blank_mtext_has_a_frame_even_when_annotative() {
let mut d = Drawing::new_metric();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
let common = || Common { anno_scales: vec![half.clone()], ..Common::default() };
let text = d.add(&Space::Model, common(), mtext_at("Visible", 1, 0.0)).unwrap();
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) });
let line = d.add(&Space::Model, common(), line).unwrap();
let blank = d.add(&Space::Model, common(), mtext_at(" ", 1, 0.0)).unwrap();
for (h, framed) in [(text, false), (line, false), (blank, true)] {
let e = d.entity(h).unwrap();
assert_eq!(blank_mtext_frame(&d, e).is_some(), framed);
}
}
/// A multileader whose text is blank, with the text 6 units right of the landing, 4 wide and
/// 2 high, attached top-left.
fn blank_mleader(s: &mut crate::Session) -> Handle {
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
let landing = m.landing;
let t = m.text.as_mut().unwrap();
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
})
.unwrap();
h
}
/// A crossing window wholly inside a blank multileader text's box selects it, as a click does.
#[test]
fn a_crossing_window_inside_a_blank_mleader_text_box_selects_it() {
let mut s = crate::Session::new();
let h = blank_mleader(&mut s);
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let o = m.text.as_ref().unwrap().insert.xy();
let inside = Bounds2::new(o + Vec2::new(1.0, -1.5), o + Vec2::new(2.0, -0.5));
assert_eq!(select_window(d, &Space::Model, inside, true), vec![h]);
let outside = Bounds2::new(o + Vec2::new(5.0, -1.5), o + Vec2::new(6.0, -0.5));
assert!(select_window(d, &Space::Model, outside, true).is_empty());
}
/// An annotative multileader's blank text is picked where it draws at the current annotation
/// scale: its size and its offset from the landing both scale.
#[test]
fn an_annotative_blank_mleader_text_is_picked_at_its_drawn_offset_and_size() {
let mut s = crate::Session::new();
let h = blank_mleader(&mut s);
let d = s.doc_mut().unwrap();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
d.modify_entity(h, |e| e.common.anno_scales = vec![half]).unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let l = m.landing.xy();
// At 1:2 the box is 8 x 4 from the landing + (12, 0) (top-left): x 12..20, y -4..0.
let at = |x: f64, y: f64| pick(d, &Space::Model, l + Vec2::new(x, y), 0.02);
assert_eq!(at(16.0, -1.0), Some(h), "inside the scaled box, outside the unscaled one");
assert_eq!(at(19.5, -3.5), Some(h), "far corner of the scaled box");
assert_eq!(at(8.0, -1.0), None, "inside the unscaled box, outside the scaled one");
assert_eq!(at(22.0, -1.0), None, "right of the scaled box");
}
/// The box follows the attachment point and the rotation, and a width of 0 falls back to the
/// text height.
#[test]
fn a_blank_mtext_box_follows_attachment_and_rotation() {
let mut d = Drawing::new_metric();
// Middle-centre: the box spans x -5..5, y -1.25..1.25.
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, 0.0)).unwrap();
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
assert_eq!(at(&d, -4.0, 1.0), Some(h));
assert_eq!(at(&d, 4.0, -1.0), Some(h));
assert_eq!(at(&d, 4.0, 2.0), None);
// Turned a quarter turn about the insertion point: the box spans x -1.25..1.25, y -5..5.
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, std::f64::consts::FRAC_PI_2)).unwrap();
assert_eq!(at(&d, 1.0, 4.0), Some(h));
assert_eq!(at(&d, 4.0, 1.0), None);
// No width: as wide as the text is high.
let mut d = Drawing::new_metric();
let EntityKind::MText(mut t) = mtext_at("", 1, 0.0) else { panic!("mtext") };
t.width = 0.0;
let h = d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
assert_eq!(at(&d, 2.0, -1.0), Some(h));
assert_eq!(at(&d, 5.0, -1.0), None);
}
/// A top-level MTEXT that matches the layout orientation is drawn upright, ignoring its stored
/// rotation, so its frame is the unturned one (the renderer and the extents do the same).
#[test]
fn rotated_blank_mtext_matching_layout_orientation_is_picked_in_its_unrotated_frame() {
let mut d = Drawing::new_metric();
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() };
let h = d.add(&Space::Model, common, mtext_at(" ", 1, std::f64::consts::FRAC_PI_2)).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
// Unrotated frame x 0..10, y -2.5..0; the rotated one would be x 0..2.5, y 0..10.
assert_eq!(at(5.0, -1.0), Some(h), "inside the unrotated frame");
assert_eq!(at(1.0, 5.0), None, "inside only the rotated frame");
}
/// A turned blank MTEXT is hit in its turned box, not in the axis-aligned box around it (whose
/// empty corners lie off the text).
#[test]
fn a_turned_blank_mtext_is_picked_in_its_turned_box() {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 1, 30f64.to_radians())).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
// Local (5, -1.25), the centre of the box.
assert_eq!(at(4.955, 1.418), Some(h));
// Inside the box around the turned one, but local (2.87, 2.96) is above the text.
assert_eq!(at(1.0, 4.0), None);
}
/// An annotative blank MTEXT is picked in the box it draws at the current annotation scale,
/// and not at all while that scale hides it.
#[test]
fn an_annotative_blank_mtext_is_picked_at_its_drawn_size() {
let mut d = Drawing::new_metric();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
let common = Common { anno_scales: vec![half], ..Common::default() };
// Middle-centre at 1:2: twice the size, x -10..10, y -2.5..2.5.
let h = d.add(&Space::Model, common, mtext_at(" ", 5, 0.0)).unwrap();
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
assert_eq!(at(&d, 8.0, 2.0), Some(h), "inside the scaled box");
assert_eq!(at(&d, 11.0, 0.0), None, "outside the scaled box");
let w = Bounds2::new(Vec2::new(7.0, 1.0), Vec2::new(9.0, 2.0));
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing the scaled box");
// At 1:1 with only supported scales shown, the object is hidden: nothing to pick.
d.header.set_str("CANNOSCALE", "1:1");
d.header.set_i64("ANNOALLVISIBLE", 0);
assert_eq!(at(&d, 0.0, 0.0), None, "hidden");
let w = Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(1.0, 1.0));
assert!(select_window(&d, &Space::Model, w, true).is_empty(), "hidden, crossing");
}
/// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate.
#[test]
fn a_blank_mtext_is_picked_in_an_indexed_drawing() {
let mut d = Drawing::new_metric();
for i in 0..(crate::spatial::MIN_INDEXED + 10) {
let y = 100.0 + i as f64;
let l = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
d.add(&Space::Model, Common::default(), l).unwrap();
}
let h = d.add(&Space::Model, Common::default(), mtext_at("", 1, 0.0)).unwrap();
assert!(spatial::index(&d, &Space::Model).is_some());
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), Some(h));
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, 3.0), 0.1), None);
}
/// Text with words is still picked by its drawn box only.
#[test]
fn a_click_far_from_a_normal_mtext_misses() {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at("AB", 1, 0.0)).unwrap();
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, -1.0), 0.1), Some(h));
assert_eq!(pick(&d, &Space::Model, Vec2::new(8.0, -1.0), 0.1), None);
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, 5.0), 0.1), None);
}
/// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in
/// the middle of the frame, or on a frame without both corners, does not.
#[test]
@@ -1116,8 +652,8 @@ mod tests {
let e = d.entity(h).unwrap();
let drawn = cadcraft_render::build_entities(&d, std::iter::once(e.as_ref()), &cadcraft_render::Options { text: false, ..Default::default() });
assert!(drawn.prims.len() > 10_000, "the pattern draws {} dashes", drawn.prims.len());
// Hit testing uses the line without laying out every dash.
assert_eq!(hit_polylines(&d, e, 0.01).len(), 1);
// The line, and the block's bounding rectangle.
assert_eq!(hit_polylines(&d, e, 0.01).len(), 2);
}
/// A dashed line in a block is hit across its gaps, as one outside a block is.
@@ -1132,126 +668,6 @@ mod tests {
let gap = end + (start - end) * 0.5;
assert_eq!(pick(&d, &Space::Model, gap, end.dist(start) / 8.0), Some(h));
}
#[test]
fn crossing_a_transformed_block_requires_its_drawn_geometry() {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("two lines");
for y in [0.0, 5.0] {
block.entities.push(Entity::new(
Handle(10 + y as u64),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }),
));
}
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert {
block: "two lines".into(),
insert: Vec3::new(30.0, 40.0, 0.0),
scale: Vec3::new(2.0, 2.0, 1.0),
rotation: std::f64::consts::FRAC_PI_2,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let bx = |a, b| Bounds2::new(a, b);
let empty = bx(Vec2::new(24.0, 48.0), Vec2::new(26.0, 52.0));
let crossed = bx(Vec2::new(19.0, 48.0), Vec2::new(21.0, 52.0));
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
assert_eq!(select_window(&d, &Space::Model, crossed, true), vec![h]);
assert!(select_window(&d, &Space::Model, crossed, false).is_empty());
assert_eq!(pick(&d, &Space::Model, Vec2::new(25.0, 40.0), 0.1), None);
}
#[test]
fn crossing_a_block_fill_uses_the_filled_shape() {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("filled triangle");
let a = Vec3::new(0.0, 0.0, 0.0);
let b = Vec3::new(10.0, 0.0, 0.0);
let c = Vec3::new(0.0, 10.0, 0.0);
block.entities.push(Entity::new(Handle(10), EntityKind::Solid(cadcraft_doc::Solid { corners: [a, b, c, c] })));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert {
block: "filled triangle".into(),
insert: Vec3::new(0.0, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let empty = Bounds2::new(Vec2::new(7.0, 7.0), Vec2::new(8.0, 8.0));
let filled = Bounds2::new(Vec2::new(2.0, 2.0), Vec2::new(3.0, 3.0));
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
assert_eq!(select_window(&d, &Space::Model, filled, true), vec![h]);
}
#[test]
fn crossing_a_block_ray_and_xline_uses_their_direction() {
for (kind, behind) in [(true, false), (false, true)] {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("infinite");
let line = RayLine { base: Vec3::new(100.0, 100.0, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) };
block.entities.push(Entity::new(Handle(10), if kind { EntityKind::Ray(line) } else { EntityKind::XLine(line) }));
block
.entities
.push(Entity::new(Handle(11), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(200.0, 0.0, 0.0) })));
block.entities.push(Entity::new(
Handle(12),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 0.0, 0.0), b: Vec3::new(200.0, 200.0, 0.0) }),
));
block.entities.push(Entity::new(
Handle(13),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 200.0, 0.0), b: Vec3::new(0.0, 200.0, 0.0) }),
));
block
.entities
.push(Entity::new(Handle(14), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 200.0, 0.0), b: Vec3::new(0.0, 0.0, 0.0) })));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert { block: "infinite".into(), ..Default::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let ahead = Bounds2::new(Vec2::new(149.0, 99.0), Vec2::new(151.0, 101.0));
let back = Bounds2::new(Vec2::new(49.0, 99.0), Vec2::new(51.0, 101.0));
assert_eq!(select_window(&d, &Space::Model, ahead, true), vec![h]);
assert_eq!(select_window(&d, &Space::Model, back, true).contains(&h), behind);
}
}
#[test]
fn crossing_a_block_image_respects_its_clip() {
let mut d = Drawing::new_metric();
d.rasters.insert("map.png", std::sync::Arc::new(Raster::new(2, 2, vec![255; 16]).unwrap()));
let mut block = cadcraft_doc::Block::new("picture");
block.entities.push(Entity::new(
Handle(10),
EntityKind::Image(Image {
insert: Vec3::ZERO,
u: Vec3::new(5.0, 0.0, 0.0),
v: Vec3::new(0.0, 5.0, 0.0),
size: Vec2::new(2.0, 2.0),
path: "map.png".into(),
clipping: true,
clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(0.5, 1.5)],
..Default::default()
}),
));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let h = d
.add(&Space::Model, Common::default(), EntityKind::Insert(cadcraft_doc::Insert { block: "picture".into(), ..Default::default() }))
.unwrap();
let visible = Bounds2::new(Vec2::new(2.0, 4.0), Vec2::new(3.0, 6.0));
let hidden = Bounds2::new(Vec2::new(7.0, 4.0), Vec2::new(8.0, 6.0));
assert_eq!(select_window(&d, &Space::Model, visible, true), vec![h]);
assert!(select_window(&d, &Space::Model, hidden, true).is_empty());
}
}
#[cfg(test)]
@@ -1401,38 +817,4 @@ mod hatch_pattern_pick_tests {
let d = solid_hatch(loops(), 2);
assert!(pick(&d, &Space::Model, Vec2::new(5.0, 5.0), 0.05).is_some());
}
/// A window around everything a blank multileader draws (its geometry and its text frame)
/// selects it, at either annotation scale: the stored insertion points snap offers do not
/// widen the box a window has to contain (#2810).
#[test]
fn window_around_a_blank_multileader_still_selects_it() {
use cadcraft_geom::Vec3;
for scale in ["1:2", "2:1"] {
let mut s = crate::Session::new();
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let d = s.doc_mut().unwrap();
d.header.set_str("CANNOSCALE", scale);
let sc = d.anno_scale(scale).cloned().unwrap();
d.modify_entity(h, |e| {
e.common.anno_scales = vec![sc];
let EntityKind::MLeader(m) = &mut e.kind else { return };
let landing = m.landing;
if let Some(t) = m.text.as_mut() {
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
}
})
.unwrap();
let d = &*d;
let e = d.entity(h).unwrap();
let frame = blank_mtext_box(d, e).expect("a blank multileader has a frame");
let bx = entity_bounds(d, e, 0).union(&frame).expand(0.01);
assert!(select_window(d, &Space::Model, bx, false).contains(&h), "scale {scale}");
}
}
}
+2 -2
View File
@@ -3,8 +3,8 @@ use super::error::{EngineError, Result};
use super::running::{PendingWindow, Running};
use super::view::View;
use super::{
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp,
pointmod, prompt, select, snap, sysvars, units,
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp, pointmod,
prompt, select, snap, sysvars, units,
};
mod cmdline;
+5 -137
View File
@@ -1,8 +1,8 @@
use crate::DisplayOnly;
use super::{
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, Origin, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value,
Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2,
assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
};
impl Session {
@@ -41,60 +41,8 @@ impl Session {
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
}
/// Launch a non-nested interactive state machine through the standard command-start checks
/// (`enabled`, `refused_in_editor`, `commands_started`, `last_command`, `Guarded`, `feed`).
pub(crate) fn launch_interactive(
&mut self,
id: &str,
enabled: fn(&Session) -> std::result::Result<(), String>,
machine: Box<dyn crate::Interactive>,
) -> Result<()> {
self.last_polar = None;
self.pick_hint = None;
if self.running.is_some() {
self.cancel();
}
self.commands_started = self.commands_started.wrapping_add(1);
self.command_origin = if self.in_script || self.program_input { Origin::Program } else { Origin::Person };
enabled(self).map_err(|m| EngineError::Disabled(id.into(), m))?;
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, id) {
return Err(EngineError::Disabled(id.into(), why));
}
self.last_command = Some(id.to_string());
self.echo(format!("Command: {}", id.to_ascii_uppercase()));
let guarded = guard::Guarded::wrap(machine);
let st = self.state()?;
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
self.running = Some(Running { id: id.to_string(), machine: guarded, before, selection_before });
self.pending_window = None;
self.point_mods.clear();
self.feed(None)?;
Ok(())
}
/// Who started the command running now ([`Origin`]): fixed when it started, so a scripted or
/// LISP-started command keeps its origin while it prompts.
pub fn command_origin(&self) -> Origin {
self.command_origin
}
/// Start a command by name or alias as if typed at the command line. A script's commands are
/// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so
/// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command
/// "LINE" "0,0" "'-INSERT" …)` replaces LINE with an INSERT the routine started.
/// Start a command by name or alias as if typed at the command line.
pub fn start(&mut self, name: &str) -> Result<()> {
let origin = if self.in_script || self.program_input { Origin::Program } else { Origin::Person };
self.start_from(name, origin)
}
/// Start a command as a program does: an AutoLISP `(command …)` cannot answer a dialog, so
/// none opens for what it starts, even after the routine ends.
pub fn start_programmatic(&mut self, name: &str) -> Result<()> {
self.start_from(name, Origin::Program)
}
/// [`Session::start`] with the command's origin recorded for its whole life.
fn start_from(&mut self, name: &str, origin: Origin) -> Result<()> {
self.last_polar = None;
self.pick_hint = None;
let name = name.trim();
@@ -126,7 +74,7 @@ impl Session {
// A bare system variable name (ORTHOMODE, GRIDMODE…) acts as SETVAR on that variable.
let var = lower.to_ascii_uppercase();
if !name.starts_with(['_', '.', '-']) && sysvars::get(self, &var).is_some() {
self.start_from(if transparent { "'setvar" } else { "setvar" }, origin)?;
self.start(if transparent { "'setvar" } else { "setvar" })?;
return self.input(Input::Text(var));
}
return Err(EngineError::UnknownCommand(typed.to_string()));
@@ -153,15 +101,10 @@ impl Session {
return self.input(Input::Keyword("Undo".into()));
}
if !nested {
// The command this one replaces is cancelled first: its cancellation can run a paused
// LISP routine's `*error*` handler, and a handler that starts a command records that
// command's Program origin. Origin and number go in after it, so they describe this
// start and the factory below still sees the origin this command was started with.
self.commands_started = self.commands_started.wrapping_add(1);
if self.running.is_some() {
self.cancel();
}
self.commands_started = self.commands_started.wrapping_add(1);
self.command_origin = origin;
}
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) {
@@ -219,7 +162,6 @@ impl Session {
/// command (as in AutoCAD) and points do nothing. A LISP routine waiting in a `get…`
/// function takes the input instead; one paused in `command` carries on after it.
pub fn input(&mut self, input: Input) -> Result<()> {
self.inputs = self.inputs.wrapping_add(1);
if self.lisp_input(input.clone()) {
return Ok(());
}
@@ -599,17 +541,6 @@ impl Session {
self.running.as_ref().and_then(|r| r.machine.text_editor())
}
/// The attribute values the running command asks for in the Edit Attributes dialog
/// ([`Interactive::attribute_entry`]), stamped with the drawing it runs in and its number in
/// [`Session::commands_started`]: a dialog draft kept for a cancelled command never belongs
/// to the one started after it, even for the same block.
pub fn attribute_entry(&self) -> Option<crate::AttribEntry> {
let mut entry = self.running.as_ref().and_then(|r| r.machine.attribute_entry())?;
entry.drawing = self.docs.get(self.active).map_or(0, |d| d.uid);
entry.command = self.commands_started;
Some(entry)
}
pub fn current_prompt(&self) -> Option<Prompt> {
if let Some(p) = self.lisp_prompt() {
return Some(p);
@@ -677,29 +608,6 @@ impl Session {
out
}
/// The value the cursor would give at the active command's prompt (see
/// [`Interactive::live_value`]).
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
self.running.as_ref()?.machine.live_value(self, cursor)
}
/// What the rollover highlight shows of the object `h` under the cursor, with its properties,
/// when the running command highlights only a part of it ([`Interactive::highlight`]: TRIM
/// the piece a click there removes, EXTEND what it adds). `None`: the whole object.
pub fn highlight(&self, h: Handle, cursor: Vec2) -> Option<Vec<Entity>> {
let kinds = self.running.as_ref()?.machine.highlight(self, h, cursor)?;
let common = self.doc().ok()?.entity(h)?.common.clone();
Some(kinds.into_iter().map(|k| Entity { handle: h, common: common.clone(), kind: k }).collect())
}
/// What the running command will change wherever the cursor is, with each part's properties
/// ([`Interactive::highlight_all`]: TRIM's Fence and Crossing). `None`: nothing of the kind.
pub fn highlight_all(&self, cursor: Vec2) -> Option<Vec<Entity>> {
let parts = self.running.as_ref()?.machine.highlight_all(self, cursor)?;
let d = self.doc().ok()?;
Some(parts.into_iter().filter_map(|(h, k)| Some(Entity { handle: h, common: d.entity(h)?.common.clone(), kind: k })).collect())
}
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
/// `None`: the drawing.
@@ -716,44 +624,4 @@ impl Session {
let extra = d.extra.iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k.clone() }).collect();
Some((d, extra))
}
/// The live parameters of the running array command ([`Interactive::array_live`]).
pub fn array_live(&self) -> Option<crate::ArrayLive> {
self.running.as_ref().and_then(|r| r.machine.array_live())
}
/// Change the running array's live parameters. With no array running this does nothing; an
/// invalid value is refused and leaves the command as it was.
pub fn set_array_live(&mut self, v: &crate::ArrayLive) -> Result<()> {
if self.array_live().is_none() {
return Ok(());
}
let Some(mut run) = self.running.take() else { return Ok(()) };
let r = run.machine.set_array_live(self, v);
self.running = Some(run);
r
}
/// Ask the running polar array for its centre as the next canvas point
/// ([`Interactive::array_pick_center`]).
pub fn array_pick_center(&mut self) -> bool {
self.running.as_mut().is_some_and(|r| r.machine.array_pick_center())
}
/// Finish the running array: `Ok(true)` when the command ended, `Ok(false)` when there is no
/// array command or it is still selecting objects.
pub fn commit_array(&mut self) -> Result<bool> {
if self.array_live().is_none() {
return Ok(false);
}
if self.current_prompt().is_some_and(|p| p.accept.select) {
return Ok(false);
}
if let Some(r) = self.running.as_mut()
&& !r.machine.array_set_main()
{
return Ok(false);
}
self.feed(Some(Input::Keyword("eXit".into())))?;
Ok(self.running.is_none())
}
}
-4
View File
@@ -138,9 +138,6 @@ pub struct Settings {
/// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them
/// (default: 1).
pub attreq: bool,
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
/// dialog; on by default, as in AutoCAD (Initial value 1).
pub attdia: bool,
}
impl Default for Settings {
@@ -208,7 +205,6 @@ impl Default for Settings {
ucs_angle: 0.0,
auditctl: false,
attreq: true,
attdia: true,
}
}
}
+18 -274
View File
@@ -7,7 +7,7 @@ mod viewport;
pub use viewport::ViewportPoint;
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
use serde::Serialize;
@@ -385,7 +385,7 @@ fn osnap_in_with_prims(
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
// that don't reach each other).
@@ -475,60 +475,9 @@ pub(crate) fn gather(
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
gather_in(d, space, ix, cursor, aperture, osmode, &[])
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
/// block reference with. Objects on the layers `frozen` in the active viewport aren't drawn there,
/// so they are passed over.
pub(crate) fn nearest_with_direction(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
frozen: &[String],
skip: Handle,
) -> Option<(Vec2, Vec2)> {
let ix = crate::spatial::index(d, space);
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, frozen, Some(skip))?;
let mut best: Option<(f64, Vec2, Vec2)> = None;
let mut consider = |at: Vec2, dir: Vec2| {
let dd = at.dist(cursor);
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
best = Some((dd, at, dir * (1.0 / dir.len())));
}
};
for p in prims.iter().take(2000) {
if let Prim::Circle(c) = p {
let at = c.closest(cursor);
consider(at, (at - c.center).perp());
continue;
}
if let Prim::Infinite { base, dir, ray } = p {
let len = dir.len();
if len > 1e-12 {
let u = *dir * (1.0 / len);
// A ray runs one way from its base: behind it, its base is the nearest point.
let t = (cursor - *base).dot(u);
consider(*base + u * if *ray { t.max(0.0) } else { t }, u);
}
continue;
}
for seg in prim_segments(p) {
let seg = fix_circle(&seg);
let at = seg.closest(cursor);
match seg {
Segment::Line(l) => consider(at, l.b - l.a),
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
}
}
}
best.map(|(_, at, dir)| (at, dir))
}
#[allow(clippy::too_many_arguments)]
fn gather_in(
d: &Drawing,
space: &Space,
@@ -537,7 +486,6 @@ fn gather_in(
aperture: f64,
osmode: u32,
frozen: &[String],
skip: Option<Handle>,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
let probe = Bounds2::new(cursor, cursor).expand(aperture);
let mut cands: Vec<(u32, Vec2)> = Vec::new();
@@ -545,19 +493,13 @@ fn gather_in(
let mut count = 0usize;
let mut budget = MAX_BLOCK_LEAVES;
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
continue;
}
let inf = crate::select::is_infinite(e);
if !inf && !crate::select::bounds_of(d, e, known).expand(aperture).intersects(&probe) {
continue;
}
// A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate
// limit nor the intersection slots unless its drawn geometry is in reach, or INS is on and an
// insertion point is within the aperture.
if !inf && crate::select::blank_frame_only(d, e, &probe, cursor, aperture, osmode & mode::INS != 0) {
continue;
}
count += 1;
if count > 2000 {
break;
@@ -573,7 +515,6 @@ fn gather_in(
}
EntityKind::AttDef(a) => cands.push((mode::INS, a.text.justify_point())),
// A multileader: its text's insertion point, or its block content's.
// select.rs blank_snap_points must offer the same points.
EntityKind::MLeader(m) => {
cands.extend(m.text.iter().map(|t| (mode::INS, t.insert.xy())));
cands.extend(m.block.iter().map(|b| (mode::INS, b.insert.xy())));
@@ -590,15 +531,6 @@ fn gather_in(
if let EntityKind::Dimension(dm) = &e.kind {
sink.dimension(d, dm, &mut budget, frozen);
}
// A dimension kept as read draws its block through a reference in its graphics (#3438),
// and snaps to the objects inside it the same way.
if let EntityKind::Unknown(u) = &e.kind {
for g in &u.graphics {
if let EntityKind::Insert(ins) = &g.kind {
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
}
}
}
}
Some((cands, near_prims))
}
@@ -840,7 +772,20 @@ impl Sink<'_> {
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
match dm.block.as_ref().and_then(|n| d.block(n)) {
Some(blk) => {
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
// The block holds world geometry: a reference at its own base point places it as is.
let ins = Insert {
block: blk.name.clone(),
insert: blk.base,
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
block_leaves(d, &ins, &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
}
None => {
let g = cadcraft_render::dimension_in(d, dm);
@@ -917,18 +862,6 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
match &be.kind {
EntityKind::AttDef(_) => {}
EntityKind::Insert(inner) => block_leaves(d, inner, &mm, depth + 1, budget, frozen, f),
// A dimension draws its block, as at the top level.
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
}
k @ EntityKind::Unknown(u) => {
f(k, &mm);
for g in &u.graphics {
if let EntityKind::Insert(inner) = &g.kind {
block_leaves(d, inner, &mm, depth + 1, budget, frozen, f);
}
}
}
k => f(k, &mm),
}
}
@@ -936,24 +869,6 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
}
}
/// The reference that places a dimension's block as the renderer draws it: the block holds world
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
/// dimension; #2634).
fn dimension_reference(blk: &cadcraft_doc::Block, dm: &cadcraft_doc::Dimension) -> Insert {
Insert {
block: blk.name.clone(),
insert: blk.base + dm.insertion_point,
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}
}
/// Whether `p` comes within `aperture` of the box `probe`.
fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool {
let b = match p {
@@ -1256,27 +1171,6 @@ mod tests {
d
}
#[test]
fn alignment_targets_stay_on_a_ray_and_off_frozen_layers() {
let mut d = Drawing::new_imperial();
let ray = |base: (f64, f64)| EntityKind::Ray(cadcraft_doc::RayLine { base: Vec3::new(base.0, base.1, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) });
d.add(&Space::Model, Common::default(), ray((0.0, 0.0))).unwrap();
// Behind the ray: its base is the nearest point, out of a small aperture.
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(-5.0, 0.0), 0.5, &[], Handle(0)), None);
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(-0.2, 0.1), 0.5, &[], Handle(0)).unwrap();
assert!(at.dist(Vec2::ZERO) < 1e-12, "{at:?}");
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 0.1), 0.5, &[], Handle(0)).unwrap();
assert!(at.dist(Vec2::new(5.0, 0.0)) < 1e-12, "{at:?}");
// A line on a layer frozen in the viewport isn't a target.
let mut d = drawing();
d.ensure_layer("Hidden");
let c = Common { layer: "Hidden".into(), ..Common::default() };
let l = EntityKind::Line(Line { a: Vec3::new(0.0, 30.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) });
d.add(&Space::Model, c, l).unwrap();
assert!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &[], Handle(0)).is_some());
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None);
}
#[test]
fn endpoint_and_mid() {
let d = drawing();
@@ -1286,156 +1180,6 @@ mod tests {
assert_eq!(m.point, Vec2::new(5.0, 0.0));
}
/// Blank MTEXT frames over the cursor are for picking: thousands of them, with their insertion
/// points out of reach, must not crowd a real endpoint out of the snap candidates (#2810).
#[test]
fn blank_mtext_frames_do_not_crowd_out_snap_candidates() {
for line_first in [true, false] {
let mut d = Drawing::new_metric();
let line = EntityKind::Line(Line { a: Vec3::new(5.2, -1.0, 0.0), b: Vec3::new(30.0, -1.0, 0.0) });
if line_first {
d.add(&Space::Model, Common::default(), line.clone()).unwrap();
}
for _ in 0..2100 {
let t = cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
if !line_first {
d.add(&Space::Model, Common::default(), line).unwrap();
}
// The cursor is inside every box (x 0..10, y -2.5..0), 0.2 from the line's end.
let h = osnap(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.5, mode::END, None, false).unwrap();
assert_eq!(h.point, Vec2::new(5.2, -1.0), "line first: {line_first}");
// A blank MTEXT whose insertion point is in the aperture keeps its INS snap.
let h = osnap(&d, &Space::Model, Vec2::new(0.1, -0.1), 0.5, mode::INS, None, false).unwrap();
assert_eq!(h.point, Vec2::new(0.0, 0.0), "line first: {line_first}");
}
}
/// 2001 blank MTEXT frames covering `cursor` (insertion points at `ins_at`), drawn before a
/// LINE whose end is at `cursor`: the END snap found with `osmode`.
fn crowded_blank_frames_end_snap(ins_at: Vec2, cursor: Vec2, aperture: f64, osmode: u32) -> Option<Vec2> {
let mut d = Drawing::new_metric();
for _ in 0..2001 {
let t = cadcraft_doc::MText {
insert: Vec3::new(ins_at.x, ins_at.y, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(cursor.x, cursor.y, 0.0), b: Vec3::new(30.0, cursor.y, 0.0) }))
.unwrap();
osnap(&d, &Space::Model, cursor, aperture, osmode, None, false).map(|h| h.point)
}
/// An insertion point in a corner of the square probe is farther than the aperture from the
/// cursor, so snap would never accept it: its frame must not crowd out an END snap.
#[test]
fn blank_insertion_points_in_the_probe_corner_do_not_crowd_out_an_end_snap() {
let cursor = Vec2::new(5.0, -1.0);
let ap = 0.5;
let corner = Vec2::new(cursor.x - 0.9 * ap, cursor.y + 0.9 * ap);
assert!(corner.dist(cursor) > ap, "outside the circle, inside the square probe");
assert_eq!(crowded_blank_frames_end_snap(corner, cursor, ap, mode::END | mode::INS), Some(cursor));
}
/// With INS off a blank MTEXT's insertion point is no snap candidate, even right at the cursor.
#[test]
fn blank_insertion_points_with_ins_off_do_not_crowd_out_an_end_snap() {
let cursor = Vec2::new(5.0, -1.0);
assert_eq!(crowded_blank_frames_end_snap(cursor, cursor, 0.5, mode::END), Some(cursor));
}
/// A blank annotative multileader (text 6 right of its landing, 4 x 2, at 1:2) among 2100 blank
/// MTEXT frames over the cursor. `block_at` also gives it a block content at that offset from
/// the landing. Returns the INS snap at `landing + probe` (aperture 0.5).
fn crowded_blank_mleader_ins(block_at: Option<f64>, probe: Vec2) -> Option<Vec2> {
let mut s = crate::Session::new();
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let landing = {
let d = s.doc_mut().unwrap();
if block_at.is_some() {
// A block whose geometry (a line 60 long) covers its base point, at the stored insertion
// and, drawn at 1:2 about the landing, at the scaled one too.
let mut blk = cadcraft_doc::Block::new("BLK");
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(60.0, 0.0, 0.0) });
blk.entities.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), line));
d.blocks.insert("BLK".into(), std::sync::Arc::new(blk));
}
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
d.modify_entity(h, |e| {
e.common.anno_scales = vec![half];
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
let landing = m.landing;
let t = m.text.as_mut().unwrap();
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
if let Some(x) = block_at {
m.block = Some(cadcraft_doc::Insert {
block: "BLK".into(),
insert: landing + Vec3::new(x, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
..Default::default()
});
}
})
.unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
m.landing.xy()
};
let cursor = landing + probe;
// Blank frames (10 x 2.5, top-left at the insert) cover the cursor; their inserts do not.
let d = s.doc_mut().unwrap();
for _ in 0..2100 {
let t = cadcraft_doc::MText {
insert: Vec3::new(cursor.x - 5.0, cursor.y + 1.0, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
osnap(d, &Space::Model, cursor, 0.5, mode::INS, None, false).map(|h| h.point - landing)
}
/// An annotative blank multileader keeps its INS snap (the stored, unscaled insertion point)
/// among thousands of blank frames, and so does its block content.
#[test]
fn annotative_blank_mleader_keeps_its_ins_snaps_among_blank_frames() {
assert_eq!(crowded_blank_mleader_ins(None, Vec2::new(6.1, -0.1)), Some(Vec2::new(6.0, 0.0)), "text");
assert_eq!(crowded_blank_mleader_ins(Some(30.0), Vec2::new(30.1, -0.1)), Some(Vec2::new(30.0, 0.0)), "block");
}
#[test]
fn intersection() {
let d = drawing();
+1 -2
View File
@@ -53,8 +53,7 @@ impl ChunkIx {
if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) {
infinite.push(u32::try_from(i).unwrap_or(u32::MAX));
}
let b = entity_bounds_cached(d, e, 0, &mut cache);
crate::select::pick_bounds(d, e, b)
entity_bounds_cached(d, e, 0, &mut cache)
})
.collect();
let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+1 -4
View File
@@ -89,11 +89,8 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53,
/// On/off session settings: name, read, write.
type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool));
const SETTINGS: &[Toggle] = &[
// ATTDIA 1 (the default): INSERT typed or from a menu asks for attribute values in the Edit
// Attributes dialog; 0: at the command line. ATTREQ 0: INSERT gives every attribute its default.
("ATTDIA", |s| s.attdia, |s, v| s.attdia = v),
("ATTREQ", |s| s.attreq, |s, v| s.attreq = v),
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
("ATTREQ", |s| s.attreq, |s, v| s.attreq = v),
("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v),
];
-91
View File
@@ -532,97 +532,6 @@ fn scale_reference_typed_and_picked() {
assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9));
}
#[test]
fn scale_reference_points_and_copy() {
fn line_ends(s: &Session) -> Vec<Vec2> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(l.b.xy()),
_ => None,
})
.collect()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference 10 via two points, then Points option with two points of length 30 -> (30, 0).
for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify new length");
assert!(p.keywords.contains(&"Points".to_string()));
assert!(p.keywords.contains(&"Copy".to_string()));
s.cmdline("p").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify first point");
s.cmdline("5,5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,35").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9));
// Coinciding Points are rejected without leaving the second-point prompt; a valid point completes.
for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_some());
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,25").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9));
// Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy.
for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 2);
assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9)));
assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9)));
// Copy entered at "Specify new length" combined with Points scales a copy.
for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 3);
assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9)));
}
#[test]
fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
e.common.thickness = 3.0;
if let EntityKind::Text(t) = &mut e.kind {
t.insert.z = 5.0;
}
})
.unwrap();
s.set_selection(vec![h]);
s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
assert!(s.current_prompt().unwrap().message.contains("** SCALE **"));
s.cmdline("2").unwrap();
assert!(s.running.is_none());
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0);
assert_eq!(t.insert.z, 10.0);
}
#[test]
fn layers_and_properties() {
let mut s = Session::new();
-21
View File
@@ -323,26 +323,5 @@ fn clipboard_travels_as_text() {
t.execute("pasteorig", &json!({})).unwrap();
assert_eq!(t.doc().unwrap().model.len(), 2);
assert!(t.doc().unwrap().block("DOOR").is_some() && t.doc().unwrap().layer("HINGE").is_some());
// A paste asked for from a menu or by name reads the system clipboard first, so text from
// another window replaces a copy made here earlier; text that is not a DXF drawing does not.
let mut u = Session::empty();
u.open_drawing(drawing_b(), "B", None);
assert!(u.execute("pasteclip", &json!({})).is_err(), "nothing to paste yet");
assert!(clipboard::load_system_text(&mut u, &text));
u.execute("pasteclip", &json!({})).unwrap();
assert_eq!(u.doc().unwrap().model.len(), 2, "the system clipboard's objects were pasted");
let mut v = Session::empty();
v.open_drawing(drawing_b(), "B", None);
let local = line(v.doc_mut().unwrap(), "0", (1.0, 1.0), (2.0, 2.0));
let local_handle = local.handle.hex();
v.doc_mut().unwrap().model.push(local);
v.execute("copyclip", &json!({ "handles": [local_handle] })).unwrap();
assert_eq!(v.clipboard.len(), 1);
assert!(!clipboard::load_system_text(&mut v, "just some words"), "not a drawing");
assert_eq!(v.clipboard.len(), 1, "the copy made here stays");
assert!(clipboard::load_system_text(&mut v, &text));
assert_eq!(v.clipboard.len(), 2, "newer text from another window replaces it");
assert!(v.clipboard_source.as_ref().is_some_and(|c| c.uid.is_none()));
let _ = a;
}
-115
View File
@@ -1,115 +0,0 @@
//! DIMASSOC 1 creates dimension objects without coupling them to source geometry; 2 couples them.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
use serde_json::{Value, json};
/// Read the single entity handle returned by a dimension command.
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
}
/// Clone the asserted dimension so later edits can be compared with its previous state.
fn dimension(s: &Session, h: Handle) -> Dimension {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Dimension(d) => d.clone(),
other => panic!("expected dimension, got {other:?}"),
}
}
/// Create a synthetic source line and return its first entity handle.
fn line(s: &mut Session, a: [i32; 2], b: [i32; 2]) -> Handle {
let v = s.execute("line", &json!({"points": [a, b]})).unwrap();
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
}
/// Set the drawing-wide associativity mode before creating the test dimensions.
fn mode(s: &mut Session, n: i32) {
s.execute("setvar", &json!({"name": "DIMASSOC", "value": n})).unwrap();
}
/// Typed and JSON dimensions retain their mode through DXF, source edits, undo and redo.
#[test]
fn linear_dimensions_respect_the_mode_through_edits_and_dxf() {
for n in [1, 2] {
for typed in [false, true] {
let mut s = Session::new();
mode(&mut s, n);
let source = line(&mut s, [0, 0], [10, 0]);
let d = if typed {
s.cmdline("dimlinear 0,0 10,0 5,4").unwrap();
s.last_dim.unwrap()
} else {
handle(&s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap())
};
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, typed{typed}");
let saved = cadcraft_io::write_dxf(s.doc().unwrap());
let has_link = saved.lines().any(|l| l.trim() == "DIMASSOC");
assert_eq!(has_link, n == 2, "mode{n}: only associative dimensions save a DIMASSOC object");
let mut reopened = Session::new();
reopened.open_drawing(cadcraft_io::read_dxf(saved.as_bytes()).unwrap(), "roundtrip.dxf", None);
for session in [&mut s, &mut reopened] {
session.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
let edited = dimension(session, d);
assert_eq!(edited.p14.x, if n == 2 { 15.0 } else { 10.0 });
assert_eq!(cadcraft_engine::render::dimension_in(session.doc().unwrap(), &edited).measurement, if n == 2 { 15.0 } else { 10.0 });
session.undo().unwrap();
assert_eq!(dimension(session, d).p14.x, 10.0);
session.redo().unwrap();
assert_eq!(dimension(session, d).p14.x, edited.p14.x);
}
}
}
}
/// Continue, Baseline and Quick Dimension attach source links only in mode 2.
#[test]
fn indexed_chains_and_qdim_respect_the_mode() {
for n in [1, 2] {
for cmd in ["dimcontinue", "dimbaseline", "qdim"] {
let mut s = Session::new();
mode(&mut s, n);
let source = line(&mut s, [0, 0], [10, 0]);
s.execute("point", &json!({"at": [20, 0]})).unwrap();
s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap();
let params = if cmd == "qdim" { json!({"handles": [source.hex()], "at": [5, 6]}) } else { json!({"points": [[20, 0]]}) };
let out = s.execute(cmd, &params).unwrap();
let hs = out["handles"].as_array().unwrap();
assert!(!hs.is_empty());
for h in hs {
let d = dimension(&s, Handle::parse_hex(h.as_str().unwrap()).unwrap());
assert_eq!(d.assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, {cmd}");
}
}
}
}
/// Even explicitly selected angular source lines produce associations only in mode 2.
#[test]
fn explicit_angular_links_respect_the_mode() {
for n in [1, 2] {
let mut s = Session::new();
mode(&mut s, n);
let a = line(&mut s, [0, 0], [10, 0]);
let b = line(&mut s, [0, 0], [0, 10]);
let d = handle(&s.execute("dimangular", &json!({"lines": [a.hex(), b.hex()], "at": [4, 4]})).unwrap());
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 4 } else { 0 });
}
}
/// Changing the creation mode preserves old links and does not disable explicit reassociation.
#[test]
fn mode_change_keeps_existing_links_and_allows_explicit_reassociation() {
let mut s = Session::new();
let source = line(&mut s, [0, 0], [10, 0]);
let params = json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]});
let existing = handle(&s.execute("dimlinear", &params).unwrap());
mode(&mut s, 1);
let new = handle(&s.execute("dimlinear", &params).unwrap());
assert_eq!(dimension(&s, existing).assoc.len(), 2);
assert!(dimension(&s, new).assoc.is_empty());
s.execute("dimreassociate", &json!({"handles": [new.hex()]})).unwrap();
assert_eq!(dimension(&s, new).assoc.len(), 2);
s.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
assert_eq!(dimension(&s, existing).p14.x, 15.0);
assert_eq!(dimension(&s, new).p14.x, 15.0);
}

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