mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-30 22:10:12 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3d23ce225 | ||
|
|
cd96a12ae4 |
@@ -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-----
|
||||
@@ -1,117 +0,0 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/cadcraft",
|
||||
"repository_id": 1408289866,
|
||||
"producer_workflow_id": 429719786,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"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": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"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"
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CADCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# Actual context guards: official repository and completed workflow_run only.
|
||||
if: >-
|
||||
github.repository == 'storytold/cadcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/cadcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/cadcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/cadcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/cadcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'cadcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -1,59 +0,0 @@
|
||||
name: CADCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
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 nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/cadcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/nightly-signer' && 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@main
|
||||
with:
|
||||
tooling-revision: main
|
||||
app-name: cadcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -1,37 +0,0 @@
|
||||
name: CADCraft unsigned nightly
|
||||
|
||||
# Automated nightly builds at 00:30 UTC (paired with nightly-dispatch.yml for automatic
|
||||
# Stage 2 signer dispatch) plus supervised manual runs by the reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 0 * * *'
|
||||
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@main
|
||||
with:
|
||||
tooling-revision: main
|
||||
app-name: cadcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
@@ -1,20 +0,0 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -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
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -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__/
|
||||
|
||||
@@ -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)
|
||||
@@ -72,8 +72,6 @@ Layout:
|
||||
|
||||
Checks for the crates you changed: `cargo test -p <crate>`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`, `cargo xtask parity` (regenerates `docs/parity-checklist.md`).
|
||||
|
||||
Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a covered menu item `headless: yes` because its command is in the engine registry that `cadcraft-cli` and the MCP server load. An uncovered item takes `no`/`partial` and a `reach` (`window`, `os`, `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs` (a path ending in ` > ` covers its submenu), or reads `unknown`. Never write `yes` there. A covered leaf is `yes` whatever its marks say, so a submenu mark stays while any leaf under it is uncovered; drop a mark only once commands cover every leaf it matches (the check then fails on it as stale).
|
||||
|
||||
Paths and conventions:
|
||||
|
||||
- No crate allows `unsafe` (`unsafe_code = "forbid"` in the workspace).
|
||||
|
||||
+1
-44
@@ -25,7 +25,6 @@ Generated-in-code assets are original and have no file to list:
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
|
||||
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
|
||||
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
|
||||
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
|
||||
@@ -46,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 |
|
||||
@@ -88,41 +81,5 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
|
||||
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
|
||||
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
|
||||
|
||||
|
||||
## PDF import
|
||||
|
||||
The CAD mapping and initial synthetic PDF tests are adapted from CADCraft contributor
|
||||
@DuukDuul's [PR #2787](https://github.com/storytold/cadcraft/pull/2787), commit
|
||||
`ec17f63f189d1dccf91357701f9bba243ca88dd5`, under MIT OR Apache-2.0. The mapping has
|
||||
been changed for the current shared reader, bounded import, fill rules and diagnostics.
|
||||
PDF test inputs in `crates/io/tests/it/pdf_import.rs`, `crates/io/src/pdf_read.rs`, and
|
||||
`apps/cadcraft-cli/tests/it/pdf_import.rs` are generated from literal content streams or
|
||||
CadCraft's own plotter. No customer documents are included.
|
||||
|
||||
Enabling `craft-pdf` interpretation uses the following unchanged dependency assets from
|
||||
`craft-libs` revision `453b0da782ccef39be9a6dac8d27c80b553ef1cc`. Fonts remain in the
|
||||
shared dependency. Their source and hashes are retained below; notices are in `NOTICE`.
|
||||
|
||||
| Asset | Author | Source | Licence | SHA-256 | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
|
||||
Generated
+92
-1415
File diff suppressed because it is too large
Load Diff
+28
-40
@@ -14,12 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
# internal
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -29,19 +28,17 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
# Delimited text (CSV/TSV) parsing (shared Craft library).
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
@@ -51,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"] }
|
||||
@@ -75,12 +70,8 @@ encoding_rs = "0.8.35"
|
||||
quick-xml = "0.42"
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -90,7 +81,7 @@ egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
web-time = "1.1"
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -122,23 +113,20 @@ debug = 0
|
||||
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
|
||||
# (Cargo ignores dependency-local patches).
|
||||
[patch.crates-io]
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -89,15 +89,9 @@
|
||||
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
|
||||
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
|
||||
the way decades of drafting habit expect.
|
||||
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
|
||||
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
|
||||
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
|
||||
and save as 2000 through 2018. New drawings default to
|
||||
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
|
||||
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
|
||||
drawings; drawings with a file keep their own version, subject to supported-version mapping
|
||||
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
|
||||
saves. Export to SVG and PNG today.
|
||||
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
|
||||
files (R13 through 2018) open and save through the open-source acadrust library. Export to SVG
|
||||
and PNG today.
|
||||
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
|
||||
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
|
||||
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
|
||||
@@ -120,11 +114,11 @@ numbers):
|
||||
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
|
||||
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
|
||||
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
|
||||
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
|
||||
| Files | DXF read (R12–2018, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) |
|
||||
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
|
||||
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
|
||||
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
|
||||
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული) and Tamil (தமிழ், with an installed Tamil font), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
|
||||
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
|
||||
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
|
||||
|
||||
## Quick start
|
||||
@@ -350,9 +344,7 @@ See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of
|
||||
|---|---|---|
|
||||
| x64 (64-bit Intel/AMD) | `cadcraft-<ver>-windows-x64.msi` | `cadcraft-<ver>-windows-x64-portable.zip` |
|
||||
| arm64 (Snapdragon and other ARM PCs) | `cadcraft-<ver>-windows-arm64.msi` | `cadcraft-<ver>-windows-arm64-portable.zip` |
|
||||
|
||||
For 32-bit Windows, [CADCraft v0.18.0](https://github.com/storytold/cadcraft/releases/tag/v0.18.0)
|
||||
was the last release with both an x86 MSI and portable ZIP.
|
||||
| x86 (32-bit) | `cadcraft-<ver>-windows-x86.msi` | `cadcraft-<ver>-windows-x86-portable.zip` |
|
||||
|
||||
Installers and executables are code-signed.
|
||||
|
||||
@@ -389,19 +381,15 @@ and web backend defaults are unchanged.
|
||||
| Flatpak | `cadcraft-<ver>-linux-x86_64.flatpak` | `cadcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
|
||||
| Debian/Ubuntu | `cadcraft-<ver>-linux-x86_64.deb` | `cadcraft-<ver>-linux-aarch64.deb` | |
|
||||
| Fedora/RHEL/openSUSE | `cadcraft-<ver>-linux-x86_64.rpm` | `cadcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Arch Linux | `cadcraft-<ver>-linux-x86_64.pkg.tar.zst` | `cadcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
|
||||
| Tarball | `cadcraft-<ver>-linux-x86_64.tar.gz` | `cadcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
|
||||
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
|
||||
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
|
||||
RISC-V (riscv64): `cadcraft-<ver>-linux-riscv64.tar.gz`, cross-compiled; needs glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `cadcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
| aarch64 (ARM64) | `cadcraft-<ver>-freebsd-aarch64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
|
||||
+3
-6
@@ -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 |
|
||||
|
||||
@@ -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 {
|
||||
@@ -66,7 +66,7 @@ fn convert_long_about() -> &'static str {
|
||||
|
||||
/// cadcraft-cli: headless CADCraft
|
||||
#[derive(Parser)]
|
||||
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), propagate_version = true, arg_required_else_help = true)]
|
||||
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
|
||||
@@ -45,17 +45,10 @@ fn install_io() {
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
});
|
||||
// The same writers, with what an image draws short of the drawing (dashed lines past the
|
||||
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
|
||||
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
|
||||
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
|
||||
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
|
||||
});
|
||||
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
@@ -66,7 +59,6 @@ fn install_io() {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
|
||||
@@ -145,22 +145,15 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
|
||||
|
||||
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
|
||||
let d = s.doc()?;
|
||||
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
|
||||
let bytes = cadcraft_io::write_framed(d, out, window)?;
|
||||
let folder = write_atomic(out, &bytes)?;
|
||||
report_new_folder(folder, io);
|
||||
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
|
||||
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
|
||||
for note in notes {
|
||||
io.errln(format_args!("{}: {note}", out.display()));
|
||||
}
|
||||
if cadcraft_engine::cmd::file::drops_unknown(out) {
|
||||
let lost = cadcraft_engine::cmd::file::not_saved(d);
|
||||
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
|
||||
io.errln(format_args!("{m}"));
|
||||
}
|
||||
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
|
||||
io.errln(format_args!("{note}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -178,10 +171,6 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) ->
|
||||
ole = ole.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
// One with proxy graphics draws them (#2697, #3438).
|
||||
if !u.graphics.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let n = types.entry(u.dxf_type.as_str()).or_insert(0);
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
|
||||
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
|
||||
//! 50,001 periods, which an export keeps dashed, gets no note.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
|
||||
fn dashed_line(periods: f64) -> String {
|
||||
format!(
|
||||
"0
|
||||
SECTION
|
||||
2
|
||||
TABLES
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LTYPE
|
||||
70
|
||||
1
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
DASHED
|
||||
70
|
||||
0
|
||||
3
|
||||
Dashed
|
||||
72
|
||||
65
|
||||
73
|
||||
2
|
||||
40
|
||||
0.75
|
||||
49
|
||||
0.5
|
||||
74
|
||||
0
|
||||
49
|
||||
-0.25
|
||||
74
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
LINE
|
||||
8
|
||||
0
|
||||
6
|
||||
DASHED
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
{}
|
||||
21
|
||||
0
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
",
|
||||
periods * 0.75
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
|
||||
let long = dir.join("long.dxf");
|
||||
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
|
||||
let control = dir.join("control.dxf");
|
||||
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
|
||||
let notes = |out: &Output| {
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
|
||||
};
|
||||
for ext in ["png", "svg", "pdf"] {
|
||||
let image = dir.join(format!("long.{ext}"));
|
||||
let image = image.to_str().unwrap();
|
||||
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
|
||||
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
|
||||
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
|
||||
assert!(got.is_empty(), "{ext}: {got:?}");
|
||||
}
|
||||
// A DXF copy draws nothing, so there is nothing to note.
|
||||
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The engine's commands that write an image say it too, on the command line and in the result's
|
||||
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
|
||||
/// `document.bytes`.
|
||||
#[test]
|
||||
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
|
||||
let cmds = [
|
||||
format!("export {{\"path\": {}}}", out("export.png")),
|
||||
format!("plot {{\"path\": {}}}", out("plot.pdf")),
|
||||
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
|
||||
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
|
||||
format!("saveas {{\"path\": {}}}", out("saved.svg")),
|
||||
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
|
||||
"plot {\"output\": \"svg\"}".to_string(),
|
||||
"document.bytes {\"format\": \"pdf\"}".to_string(),
|
||||
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
|
||||
];
|
||||
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
|
||||
let input = dir.join(format!("line-{periods}.dxf"));
|
||||
std::fs::write(&input, dashed_line(periods)).unwrap();
|
||||
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
|
||||
for c in &cmds {
|
||||
args.extend(["--cmd".to_string(), c.clone()]);
|
||||
}
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
|
||||
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
|
||||
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(results.len(), cmds.len(), "{results:?}");
|
||||
for (c, r) in cmds.iter().zip(&results) {
|
||||
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
|
||||
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
|
||||
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
|
||||
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
|
||||
}
|
||||
// Said on the command line once for each command.
|
||||
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
|
||||
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//! A LISP routine in a `run` script runs to its end before the script goes on and the drawing is
|
||||
//! saved, however many slices it takes (#3635).
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
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 loop takes many slices: the circle drawn after it is in the saved drawing, and the next
|
||||
/// line runs once the routine has ended.
|
||||
#[test]
|
||||
fn a_long_routine_in_a_script_draws_before_the_save() {
|
||||
let scratch = Scratch::new("lisp-script");
|
||||
let saved = scratch.0.join("out.dxf");
|
||||
let saved = saved.to_str().unwrap();
|
||||
let script = r#"(progn (repeat 1000000 (setq x 1)) (command "circle" "0,0" "5") (princ "done"))\n(princ (+ x 1))"#;
|
||||
let out = cli(&["run", "--metric", "--script", script, "--save", saved]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(err.lines().any(|l| l == "done") && err.lines().any(|l| l == "2"), "{err}");
|
||||
let info = cli(&["info", saved]);
|
||||
let v: serde_json::Value = serde_json::from_slice(&info.stdout).unwrap();
|
||||
assert_eq!(v["counts"]["Circle"], 1, "{v}");
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
|
||||
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A DXF with a 256-element linetype and a line drawn with it.
|
||||
fn dxf() -> String {
|
||||
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
|
||||
for i in 0..256 {
|
||||
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
|
||||
}
|
||||
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = dir.join("long.dxf");
|
||||
std::fs::write(&source, dxf()).unwrap();
|
||||
let source = source.to_str().unwrap();
|
||||
let notes =
|
||||
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
|
||||
|
||||
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(
|
||||
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
|
||||
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
|
||||
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1,13 +1,7 @@
|
||||
mod cli;
|
||||
mod dash_limit_note;
|
||||
mod drafting_spacing;
|
||||
mod help;
|
||||
mod lisp_script;
|
||||
// DWG output needs craft-dwg's bridge.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_note;
|
||||
mod mcp_connect;
|
||||
mod pdf_import;
|
||||
mod skipped_records;
|
||||
mod undrawn_entities;
|
||||
mod usage;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -188,25 +188,12 @@ fn subcommand_help_requests() {
|
||||
),
|
||||
case("help after an extra argument", &["info", "{b}", "extra", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty),
|
||||
case("--help after -- is a file name", &["run", "--", "--help"], 1, Empty, Starts("error: invalid parameters for `open`: --help:")),
|
||||
case("run --version", &["run", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
|
||||
case("info --version", &["info", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
|
||||
/// return without running it (`mcp` would otherwise wait for a client).
|
||||
#[test]
|
||||
fn every_subcommand_prints_the_version() {
|
||||
for sub in ["info", "convert", "run", "commands", "mcp", "perf", "sample", "roundtrip"] {
|
||||
for flag in ["--version", "-V"] {
|
||||
let top = invoke(&[flag]);
|
||||
let release = top.stdout.strip_prefix("cadcraft-cli ").unwrap_or_else(|| panic!("{:?}", top.stdout));
|
||||
let got = invoke(&[sub, flag]);
|
||||
assert_eq!((got.code, got.stderr.as_str()), (0, ""), "{sub} {flag}");
|
||||
assert_eq!(got.stdout, format!("cadcraft-cli-{sub} {release}"), "{sub} {flag}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_flags_on_every_subcommand() {
|
||||
run_cases(
|
||||
@@ -831,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() {
|
||||
@@ -850,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")),
|
||||
@@ -870,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:?}");
|
||||
|
||||
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -54,12 +54,11 @@ mod web {
|
||||
if let Some(bridge) = &self.2 {
|
||||
bridge.report_dirty(&self.0);
|
||||
}
|
||||
self.0.close_path(ctx);
|
||||
}
|
||||
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
|
||||
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
}
|
||||
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
@@ -120,17 +119,10 @@ mod web {
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
});
|
||||
// The same writers, with what an image draws short of the drawing (dashed lines past the
|
||||
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
|
||||
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
|
||||
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
|
||||
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
|
||||
});
|
||||
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
@@ -141,7 +133,6 @@ mod web {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
@@ -174,7 +165,6 @@ mod web {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
|
||||
@@ -94,7 +94,7 @@ mod tests {
|
||||
let mut ui = UiState::default();
|
||||
let before = serde_json::to_value(&ui).unwrap();
|
||||
let mut invalid = ui.clone();
|
||||
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
|
||||
invalid.docking.layout.root = None;
|
||||
assert!(save(&invalid).is_err());
|
||||
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
|
||||
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
|
||||
|
||||
@@ -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;
|
||||
|
||||
+10
-11
@@ -24,16 +24,11 @@ serde_json = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
log = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
craft-nightly = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`).
|
||||
# Already in Cargo.lock through eframe; same version so nothing is built twice.
|
||||
ron = "0.12"
|
||||
# Waits for wgpu's answers while the graphics start (src/renderer.rs) and, on macOS, for the
|
||||
# answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already in
|
||||
# Cargo.lock through eframe.
|
||||
pollster = "1"
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
@@ -46,20 +41,27 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
|
||||
craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
|
||||
# controls and under floating panels.
|
||||
craft-window = { workspace = true }
|
||||
muda = { version = "0.21", default-features = false }
|
||||
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
|
||||
# (system_animations.rs). Already in Cargo.lock through muda.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
|
||||
# The same winit eframe uses (the storytold fork, patched in the workspace).
|
||||
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
|
||||
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
|
||||
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
|
||||
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
|
||||
# in Cargo.lock through eframe.
|
||||
pollster = "1"
|
||||
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
|
||||
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
|
||||
@@ -75,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
@@ -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}");
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
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::{BuildFlavor, needs_native_error, version, version_query};
|
||||
|
||||
#[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_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(&[]));
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,8 @@
|
||||
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
|
||||
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
|
||||
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
|
||||
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
|
||||
//! connection has carried the token), queued requests, and how long a socket may sit idle or
|
||||
//! blocked on a write.
|
||||
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
|
||||
//! socket may sit idle or blocked on a write.
|
||||
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
@@ -25,9 +24,6 @@ struct Limits {
|
||||
max_clients: usize,
|
||||
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
|
||||
max_line: usize,
|
||||
/// Longest request line until a request on the connection has carried the right token; a
|
||||
/// longer one closes the connection (#1925).
|
||||
preauth_line: usize,
|
||||
/// Request-line bytes buffered at once across all connections; a request that would pass it
|
||||
/// is refused with an error reply.
|
||||
total_bytes: usize,
|
||||
@@ -47,7 +43,6 @@ impl Default for Limits {
|
||||
max_clients: 16,
|
||||
// Generous, so requests that carry whole drawings or images as base64 still fit.
|
||||
max_line: 256 * 1024 * 1024,
|
||||
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
|
||||
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
|
||||
total_bytes: 512 * 1024 * 1024,
|
||||
queue: 64,
|
||||
@@ -349,21 +344,12 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
let mut reader = BufReader::new(read);
|
||||
let mut buf = Vec::new();
|
||||
let mut held = Held::new(budget);
|
||||
// The token is checked only after the whole line is read, so until a request here has carried
|
||||
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
|
||||
let mut authenticated = false;
|
||||
loop {
|
||||
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
|
||||
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
|
||||
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
|
||||
Ok(false) => break,
|
||||
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
|
||||
// A line nobody asked for would be read as the reply to the client's next request.
|
||||
Err(_) if buf.is_empty() => break,
|
||||
// Only an overlong line leaves more than `max` bytes buffered.
|
||||
Err(_) if !authenticated && buf.len() > max => format!(
|
||||
"request line longer than {max} bytes before a request with the control token on this connection; \
|
||||
send a short request with the token (such as `ping`) first; closing the connection"
|
||||
),
|
||||
Err(e) => e,
|
||||
Ok(true) => match parse_line(&buf) {
|
||||
Line::Blank => continue,
|
||||
@@ -380,7 +366,6 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
let _ = writeln!(out, "{r}");
|
||||
break;
|
||||
}
|
||||
authenticated = true;
|
||||
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
|
||||
// error, not a request run with defaults.
|
||||
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
|
||||
@@ -514,12 +499,7 @@ mod tests {
|
||||
|
||||
/// The control server on a loopback port, with a stand-in UI that echoes each method.
|
||||
fn serve_echo() -> std::net::SocketAddr {
|
||||
serve_echo_with(Limits::default())
|
||||
}
|
||||
|
||||
/// [`serve_echo`] under `limits`.
|
||||
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
|
||||
let (addr, rx) = serve_with(limits);
|
||||
let (addr, rx) = serve_with(Limits::default());
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
|
||||
@@ -632,60 +612,6 @@ mod tests {
|
||||
drop(first);
|
||||
}
|
||||
|
||||
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
|
||||
/// has shown the token, up to 100 000 after.
|
||||
fn preauth() -> Limits {
|
||||
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
|
||||
}
|
||||
|
||||
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
|
||||
fn long_req_line(id: i64, len: usize) -> String {
|
||||
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
|
||||
}
|
||||
|
||||
/// A peer without the token is refused once its line passes the pre-authentication bound,
|
||||
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
|
||||
/// at its end (#1925).
|
||||
#[test]
|
||||
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
|
||||
let (addr, rx) = serve_with(preauth());
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
|
||||
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
|
||||
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
|
||||
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
|
||||
c.write_all(unfinished.as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(&mut c).read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(v["ok"], json!(false));
|
||||
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// A long request with the token is taken once a shorter request with the token has been
|
||||
/// answered on the same connection; as a connection's first line it is refused, since its
|
||||
/// token comes only at the end.
|
||||
#[test]
|
||||
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
|
||||
let addr = serve_echo_with(preauth());
|
||||
let long = long_req_line(2, 5000);
|
||||
let first = exchange(addr, long.as_bytes());
|
||||
assert_eq!(first.len(), 1, "{first:?}");
|
||||
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
for (id, method) in [(1, "ping"), (2, "long")] {
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["id"].as_i64(), v["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_budget_is_given_back_when_the_connection_ends() {
|
||||
let budget = Budget::new(100);
|
||||
|
||||
@@ -23,10 +23,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
|
||||
(CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"),
|
||||
(LOCALE, "the interface language, instead of the system's"),
|
||||
(VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"),
|
||||
(
|
||||
STENCIL,
|
||||
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
|
||||
),
|
||||
(STENCIL, "0 opens the window without a stencil buffer, for drivers that show a black window; clipped layout viewports then draw unclipped"),
|
||||
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
|
||||
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
|
||||
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
|
||||
@@ -49,10 +46,8 @@ pub(crate) struct Env {
|
||||
pub(crate) locale: Option<String>,
|
||||
/// Present with vsync (default: off on Linux and BSD, on elsewhere).
|
||||
pub(crate) vsync: Switch,
|
||||
/// Off: the window has no stencil buffer; on: it keeps one on every attempt at starting the
|
||||
/// graphics. Default: it starts with one, and a start that can't draw with it drops it (see
|
||||
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
|
||||
/// stencil pass and then present a black window.
|
||||
/// Off: the window has no stencil buffer (default: on). Some old drivers (Mesa on Intel HD
|
||||
/// 4000, old Intel drivers on Windows) accept a stencil pass and then present a black window.
|
||||
pub(crate) stencil: Switch,
|
||||
/// Keep the native Wayland backend instead of XWayland.
|
||||
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
|
||||
@@ -76,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
|
||||
@@ -96,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());
|
||||
@@ -144,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()));
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
//! Nightly-v1 bootstrap powered by `craft-nightly`: selected before logging, updates, fonts, or
|
||||
//! saved state. Direct nightly launches self-isolate into `craft_nightly::canonical_profile_root`,
|
||||
//! while explicit `--launch-profile nightly-v1 --profile-root <dir>` invocations keep their
|
||||
//! launcher-supplied root. Stable launches retain their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
craft_nightly::current().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
craft_nightly::prepare_launch(flavor, &crate::profile_root::spec(), args, &StartupOptions::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
|
||||
|
||||
use crate::profile_root::{APP_ID, spec};
|
||||
|
||||
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" }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_user_args() {
|
||||
let expected_root = canonical_profile_root(APP_ID).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), args(&["--sample", "plan.dxf"]), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(launch.passthrough_args, args(&["--sample", "plan.dxf"]));
|
||||
assert!(!launch.is_version_query());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_launcher_flags_override_canonical_root_and_forward_passthrough_args() {
|
||||
let argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "drawing with spaces.dxf"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), argv, &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.passthrough_args, args(&["drawing with spaces.dxf"]));
|
||||
assert!(!launch.is_version_query());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
|
||||
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec(), argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
}
|
||||
let nightly = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]);
|
||||
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec(), nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_nightly_flags_are_refused() {
|
||||
let s = spec();
|
||||
for argv in [
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
args(&["--new-window", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launcher_and_direct_version_queries_are_recognized() {
|
||||
let s = spec();
|
||||
for flag in ["--version", "-V"] {
|
||||
let direct = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap();
|
||||
assert!(direct.is_version_query(), "direct {flag}");
|
||||
|
||||
let launcher = parse_startup(
|
||||
BuildFlavor::NightlyV1,
|
||||
&s,
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]),
|
||||
&StartupOptions::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(launcher.is_version_query(), "launcher {flag}");
|
||||
}
|
||||
|
||||
let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
|
||||
assert!(!file_named_version.is_version_query());
|
||||
}
|
||||
}
|
||||
+82
-309
@@ -16,24 +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;
|
||||
mod renderer;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod sheet;
|
||||
mod single_instance;
|
||||
@@ -42,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};
|
||||
|
||||
@@ -62,6 +53,9 @@ struct App {
|
||||
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
menus_in_window: bool,
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
@@ -139,18 +133,17 @@ impl eframe::App for App {
|
||||
if std::mem::take(&mut self.cad.quit_requested) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
self.cad.close_path(ctx);
|
||||
}
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
|
||||
/// runtime.
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
follow_desktop(raw, self.desktop_theme.current());
|
||||
self.cad.raw_input_hook(ctx, raw);
|
||||
self.cad.before_input(ctx);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.cad.guarded_ui(ui);
|
||||
#[cfg(target_os = "macos")]
|
||||
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
|
||||
}
|
||||
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
|
||||
/// crash leaves them for recovery).
|
||||
@@ -158,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.
|
||||
@@ -183,17 +171,10 @@ pub fn install_io() {
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
});
|
||||
// The same writers, with what an image draws short of the drawing (dashed lines past the
|
||||
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
|
||||
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
|
||||
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
|
||||
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
|
||||
});
|
||||
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
@@ -204,7 +185,6 @@ pub fn install_io() {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -219,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,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(),
|
||||
@@ -240,38 +217,9 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Services::start_pick` for Linux and the BSDs: the blocking dialog runs on a thread of its
|
||||
/// own, so the window keeps answering the desktop while the dialog is open; `ui` is woken when
|
||||
/// it answers. If the thread cannot start, `done` is dropped unanswered and the app says the
|
||||
/// dialog could not be shown.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn start_pick(ui: egui::Context) -> cadcraft_ui_egui::StartPick {
|
||||
Box::new(move |pick, done| {
|
||||
let ui = ui.clone();
|
||||
// Here, not on the thread: the interface language is this thread's
|
||||
// (`i18n::with_language`), and the filter labels are translated.
|
||||
let filters = filters(&pick);
|
||||
let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || {
|
||||
let dialog = file_dialog_with(&pick, &filters);
|
||||
let picked = if matches!(pick, Pick::Save(_)) { dialog.save_file() } else { dialog.pick_file() };
|
||||
done(picked.map(|p| p.to_string_lossy().to_string()));
|
||||
ui.request_repaint();
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("file dialog: {e}");
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The blocking dialog for `pick` (Windows, Linux, FreeBSD).
|
||||
fn file_dialog(pick: &Pick) -> rfd::FileDialog {
|
||||
file_dialog_with(pick, &filters(pick))
|
||||
}
|
||||
|
||||
/// [`file_dialog`] offering `filters`, the file types of `pick` ([`filters`]) as the caller's
|
||||
/// thread names them.
|
||||
fn file_dialog_with(pick: &Pick, filters: &[(&'static str, Vec<&'static str>)]) -> rfd::FileDialog {
|
||||
let dialog = filters.iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
|
||||
let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
|
||||
match pick {
|
||||
Pick::Save(name) => dialog.set_file_name(name),
|
||||
Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir),
|
||||
@@ -302,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 };
|
||||
@@ -336,16 +283,18 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
|
||||
|
||||
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
|
||||
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
|
||||
/// its render pass (each attempt at starting the graphics sets its own, see [`renderer::apply`]).
|
||||
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
|
||||
let viewport = egui::ViewportBuilder::default()
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_app_id(os_window::app_id());
|
||||
/// its render pass ([`stencil_bits`]).
|
||||
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
|
||||
eframe::NativeOptions {
|
||||
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("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(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,
|
||||
@@ -362,9 +311,22 @@ fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui:
|
||||
}
|
||||
}
|
||||
|
||||
const APP_ID: &str = "ai.storyteller.cadcraft";
|
||||
|
||||
/// The key eframe saves the main window state under in its storage.
|
||||
const WINDOW_KEY: &str = "window";
|
||||
|
||||
/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`).
|
||||
const STENCIL_BITS: u8 = 8;
|
||||
|
||||
/// The stencil bits of the window's render pass: none when `CADCRAFT_STENCIL` is off. Some old
|
||||
/// drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a stencil pass without an
|
||||
/// error and then present a black window, so only an explicit opt-out drops it. Without a stencil
|
||||
/// buffer, clipped layout viewports draw unclipped.
|
||||
fn stencil_bits(stencil: Switch) -> u8 {
|
||||
if stencil == Switch::Off { 0 } else { STENCIL_BITS }
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -374,122 +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))
|
||||
}
|
||||
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
|
||||
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
|
||||
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("CADCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if 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 `-V`: answered before resolving a home directory, root validation,
|
||||
// process identity, logging, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
|
||||
return None;
|
||||
}
|
||||
let launch = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> --version` (or `-V`):
|
||||
// `craft_nightly::prepare_launch` leaves the filesystem untouched and installs no profile.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && launch.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
|
||||
return None;
|
||||
}
|
||||
let identity = if launch.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
|
||||
if let Err(error) = initialize_nightly_process_identity().map_err(|e| e.to_string()).and_then(|()| os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(launch.passthrough_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);
|
||||
@@ -499,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();
|
||||
@@ -528,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));
|
||||
}
|
||||
@@ -564,19 +396,18 @@ fn main() -> eframe::Result {
|
||||
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
|
||||
}
|
||||
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
|
||||
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
|
||||
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
|
||||
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
|
||||
let persistence_path = vars
|
||||
.portable_storage_file
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os("CADCRAFT_CONFIG_DIR").and_then(|_| vars.config_dir.as_ref().map(|d| d.join("app.ron"))));
|
||||
// The window's render pass and the canvas's pipelines must agree on it; a mismatch is a wgpu
|
||||
// validation error.
|
||||
let stencil = stencil_bits(vars.stencil);
|
||||
if stencil == 0 {
|
||||
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
|
||||
}
|
||||
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()), renderer::STENCIL_BITS, frame.as_ref())
|
||||
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);
|
||||
@@ -599,64 +430,44 @@ fn main() -> eframe::Result {
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if forced_x11 {
|
||||
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
|
||||
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
|
||||
// close request for the window instead, so it asks first, as the close button does.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
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);
|
||||
// Each attempt at starting the graphics sets its backends, adapter and stencil buffer, and a
|
||||
// failed one is followed by the next (see renderer.rs).
|
||||
let result = renderer::run_native(
|
||||
os_window::name_for(os_window::identity()),
|
||||
eframe::run_native(
|
||||
"CADCraft",
|
||||
options,
|
||||
vars.stencil,
|
||||
Box::new(move |cc, started| {
|
||||
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
|
||||
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")]
|
||||
if let Some(window) = cc.winit_window().cloned() {
|
||||
app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone()));
|
||||
}
|
||||
// On Linux and the BSDs the dialog is the desktop portal's, another process: waiting
|
||||
// for it in the event handler leaves the window unanswered for as long as it is open,
|
||||
// and the desktop then offers to force-quit the app.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
|
||||
}
|
||||
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
|
||||
if let Some(ui) = restored {
|
||||
app.ui = ui;
|
||||
}
|
||||
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);
|
||||
@@ -678,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");
|
||||
@@ -690,12 +498,13 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
app.session.set_lisp_support_dir(Some(support));
|
||||
}
|
||||
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
|
||||
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
|
||||
}
|
||||
// On the GPU with the window's stencil buffer, or on the CPU when the GPU refuses the canvas.
|
||||
started.install(&mut app, cc.wgpu_render_state.as_ref());
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, stencil));
|
||||
}
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
@@ -740,21 +549,17 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
menus_in_window: vars.no_native_menu == Switch::On,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events,
|
||||
}))
|
||||
}),
|
||||
);
|
||||
// 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::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
|
||||
use crate::renderer::STENCIL_BITS;
|
||||
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() {
|
||||
@@ -775,7 +580,7 @@ mod tests {
|
||||
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
|
||||
#[test]
|
||||
fn the_first_launch_opens_centred() {
|
||||
let o = window_options(false, STENCIL_BITS, None);
|
||||
let o = window_options(false, STENCIL_BITS);
|
||||
assert!(o.centered, "centred on launch");
|
||||
assert!(o.persist_window, "the window state is saved for the next launch");
|
||||
}
|
||||
@@ -783,31 +588,24 @@ mod tests {
|
||||
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
|
||||
#[test]
|
||||
fn a_saved_window_reopens_where_it_was() {
|
||||
let o = window_options(true, STENCIL_BITS, None);
|
||||
let o = window_options(true, STENCIL_BITS);
|
||||
assert!(!o.centered, "centring would move a restored window");
|
||||
assert!(o.persist_window);
|
||||
}
|
||||
|
||||
/// `CADCRAFT_STENCIL=0` (also `no`, `false`, any case) opens the window without a stencil
|
||||
/// buffer, and `1` keeps it on every attempt; unset, blank or anything else starts with one and
|
||||
/// lets a failed start drop it.
|
||||
/// buffer; unset, blank, `1` or anything else keeps it.
|
||||
#[test]
|
||||
fn the_stencil_buffer_follows_cadcraft_stencil() {
|
||||
let stencils = |value: Option<&str>| {
|
||||
fn the_stencil_buffer_is_dropped_only_when_asked() {
|
||||
let bits = |value: Option<&str>| {
|
||||
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(value).flatten().map(Into::into));
|
||||
let attempts = crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil);
|
||||
attempts.iter().map(|a| a.stencil).collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>()
|
||||
stencil_bits(vars.stencil)
|
||||
};
|
||||
for off in ["0", "no", "NO", "false", "False", " 0 "] {
|
||||
assert_eq!(stencils(Some(off)), [false], "{off:?}");
|
||||
assert_eq!(bits(Some(off)), 0, "{off:?}");
|
||||
}
|
||||
for on in ["1", "yes", "On"] {
|
||||
assert_eq!(stencils(Some(on)), [true], "{on:?}");
|
||||
}
|
||||
for unset in [None, Some(""), Some("8"), Some("maybe")] {
|
||||
assert_eq!(stencils(unset), [false, true], "{unset:?}");
|
||||
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(unset).flatten().map(Into::into));
|
||||
assert!(crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil)[0].stencil, "{unset:?}: the first has one");
|
||||
for on in [None, Some(""), Some("1"), Some("yes"), Some("8"), Some("maybe")] {
|
||||
assert_eq!(bits(on), STENCIL_BITS, "{on:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,8 +613,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_window_carries_the_chosen_stencil_bits() {
|
||||
for bits in [0, STENCIL_BITS] {
|
||||
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
|
||||
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
|
||||
assert_eq!(window_options(false, bits).stencil_buffer, bits);
|
||||
assert_eq!(window_options(true, bits).stencil_buffer, bits);
|
||||
}
|
||||
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
|
||||
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
|
||||
@@ -844,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]
|
||||
@@ -870,17 +657,3 @@ mod tests {
|
||||
assert_eq!(raw.system_theme, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refusal_dialog_tests {
|
||||
use super::refusal_dialog;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,9 +15,6 @@ pub struct NativeMenu {
|
||||
items: HashMap<String, (String, String, MenuItem)>,
|
||||
submenus: Vec<(String, Submenu)>,
|
||||
predefined: Vec<(&'static str, PredefinedMenuItem)>,
|
||||
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
|
||||
/// muda's predefined Quit ends the process through `terminate:` without asking.
|
||||
quit: MenuItem,
|
||||
language: &'static str,
|
||||
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
|
||||
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
|
||||
@@ -61,6 +58,7 @@ impl NativeMenu {
|
||||
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
|
||||
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
|
||||
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
|
||||
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
|
||||
];
|
||||
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
|
||||
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
|
||||
@@ -71,8 +69,6 @@ impl NativeMenu {
|
||||
let _ = app_menu.append(&PredefinedMenuItem::separator());
|
||||
}
|
||||
}
|
||||
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
|
||||
let _ = app_menu.append(&quit);
|
||||
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
|
||||
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
|
||||
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
|
||||
@@ -89,7 +85,6 @@ impl NativeMenu {
|
||||
items,
|
||||
submenus,
|
||||
predefined,
|
||||
quit,
|
||||
language,
|
||||
last_refresh: f64::NEG_INFINITY,
|
||||
recent: app.ui.recent_files.clone(),
|
||||
@@ -119,9 +114,7 @@ impl NativeMenu {
|
||||
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
|
||||
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
|
||||
while let Ok(ev) = self.events.try_recv() {
|
||||
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
|
||||
ctx.request_repaint();
|
||||
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if cmd == "ui.discord" {
|
||||
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
|
||||
} else {
|
||||
@@ -140,7 +133,6 @@ impl NativeMenu {
|
||||
for (label, item) in &self.predefined {
|
||||
item.set_text(i18n::tr(language, label));
|
||||
}
|
||||
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
|
||||
for (label, submenu) in &self.submenus {
|
||||
submenu.set_text(i18n::tr_menu(language, label));
|
||||
}
|
||||
@@ -156,8 +148,7 @@ impl NativeMenu {
|
||||
if cmd == menus::RECENT_CLEAR {
|
||||
continue;
|
||||
}
|
||||
let en = (typing && menus::edits_text(cmd))
|
||||
|| cadcraft_engine::find_command(cmd).is_none_or(|c| cadcraft_ui_egui::clipboard::offered(&app.session, c));
|
||||
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
|
||||
item.set_enabled(en);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
//! CADCraft's `craft-nightly` isolation specification: stable paths, environment fence,
|
||||
//! portable-mode markers, folder-only entries, and platform-specific forbidden roots.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
use crate::portable::PORTABLE_MARKER;
|
||||
|
||||
pub const APP_ID: &str = "cadcraft";
|
||||
|
||||
/// The app id eframe derives stable's storage folder from (`main.rs` `persistence_path`).
|
||||
const STABLE_PACKAGE_ID: &str = "ai.storyteller.cadcraft";
|
||||
|
||||
/// The app id of the nightly bundle (`packaging/linux/flatpak-bundle.sh`).
|
||||
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.cadcraft.nightly";
|
||||
|
||||
const STABLE_DIR_NAMES: &[&str] = &["CADCraft", "cadcraft"];
|
||||
const FORBIDDEN_ENV_VARS: &[&str] = &["CADCRAFT_CONFIG_DIR"];
|
||||
const PORTABLE_MARKERS: &[&str] = &[PORTABLE_MARKER];
|
||||
const FOLDER_ONLY_ENTRIES: &[&str] = &["autosave", "logs", "support", "single-instance", "plotters", "crash-reports"];
|
||||
|
||||
/// Builds CADCraft's `craft-nightly` isolation specification from the current process environment.
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with_env(|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
fn spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: "CADCraft",
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: STABLE_PACKAGE_ID,
|
||||
nightly_package_id: NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: FORBIDDEN_ENV_VARS,
|
||||
portable_markers: PORTABLE_MARKERS,
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots(&env),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// The MSI's per-machine install folder (`cadcraft.wxs`).
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(env, key) {
|
||||
roots.push(base.join("ArtCraft").join("CADCraft"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
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.
|
||||
if let Some(home) = non_empty_abs(env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.cadcraft"));
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if let Some(home) = non_empty_abs(env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.cadcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.cadcraft.savedState"));
|
||||
roots.push(home.join("Applications/CADCraft.app"));
|
||||
}
|
||||
roots.push(PathBuf::from("/Applications/CADCraft.app"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key).filter(|v| !v.is_empty())?;
|
||||
let path = PathBuf::from(value);
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
|
||||
use super::{
|
||||
APP_ID, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, PORTABLE_MARKERS, STABLE_DIR_NAMES, STABLE_PACKAGE_ID, spec,
|
||||
spec_with_env,
|
||||
};
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate = std::env::temp_dir().join(format!(
|
||||
"cadcraft-profile-spec-{}-{}-{label}",
|
||||
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 temp dir: {error}"),
|
||||
}
|
||||
};
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_preserves_cadcraft_isolation_constants_and_extra_forbidden_roots() {
|
||||
let mut env = BTreeMap::<String, OsString>::new();
|
||||
#[cfg(target_os = "windows")]
|
||||
env.insert("ProgramFiles".into(), OsString::from(r"C:\Program Files"));
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
env.insert("HOME".into(), OsString::from("/home/tester"));
|
||||
|
||||
let s = spec_with_env(|key| env.get(key).cloned());
|
||||
assert_eq!(s.app_id, APP_ID);
|
||||
assert_eq!(s.display_name, "CADCraft");
|
||||
assert_eq!(s.stable_dir_names, STABLE_DIR_NAMES);
|
||||
assert_eq!(s.stable_package_id, STABLE_PACKAGE_ID);
|
||||
assert_eq!(s.nightly_package_id, NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(s.profile_root_env, None);
|
||||
assert_eq!(s.forbidden_env_vars, FORBIDDEN_ENV_VARS);
|
||||
assert_eq!(s.portable_markers, PORTABLE_MARKERS);
|
||||
assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\CADCraft")));
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/cadcraft")));
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/local/bin/cadcraft")));
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/opt/cadcraft")));
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.cadcraft")));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Preferences/ai.storyteller.cadcraft.plist")));
|
||||
assert!(
|
||||
s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Saved Application State/ai.storyteller.cadcraft.savedState"))
|
||||
);
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Applications/CADCraft.app")));
|
||||
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/Applications/CADCraft.app")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
|
||||
let temp = TempDir::new("reopen");
|
||||
let private = temp.0.join("nightly-profile");
|
||||
let s = spec();
|
||||
|
||||
let canonical = validate_and_prepare_root(&private, &s).unwrap();
|
||||
assert_eq!(canonical, private);
|
||||
|
||||
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&private, &s).unwrap(), private);
|
||||
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening");
|
||||
}
|
||||
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(matches!(validate_and_prepare_root(&private, &s), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_directory_profile_stops_startup_without_installing_a_profile() {
|
||||
let temp = TempDir::new("invalid-root");
|
||||
let root = temp.0.join("ordinary-file");
|
||||
std::fs::write(&root, b"existing file").unwrap();
|
||||
let argv = craft_nightly::launch_arguments(&root, &[]);
|
||||
assert!(craft_nightly::current().is_none());
|
||||
let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv);
|
||||
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
|
||||
assert!(craft_nightly::current().is_none());
|
||||
assert_eq!(std::fs::read(root).unwrap(), b"existing file");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinks_inside_profile_root_are_refused() {
|
||||
let temp = TempDir::new("symlink");
|
||||
let outside = temp.0.join("outside");
|
||||
let private = temp.0.join("nightly-profile");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::create_dir_all(&private).unwrap();
|
||||
std::os::unix::fs::symlink(outside.join("target"), private.join("autosave")).unwrap();
|
||||
|
||||
let err = validate_and_prepare_root(&private, &spec()).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::SymlinkEntry(_)), "unexpected error: {err}");
|
||||
}
|
||||
}
|
||||
@@ -1,660 +0,0 @@
|
||||
//! Which renderer draws the window, and what the app does when one can't start.
|
||||
//!
|
||||
//! The window draws with wgpu (eframe is built with its `wgpu` renderer only). Where a start fails
|
||||
//! decides what is tried next:
|
||||
//!
|
||||
//! - The adapter, the device or the window's surface can't be made (no adapter for the backends, a
|
||||
//! device the driver refuses or loses): eframe returns `Error::Wgpu` before the app exists. The
|
||||
//! stencil buffer plays no part, so another adapter is tried.
|
||||
//! - The window's surface can't be configured, or egui's pipelines are refused: also before the app
|
||||
//! exists. The stencil buffer is part of both, so the same adapter is tried without it first.
|
||||
//! - The driver takes the stencil buffer and then draws nothing, with no error: Mesa's OpenGL on Ivy
|
||||
//! Bridge refuses `glTexStorage2D(GL_STENCIL_INDEX8)`, the frame buffer is incomplete and every
|
||||
//! frame comes out black (#1724). egui makes the window's stencil buffer a texture it can also
|
||||
//! sample, which wgpu's OpenGL backend stores with that call. Before the app is created, [`check`]
|
||||
//! clears a small target, without and then with a stencil buffer made the same way, and reads it
|
||||
//! back.
|
||||
//! - The canvas's own pipelines are refused: the canvas draws on the CPU ([`Started::install`]).
|
||||
//!
|
||||
//! Not caught: a driver that crashes the process or hangs, a black window whose offscreen check
|
||||
//! passes (a fault in presenting to the window), a failure after the app was created (an error
|
||||
//! then ends the start as before), and a panic inside eframe or egui-wgpu.
|
||||
//!
|
||||
//! The attempts, in order ([`attempts`]): the start as it always was (DirectX 12 alone on Windows,
|
||||
//! see `graphics.rs`; eframe's backends elsewhere); OpenGL alone, where those backends have it
|
||||
//! beside another; then those backends with a software adapter only (WARP, llvmpipe). Each is tried
|
||||
//! with a stencil buffer, then without. No attempt creates a backend the first one did not, so no
|
||||
//! driver code runs that the start did not run before: on Windows, where OpenGL is left out because
|
||||
//! an AMD driver crashes inside it (#31), the fallback is WARP. A start that works today makes only
|
||||
//! the first attempt, and the check.
|
||||
//!
|
||||
//! `WGPU_BACKEND` limits every attempt to its backends, and `CADCRAFT_STENCIL` fixes the stencil
|
||||
//! buffer. Nothing is remembered between starts: a failed attempt costs a fraction of a second, and
|
||||
//! a remembered choice would keep a lesser renderer after a failure that happened once.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
use cadcraft_ui_egui::switch::Switch;
|
||||
use eframe::egui_wgpu::{self, NativeAdapterSelectorMethod, WgpuError, WgpuSetup};
|
||||
use eframe::wgpu::{self, Backends, DeviceType};
|
||||
|
||||
/// Stencil bits of the window's render pass when an attempt has a stencil buffer (see
|
||||
/// `NativeOptions::stencil_buffer`).
|
||||
pub(crate) const STENCIL_BITS: u8 = 8;
|
||||
|
||||
/// How long [`check`] waits for its read-back. A slower answer counts as a pass: a busy GPU is no
|
||||
/// reason to fall back.
|
||||
const CHECK_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The width of [`check`]'s target: one row of RGBA8 pixels is then exactly the row alignment a
|
||||
/// copy to a buffer needs.
|
||||
const CHECK_WIDTH: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT / 4;
|
||||
|
||||
/// The colour [`check`] clears to, as it reads back: a new texture starts as zeros.
|
||||
const CHECK_COLOR: [u8; 4] = [255, 0, 255, 255];
|
||||
|
||||
type DynError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
/// Builds the app once an attempt's window draws.
|
||||
pub(crate) type Creator<'a> = Box<dyn FnOnce(&eframe::CreationContext<'_>, &Started) -> Result<Box<dyn eframe::App + 'a>, DynError> + 'a>;
|
||||
|
||||
/// The backends by name, for the log and the status bar.
|
||||
const NAMES: [(Backends, &str); 4] =
|
||||
[(Backends::DX12, "DirectX 12"), (Backends::METAL, "Metal"), (Backends::VULKAN, "Vulkan"), (Backends::GL, "OpenGL")];
|
||||
|
||||
/// One way to start the window's graphics.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Attempt {
|
||||
/// The backends wgpu chooses an adapter from.
|
||||
pub(crate) backends: Backends,
|
||||
/// Only a software adapter (WARP, llvmpipe); otherwise wgpu's choice, which prefers a GPU.
|
||||
pub(crate) software: bool,
|
||||
/// The window has a stencil buffer, which clips the contents of clipped layout viewports.
|
||||
pub(crate) stencil: bool,
|
||||
}
|
||||
|
||||
impl Attempt {
|
||||
/// The same adapter: an attempt that differs only in its stencil buffer.
|
||||
fn same_adapter(self, other: Attempt) -> bool {
|
||||
(self.backends, self.software) == (other.backends, other.software)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Attempt {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let backends: Vec<&str> = NAMES.iter().filter(|n| self.backends.contains(n.0)).map(|n| n.1).collect();
|
||||
f.write_str(&if backends.is_empty() { format!("{:?}", self.backends) } else { backends.join(" or ") })?;
|
||||
if self.software {
|
||||
f.write_str(" on a software adapter")?;
|
||||
}
|
||||
f.write_str(if self.stencil { "" } else { " without a stencil buffer" })
|
||||
}
|
||||
}
|
||||
|
||||
/// The attempts in order (see the module docs). `first`: the backends the start is configured with;
|
||||
/// `requested`: they are `WGPU_BACKEND`'s, which every attempt keeps; `stencil`: `CADCRAFT_STENCIL`.
|
||||
pub(crate) fn attempts(first: Backends, requested: bool, stencil: Switch) -> Vec<Attempt> {
|
||||
let mut adapters = vec![(first, false)];
|
||||
if !requested && first.contains(Backends::GL) && first != Backends::GL {
|
||||
adapters.push((Backends::GL, false));
|
||||
}
|
||||
adapters.push((first, true));
|
||||
let stencils: &[bool] = match stencil {
|
||||
Switch::On => &[true],
|
||||
Switch::Off => &[false],
|
||||
Switch::Default => &[true, false],
|
||||
};
|
||||
adapters.into_iter().flat_map(|(backends, software)| stencils.iter().map(move |&stencil| Attempt { backends, software, stencil })).collect()
|
||||
}
|
||||
|
||||
/// What a failed attempt says about the attempts after it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Failure {
|
||||
/// The adapter, the device or the surface couldn't be made, or nothing was drawn: the same
|
||||
/// adapter without a stencil buffer fails the same way.
|
||||
Adapter,
|
||||
/// Something the stencil buffer is part of failed: the same adapter without one may work.
|
||||
Stencil,
|
||||
}
|
||||
|
||||
/// The attempt to try after the one at `at` failed with `failure`: the next one after a stencil
|
||||
/// failure, else the next on another adapter.
|
||||
pub(crate) fn next(attempts: &[Attempt], at: usize, failure: Failure) -> Option<usize> {
|
||||
let failed = *attempts.get(at)?;
|
||||
attempts.iter().enumerate().skip(at + 1).find(|(_, a)| failure == Failure::Stencil || !a.same_adapter(failed)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// What `error` from `eframe::run_native` says about the attempt: `None` when it isn't the graphics
|
||||
/// (the app's own start, the windowing system).
|
||||
pub(crate) fn classify(error: &eframe::Error) -> Option<Failure> {
|
||||
match error {
|
||||
eframe::Error::Wgpu(WgpuError::ConfigureSurface(_) | WgpuError::CreateRenderer(_)) => Some(Failure::Stencil),
|
||||
eframe::Error::Wgpu(_) => Some(Failure::Adapter),
|
||||
eframe::Error::AppCreation(error) => error.downcast_ref::<CheckFailed>().map(|c| c.failure),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The attempt to try after the one at `at` ended with `error`: none once the app was `created`,
|
||||
/// since a failure after that is no start failure (and the app can't be built twice), and none for
|
||||
/// an error that isn't the graphics'.
|
||||
pub(crate) fn retry(attempts: &[Attempt], at: usize, created: bool, error: &eframe::Error) -> Option<usize> {
|
||||
if created {
|
||||
return None;
|
||||
}
|
||||
next(attempts, at, classify(error)?)
|
||||
}
|
||||
|
||||
/// [`check`] found that the window can't draw. Returned from the app creator, it ends the attempt
|
||||
/// before the app exists.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CheckFailed {
|
||||
failure: Failure,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CheckFailed {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CheckFailed {}
|
||||
|
||||
/// Clear a small target and read it back: as it is, then with a stencil buffer of `stencil`, made
|
||||
/// as egui makes the window's (see the module docs). A target that doesn't come back cleared is a
|
||||
/// [`Failure::Adapter`] without the stencil buffer and a [`Failure::Stencil`] with it.
|
||||
pub(crate) fn check(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
|
||||
passes(stencil, |format| clear_and_read(device, queue, format))
|
||||
}
|
||||
|
||||
/// [`check`]'s passes, each made by `pass` with or without the stencil buffer: what failed names
|
||||
/// the [`Failure`], and a device that didn't answer the first pass isn't waited for a second time.
|
||||
fn passes(
|
||||
stencil: Option<wgpu::TextureFormat>,
|
||||
mut pass: impl FnMut(Option<wgpu::TextureFormat>) -> Result<bool, String>,
|
||||
) -> Result<(), CheckFailed> {
|
||||
let failed = |failure: Failure| move |message: String| CheckFailed { failure, message };
|
||||
let answered = pass(None).map_err(failed(Failure::Adapter))?;
|
||||
match stencil {
|
||||
Some(format) if answered => pass(Some(format)).map(|_| ()).map_err(failed(Failure::Stencil)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass of [`check`]: `Err` names what came back instead of [`CHECK_COLOR`]; `Ok(false)`: no
|
||||
/// answer came, which counts as a pass.
|
||||
fn clear_and_read(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<bool, String> {
|
||||
let size = wgpu::Extent3d { width: CHECK_WIDTH, height: 1, depth_or_array_layers: 1 };
|
||||
let row = CHECK_WIDTH * 4;
|
||||
let submitted = pollster::block_on(egui_wgpu::winit::catch_errors(device, || {
|
||||
let texture = |format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("startup check"),
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let color = texture(wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
|
||||
// The usage egui gives the window's depth and stencil texture.
|
||||
let depth = stencil.map(|format| texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING));
|
||||
let color_view = color.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let depth_view = depth.as_ref().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("startup check"),
|
||||
size: u64::from(row),
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
|
||||
let [r, g, b, a] = CHECK_COLOR.map(|c| f64::from(c) / 255.0);
|
||||
drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("startup check"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &color_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }), store: wgpu::StoreOp::Store },
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: depth_view.as_ref().zip(stencil).map(|(view, format)| wgpu::RenderPassDepthStencilAttachment {
|
||||
view,
|
||||
depth_ops: format.has_depth_aspect().then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
|
||||
}),
|
||||
..Default::default()
|
||||
}));
|
||||
encoder.copy_texture_to_buffer(
|
||||
color.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None },
|
||||
},
|
||||
size,
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
buffer
|
||||
}));
|
||||
let buffer = submitted.map_err(|e| format!("the device refused the check: {e}"))?;
|
||||
let (send, mapped) = std::sync::mpsc::channel();
|
||||
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = send.send(result);
|
||||
});
|
||||
match device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(CHECK_TIMEOUT) }) {
|
||||
Ok(_) => {}
|
||||
Err(wgpu::PollError::Timeout) => {
|
||||
log::warn!("graphics: the start-up check had no answer after {CHECK_TIMEOUT:?}; taken as passed");
|
||||
return Ok(false);
|
||||
}
|
||||
Err(e) => return Err(format!("waiting for the check failed: {e}")),
|
||||
}
|
||||
match mapped.try_recv() {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => return Err(format!("the check could not be read back: {e}")),
|
||||
Err(_) => {
|
||||
log::warn!("graphics: the start-up check was not read back; taken as passed");
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
let pixels = buffer.slice(..).get_mapped_range().map_err(|e| format!("the check could not be read back: {e}"))?;
|
||||
read_back(&pixels).map(|()| true)
|
||||
}
|
||||
|
||||
/// Whether the row [`check`] read back is [`CHECK_COLOR`] throughout, within what a driver's
|
||||
/// rounding could change.
|
||||
fn read_back(pixels: &[u8]) -> Result<(), String> {
|
||||
let row = CHECK_WIDTH as usize * CHECK_COLOR.len();
|
||||
let cleared = |p: &[u8; CHECK_COLOR.len()]| p.iter().zip(CHECK_COLOR).all(|(&p, c)| p.abs_diff(c) <= 8);
|
||||
match pixels.as_chunks::<{ CHECK_COLOR.len() }>().0.iter().find(|&p| !cleared(p)) {
|
||||
Some(p) => Err(format!("a cleared target read back {p:?}, not {CHECK_COLOR:?}")),
|
||||
None if pixels.len() == row => Ok(()),
|
||||
None => Err(format!("the check read back {} bytes, not {row}", pixels.len())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `options` for `attempt`: its backends, its adapter and its stencil buffer.
|
||||
pub(crate) fn apply(options: &mut eframe::NativeOptions, attempt: Attempt) {
|
||||
options.stencil_buffer = if attempt.stencil { STENCIL_BITS } else { 0 };
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.instance_descriptor.backends = attempt.backends;
|
||||
create.native_adapter_selector = attempt.software.then(|| Arc::new(software_adapter) as NativeAdapterSelectorMethod);
|
||||
}
|
||||
}
|
||||
|
||||
/// A software adapter of `adapters` that can show `surface`.
|
||||
fn software_adapter(adapters: &[wgpu::Adapter], surface: Option<&wgpu::Surface<'_>>) -> Result<wgpu::Adapter, String> {
|
||||
adapters
|
||||
.iter()
|
||||
.find(|a| a.get_info().device_type == DeviceType::Cpu && surface.is_none_or(|s| a.is_surface_supported(s)))
|
||||
.cloned()
|
||||
.ok_or_else(|| "no software adapter can show the window".to_owned())
|
||||
}
|
||||
|
||||
/// Run eframe with each attempt in turn until one starts the window, then build the app with
|
||||
/// `create`. `options` are as configured (their backends are `WGPU_BACKEND`'s or the platform's),
|
||||
/// `stencil` is `CADCRAFT_STENCIL`. A failed attempt is dropped with its window before any app
|
||||
/// exists; an error once the app was created ends the start, as before. When every attempt failed,
|
||||
/// the first one's error is returned: it is the one the start as it always was would have given.
|
||||
pub(crate) fn run_native(name: &str, options: eframe::NativeOptions, stencil: Switch, create: Creator<'_>) -> eframe::Result {
|
||||
let requested = Backends::from_env().is_some();
|
||||
let configured = match &options.wgpu_options.wgpu_setup {
|
||||
WgpuSetup::CreateNew(create) => create.instance_descriptor.backends,
|
||||
WgpuSetup::Existing(_) => Backends::all(),
|
||||
};
|
||||
// Only what this build has, so no attempt asks for a backend that can't be there.
|
||||
let first = if requested { configured } else { configured & wgpu::Instance::enabled_backend_features() };
|
||||
let attempts = attempts(first, requested, stencil);
|
||||
// Later attempts reuse eframe's event loop, so the hooks a clone drops aren't needed again.
|
||||
let template = options.clone();
|
||||
let mut options = Some(options);
|
||||
let mut create = Some(create);
|
||||
let mut first_failure = None;
|
||||
let mut why = None;
|
||||
let mut at = 0;
|
||||
while let Some(&attempt) = attempts.get(at) {
|
||||
let mut attempt_options = options.take().unwrap_or_else(|| template.clone());
|
||||
apply(&mut attempt_options, attempt);
|
||||
fault::refuse_adapter(&mut attempt_options, at);
|
||||
log::info!("graphics: starting with {attempt} (attempt {} of {})", at + 1, attempts.len());
|
||||
let started = Started { attempt, index: at, why: why.clone() };
|
||||
let slot = &mut create;
|
||||
let result = eframe::run_native(
|
||||
name,
|
||||
attempt_options,
|
||||
Box::new(|cc| {
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
fault::check(started.index, started.stencil_format())?;
|
||||
let checking = std::time::Instant::now();
|
||||
check(&rs.device, &rs.queue, started.stencil_format())?;
|
||||
log::info!("graphics: the start-up check passed in {:.1?}", checking.elapsed());
|
||||
}
|
||||
let create = slot.take().ok_or("the app was already created")?;
|
||||
create(cc, &started)
|
||||
}),
|
||||
);
|
||||
let Err(error) = result else { return Ok(()) };
|
||||
let Some(after) = retry(&attempts, at, create.is_none(), &error) else {
|
||||
if create.is_none() || classify(&error).is_none() {
|
||||
return Err(error);
|
||||
}
|
||||
log::error!("graphics: {attempt} failed: {error}; no other renderer is left to try");
|
||||
return Err(first_failure.unwrap_or(error));
|
||||
};
|
||||
log::warn!("graphics: {attempt} failed: {error}; trying the next renderer");
|
||||
// The first failure says why the first choice isn't drawing; the log has the others.
|
||||
why.get_or_insert_with(|| format!("{attempt} failed: {}", error.to_string().lines().next().unwrap_or_default()));
|
||||
first_failure.get_or_insert(error);
|
||||
at = after;
|
||||
}
|
||||
Err(first_failure.unwrap_or_else(|| eframe::Error::AppCreation("no renderer to start the window with".into())))
|
||||
}
|
||||
|
||||
/// The attempt that started the window, handed to the app creator.
|
||||
pub(crate) struct Started {
|
||||
attempt: Attempt,
|
||||
/// Its position in [`attempts`].
|
||||
index: usize,
|
||||
/// Why the first attempt isn't the one drawing.
|
||||
why: Option<String>,
|
||||
}
|
||||
|
||||
impl Started {
|
||||
/// The format of the window's stencil buffer, which the canvas's pipelines must match.
|
||||
fn stencil_format(&self) -> Option<wgpu::TextureFormat> {
|
||||
egui_wgpu::depth_format_from_bits(0, if self.attempt.stencil { STENCIL_BITS } else { 0 })
|
||||
}
|
||||
|
||||
/// Draw the canvas on the GPU with the window's render state `rs`, or on the CPU when its
|
||||
/// pipelines are refused. Logs which renderer draws, and says in the status bar why when it is
|
||||
/// not the first choice (unless the start already put something there).
|
||||
pub(crate) fn install(&self, app: &mut CadApp, rs: Option<&egui_wgpu::RenderState>) {
|
||||
let Some(rs) = rs else { return };
|
||||
let stencil = self.stencil_format();
|
||||
let installed = pollster::block_on(egui_wgpu::winit::catch_errors(&rs.device, || app.set_wgpu(rs, stencil)));
|
||||
let canvas_failed = match installed {
|
||||
Err(e) => Some(e.to_string()),
|
||||
Ok(()) => fault::canvas(self.index),
|
||||
};
|
||||
if canvas_failed.is_some() {
|
||||
app.canvas.gpu = None;
|
||||
app.canvas.gpu_device = None;
|
||||
}
|
||||
let info = rs.adapter.get_info();
|
||||
log::info!(
|
||||
"graphics: {} draws the window on {} ({:?}, {:?}, driver {}); the canvas draws on the {}",
|
||||
self.attempt,
|
||||
info.name.trim(),
|
||||
info.backend,
|
||||
info.device_type,
|
||||
[info.driver.trim(), info.driver_info.trim()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" "),
|
||||
if canvas_failed.is_some() { "CPU" } else { "GPU" }
|
||||
);
|
||||
if !self.attempt.stencil {
|
||||
log::warn!("graphics: no stencil buffer: clipped layout viewports draw unclipped");
|
||||
}
|
||||
let note = match (&self.why, &canvas_failed) {
|
||||
(_, Some(error)) => {
|
||||
Some(cadcraft_ui_egui::tf!("Graphics: the drawing area draws on the CPU, because the GPU refused it: {error}", error = error))
|
||||
}
|
||||
(Some(why), None) => Some(cadcraft_ui_egui::tf!("Graphics: drawing with {renderer}, because {why}", renderer = self.attempt, why = why)),
|
||||
(None, None) => None,
|
||||
};
|
||||
if let Some(note) = note {
|
||||
log::warn!("{note}");
|
||||
if app.status.is_none() {
|
||||
app.set_status(note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A test switch read only by debug builds: `CADCRAFT_GRAPHICS_FAULT=<attempt>:<step>[,...]` fails
|
||||
/// the attempt at that position in [`attempts`] (from 0) at `adapter` (its adapter is refused),
|
||||
/// `draw` or `stencil` ([`check`]'s pass without or with the stencil buffer), or `canvas` (the
|
||||
/// canvas's pipelines), so each fallback can be run on a machine whose graphics work.
|
||||
mod fault {
|
||||
use super::{Arc, CheckFailed, Failure, NativeAdapterSelectorMethod, WgpuSetup, wgpu};
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn asked(index: usize, step: &str) -> bool {
|
||||
listed(std::env::var("CADCRAFT_GRAPHICS_FAULT").ok().as_deref(), index, step)
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
fn asked(_index: usize, _step: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `value` lists `<index>:<step>`.
|
||||
#[cfg(any(debug_assertions, test))]
|
||||
pub(super) fn listed(value: Option<&str>, index: usize, step: &str) -> bool {
|
||||
value.is_some_and(|v| v.split(',').any(|f| f.trim().split_once(':') == Some((index.to_string().as_str(), step))))
|
||||
}
|
||||
|
||||
pub(super) fn refuse_adapter(options: &mut eframe::NativeOptions, index: usize) {
|
||||
if asked(index, "adapter")
|
||||
&& let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
|
||||
{
|
||||
let refuse = |_: &[wgpu::Adapter], _: Option<&wgpu::Surface<'_>>| Err("refused by CADCRAFT_GRAPHICS_FAULT".to_owned());
|
||||
create.native_adapter_selector = Some(Arc::new(refuse) as NativeAdapterSelectorMethod);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn check(index: usize, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
|
||||
let fail = |failure, step| CheckFailed { failure, message: format!("the {step} check failed (CADCRAFT_GRAPHICS_FAULT)") };
|
||||
if asked(index, "draw") {
|
||||
return Err(fail(Failure::Adapter, "draw"));
|
||||
}
|
||||
if stencil.is_some() && asked(index, "stencil") {
|
||||
return Err(fail(Failure::Stencil, "stencil"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn canvas(index: usize) -> Option<String> {
|
||||
asked(index, "canvas").then(|| "refused by CADCRAFT_GRAPHICS_FAULT".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ANY: Backends = Backends::VULKAN.union(Backends::GL);
|
||||
|
||||
/// A short name of `attempt`, to read the order in the asserts.
|
||||
fn key(attempt: &Attempt) -> String {
|
||||
let short = [(Backends::DX12, "dx12"), (Backends::METAL, "metal"), (Backends::VULKAN, "vulkan"), (Backends::GL, "gl")];
|
||||
let mut key = short.iter().filter(|(b, _)| attempt.backends.contains(*b)).map(|(_, n)| *n).collect::<Vec<_>>().join("+");
|
||||
if attempt.software {
|
||||
key.push_str(" software");
|
||||
}
|
||||
if !attempt.stencil {
|
||||
key.push_str(" no-stencil");
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
fn keys(list: &[Attempt]) -> Vec<String> {
|
||||
list.iter().map(key).collect()
|
||||
}
|
||||
|
||||
/// The first attempt is the start as it always was; OpenGL alone comes only where it was one of
|
||||
/// several, then the same backends on a software adapter, each with and then without a stencil
|
||||
/// buffer. `WGPU_BACKEND` keeps its backends on every attempt, and `CADCRAFT_STENCIL` its choice.
|
||||
#[test]
|
||||
fn the_attempts_begin_with_the_start_as_it_was_and_keep_explicit_choices() {
|
||||
let linux = attempts(ANY, false, Switch::Default);
|
||||
assert_eq!(keys(&linux), ["vulkan+gl", "vulkan+gl no-stencil", "gl", "gl no-stencil", "vulkan+gl software", "vulkan+gl software no-stencil"]);
|
||||
// Windows: DirectX 12 alone (graphics.rs), so the fallback never creates OpenGL there.
|
||||
let windows = attempts(Backends::DX12, false, Switch::Default);
|
||||
assert_eq!(keys(&windows), ["dx12", "dx12 no-stencil", "dx12 software", "dx12 software no-stencil"]);
|
||||
// WGPU_BACKEND=vulkan,gl: no attempt leaves its backends.
|
||||
assert!(attempts(ANY, true, Switch::Default).iter().all(|a| a.backends == ANY));
|
||||
assert_eq!(attempts(Backends::GL, false, Switch::Default).len(), 4, "OpenGL alone is already the first");
|
||||
// CADCRAFT_STENCIL: off is never on, on is never dropped.
|
||||
assert!(attempts(ANY, false, Switch::Off).iter().all(|a| !a.stencil));
|
||||
assert!(attempts(ANY, false, Switch::On).iter().all(|a| a.stencil));
|
||||
assert_eq!(attempts(ANY, false, Switch::On).len() * 2, linux.len());
|
||||
}
|
||||
|
||||
/// A stencil failure tries the same adapter without the stencil buffer; any other failure skips
|
||||
/// that twin and tries the next adapter; past the last there is nothing.
|
||||
#[test]
|
||||
fn a_failure_picks_the_next_attempt_by_what_failed() {
|
||||
let list = attempts(ANY, false, Switch::Default);
|
||||
let at = |k: &str| list.iter().position(|a| key(a) == k).unwrap();
|
||||
let next_key = |from: &str, failure| next(&list, at(from), failure).map(|i| key(&list[i]));
|
||||
assert_eq!(next_key("vulkan+gl", Failure::Stencil).as_deref(), Some("vulkan+gl no-stencil"));
|
||||
assert_eq!(next_key("vulkan+gl", Failure::Adapter).as_deref(), Some("gl"));
|
||||
assert_eq!(next_key("vulkan+gl no-stencil", Failure::Adapter).as_deref(), Some("gl"));
|
||||
assert_eq!(next_key("gl no-stencil", Failure::Stencil).as_deref(), Some("vulkan+gl software"));
|
||||
assert_eq!(next_key("vulkan+gl software", Failure::Adapter), None);
|
||||
assert_eq!(next_key("vulkan+gl software no-stencil", Failure::Stencil), None);
|
||||
assert_eq!(next(&list, list.len(), Failure::Stencil), None);
|
||||
// CADCRAFT_STENCIL=1: a stencil failure has no twin to fall back to, so the next adapter.
|
||||
let on = attempts(Backends::DX12, false, Switch::On);
|
||||
assert_eq!(next(&on, 0, Failure::Stencil), Some(1));
|
||||
assert!(on[1].software);
|
||||
}
|
||||
|
||||
/// Errors before the app exists are graphics failures; which kind decides the next attempt. The
|
||||
/// app's own errors and the windowing system's are not, so they end the start as before.
|
||||
#[test]
|
||||
fn start_errors_are_sorted_by_what_failed() {
|
||||
let no_adapter = eframe::Error::Wgpu(WgpuError::CustomNativeAdapterSelectionError("none".into()));
|
||||
assert_eq!(classify(&no_adapter), Some(Failure::Adapter));
|
||||
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable)), Some(Failure::Adapter));
|
||||
let refused = || wgpu::Error::Validation { source: Box::new(std::fmt::Error), description: "refused".into() };
|
||||
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::ConfigureSurface(refused()))), Some(Failure::Stencil));
|
||||
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::CreateRenderer(refused()))), Some(Failure::Stencil));
|
||||
for failure in [Failure::Adapter, Failure::Stencil] {
|
||||
let failed = eframe::Error::AppCreation(Box::new(CheckFailed { failure, message: "black".into() }));
|
||||
assert_eq!(classify(&failed), Some(failure));
|
||||
}
|
||||
assert_eq!(classify(&eframe::Error::AppCreation("the app's own start".into())), None);
|
||||
}
|
||||
|
||||
/// Only a graphics failure before the app exists is retried: once the app was created an error
|
||||
/// ends the start (the app can't be built twice), as does an error that isn't the graphics'.
|
||||
#[test]
|
||||
fn only_a_start_failure_before_the_app_exists_is_retried() {
|
||||
let list = attempts(Backends::DX12, false, Switch::Default);
|
||||
let gpu = eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable);
|
||||
assert_eq!(retry(&list, 0, false, &gpu), Some(2));
|
||||
assert_eq!(retry(&list, 0, true, &gpu), None);
|
||||
let black = eframe::Error::AppCreation(Box::new(CheckFailed { failure: Failure::Stencil, message: "black".into() }));
|
||||
assert_eq!(retry(&list, 0, false, &black), Some(1));
|
||||
assert_eq!(retry(&list, 0, false, &eframe::Error::AppCreation("the app's own start".into())), None);
|
||||
}
|
||||
|
||||
/// Each attempt takes its backends, its adapter and its stencil buffer.
|
||||
#[test]
|
||||
fn an_attempt_sets_its_backends_adapter_and_stencil_buffer() {
|
||||
let mut options = eframe::NativeOptions::default();
|
||||
for attempt in attempts(Backends::VULKAN | Backends::GL, false, Switch::Default) {
|
||||
apply(&mut options, attempt);
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
|
||||
assert_eq!(create.instance_descriptor.backends, attempt.backends);
|
||||
assert_eq!(create.native_adapter_selector.is_some(), attempt.software, "{attempt}");
|
||||
assert_eq!(options.stencil_buffer > 0, attempt.stencil, "{attempt}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The read-back is answered and passes on a working device, with and without a stencil
|
||||
/// buffer. The device is made as the app makes it: on Windows DirectX 12 alone with FXC
|
||||
/// (graphics.rs; an AMD driver crashes when OpenGL is created there, #31), and egui's limits for
|
||||
/// the adapter.
|
||||
#[test]
|
||||
fn the_check_passes_on_a_device_that_draws() {
|
||||
let mut options = eframe::NativeOptions::default();
|
||||
crate::graphics::configure(&mut options, if cfg!(windows) { None } else { Some(Backends::all()) }, None);
|
||||
let WgpuSetup::CreateNew(mut create) = options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
|
||||
create.instance_descriptor.backends.remove(Backends::BROWSER_WEBGPU);
|
||||
let setup = WgpuSetup::CreateNew(create);
|
||||
let instance = pollster::block_on(setup.new_instance());
|
||||
let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() };
|
||||
let Ok(rs) = pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, Default::default())) else {
|
||||
eprintln!("no graphics adapter here: the device check is left to machines with one");
|
||||
return;
|
||||
};
|
||||
let info = rs.adapter.get_info();
|
||||
for stencil in [None, Some(wgpu::TextureFormat::Stencil8)] {
|
||||
// `check` takes no answer as a pass; a working device must answer, or every start on it
|
||||
// would wait for the timeout.
|
||||
let started = std::time::Instant::now();
|
||||
let read = clear_and_read(&rs.device, &rs.queue, stencil);
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(read, Ok(true), "{stencil:?} on {} ({:?}, {:?}) after {elapsed:?}", info.name, info.backend, info.device_type);
|
||||
}
|
||||
}
|
||||
|
||||
/// The read-back passes only when every pixel came back cleared: a target the clear never
|
||||
/// reached still holds the zeros a texture starts as.
|
||||
#[test]
|
||||
fn the_check_fails_a_target_the_clear_did_not_reach() {
|
||||
let row = |pixel: [u8; 4]| pixel.repeat(CHECK_WIDTH as usize);
|
||||
assert!(read_back(&row(CHECK_COLOR)).is_ok());
|
||||
assert!(read_back(&row([250, 6, 251, 255])).is_ok(), "a driver's rounding");
|
||||
assert!(read_back(&row([0, 0, 0, 0])).is_err(), "never cleared");
|
||||
assert!(read_back(&row([255, 0, 255, 0])).is_err(), "another alpha");
|
||||
let mut one_off = row(CHECK_COLOR);
|
||||
one_off[CHECK_COLOR.len() * 7 + 1] = 200;
|
||||
assert!(read_back(&one_off).is_err(), "one pixel the clear missed");
|
||||
assert!(read_back(&row(CHECK_COLOR)[..8]).is_err(), "a short read");
|
||||
assert!(read_back(&[]).is_err());
|
||||
}
|
||||
|
||||
/// A target that didn't come back cleared blames the adapter without the stencil buffer and the
|
||||
/// stencil buffer with it; no answer is a pass, and isn't waited for twice.
|
||||
#[test]
|
||||
fn a_failed_pass_names_what_failed() {
|
||||
let stencil = Some(wgpu::TextureFormat::Stencil8);
|
||||
let failure = |black_with: Option<bool>| {
|
||||
passes(stencil, |format| if black_with.is_none_or(|with| with == format.is_some()) { Err("black".into()) } else { Ok(true) })
|
||||
.map_err(|e| e.failure)
|
||||
};
|
||||
assert_eq!(failure(Some(false)), Err(Failure::Adapter), "black without the stencil buffer");
|
||||
assert_eq!(failure(None), Err(Failure::Adapter), "black either way");
|
||||
assert_eq!(failure(Some(true)), Err(Failure::Stencil), "black only with it");
|
||||
let mut asked = Vec::new();
|
||||
let unanswered = passes(stencil, |format| {
|
||||
asked.push(format);
|
||||
Ok(false)
|
||||
});
|
||||
assert!(unanswered.is_ok());
|
||||
assert_eq!(asked, [None], "no second wait after no answer");
|
||||
let mut asked = Vec::new();
|
||||
let answered = passes(stencil, |format| {
|
||||
asked.push(format);
|
||||
Ok(true)
|
||||
});
|
||||
assert!(answered.is_ok());
|
||||
assert_eq!(asked, [None, stencil], "both passes when the first answered");
|
||||
}
|
||||
|
||||
/// The test switch names attempts by position and step, and nothing else trips it.
|
||||
#[test]
|
||||
fn the_fault_switch_names_one_step_of_one_attempt() {
|
||||
assert!(fault::listed(Some("0:stencil"), 0, "stencil"));
|
||||
assert!(fault::listed(Some(" 2:adapter , 0:draw"), 0, "draw"));
|
||||
assert!(!fault::listed(Some("0:stencil"), 1, "stencil"));
|
||||
assert!(!fault::listed(Some("10:draw"), 1, "draw"));
|
||||
assert!(!fault::listed(Some("0:stencils"), 0, "stencil"));
|
||||
assert!(!fault::listed(None, 0, "draw"));
|
||||
}
|
||||
|
||||
/// The log and the status bar tell the attempts apart.
|
||||
#[test]
|
||||
fn an_attempt_names_what_it_tries() {
|
||||
let list = attempts(ANY, false, Switch::Default);
|
||||
let names: std::collections::BTreeSet<String> = list.iter().map(ToString::to_string).collect();
|
||||
assert_eq!(names.len(), list.len());
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -428,62 +423,4 @@ mod tests {
|
||||
received.sort();
|
||||
assert_eq!(received, handed);
|
||||
}
|
||||
|
||||
/// A Nightly profile on Windows keeps its single-instance AF_UNIX socket under
|
||||
/// `<profile>\single-instance\*.sock`. Both a live socket (while a first Nightly copy is
|
||||
/// running and a second document launch prepares to hand off) and a leftover/stale socket
|
||||
/// (after the first copy exits, or from an earlier Nightly build) must pass profile
|
||||
/// validation, and the next launch must reclaim the stale socket and accept subsequent
|
||||
/// document handoffs.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn nightly_profile_allows_live_and_stale_single_instance_socket_for_handoff_and_reopen() {
|
||||
use std::ffi::OsString;
|
||||
|
||||
use craft_nightly::{BuildFlavor, Profile, StartupOptions, launch_arguments, parse_startup, validate_and_prepare_root};
|
||||
|
||||
let profile = std::env::temp_dir().join(format!("cc-ni-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&profile);
|
||||
std::fs::create_dir_all(&profile).unwrap();
|
||||
let _cleanup = Cleanup(profile.clone());
|
||||
|
||||
let spec = crate::profile_root::spec();
|
||||
let prepare_profile = |doc: &str| {
|
||||
let argv = launch_arguments(&profile, &[OsString::from(doc)]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
let Profile::NightlyV1(root) = launch.profile else {
|
||||
panic!("expected NightlyV1 profile");
|
||||
};
|
||||
validate_and_prepare_root(&root, &spec).unwrap();
|
||||
launch.passthrough_args
|
||||
};
|
||||
|
||||
let sock_path = socket_path(Some(&profile)).unwrap();
|
||||
std::fs::create_dir_all(sock_path.parent().unwrap()).unwrap();
|
||||
if !can_bind(&sock_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Live socket in `<profile>\single-instance\*.sock`: second-document launch must not
|
||||
// be refused by profile validation before handoff.
|
||||
let listener = uds_windows::UnixListener::bind(&sock_path).unwrap();
|
||||
assert_eq!(prepare_profile("second.dwg"), [OsString::from("second.dwg")]);
|
||||
|
||||
// 2. First instance exits leaving a leftover/stale socket behind: reopening must pass
|
||||
// profile validation and reclaim the socket as the new primary instance.
|
||||
drop(listener);
|
||||
assert!(sock_path.exists(), "stale socket remains after exit");
|
||||
assert_eq!(prepare_profile("reopen.dwg"), [OsString::from("reopen.dwg")]);
|
||||
let Claim::Primary(server) = claim(&[], false, Some(&profile)) else {
|
||||
panic!("failed to reclaim stale single-instance socket in nightly profile");
|
||||
};
|
||||
|
||||
// 3. While the reclaimed primary instance is running (socket + election lock both live in
|
||||
// `<profile>\single-instance`), launching a second document passes profile validation
|
||||
// and hands off to the running instance.
|
||||
let second_doc = profile.join("second.dwg").to_string_lossy().into_owned();
|
||||
assert_eq!(prepare_profile(&second_doc), [OsString::from(&second_doc)]);
|
||||
assert!(matches!(claim(std::slice::from_ref(&second_doc), true, Some(&profile)), Claim::HandedOff));
|
||||
assert_eq!(server.take_paths(), [PathBuf::from(&second_doc)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ mod tests {
|
||||
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
|
||||
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
|
||||
ui.docking = app.ui.docking;
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
|
||||
ui.show_toolsets = false;
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||
@@ -263,9 +263,9 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
|
||||
assert!(!reloaded.show_toolsets);
|
||||
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
|
||||
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
|
||||
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
|
||||
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
@@ -293,8 +293,8 @@ mod tests {
|
||||
assert_eq!(ui.toolset_tab, "Modeling");
|
||||
assert_eq!(ui.history_lines, 4);
|
||||
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
|
||||
assert_eq!(ui.docking.layout(), default_workspace().layout());
|
||||
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
|
||||
assert_eq!(ui.docking.layout, default_workspace().layout);
|
||||
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -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 |
@@ -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."
|
||||
}
|
||||
@@ -2,4 +2,7 @@ allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
9fa32aecf2759cd61bb216a958df68da619798f3
|
||||
@@ -238,9 +238,8 @@ mod tests {
|
||||
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
|
||||
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
|
||||
}
|
||||
// An unclamped spline has no ends: one whose control points wrap round.
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
|
||||
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
|
||||
assert!(closed.wraps() && spline_end(&closed, false).is_none());
|
||||
// An unclamped (periodic) spline has no ends.
|
||||
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
|
||||
assert!(spline_end(&closed, false).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +206,8 @@ pub fn next_id(d: &Drawing) -> u32 {
|
||||
/// Interpret a constraint against the model's current parameters, appending its auxiliary
|
||||
/// unknowns (contact parameters) to the model, settled with the geometry held still.
|
||||
pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> {
|
||||
let mut b = Built::new(c, model, &model.x0, target)?;
|
||||
let x = model.x0.clone();
|
||||
let mut b = Built::new(c, model, &x, target)?;
|
||||
if b.aux_init.is_empty() {
|
||||
return Ok(b);
|
||||
}
|
||||
@@ -526,26 +527,22 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result<SolveReport, SolveE
|
||||
/// Largest residual of each constraint at the current geometry (`None` when it cannot be
|
||||
/// interpreted).
|
||||
pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
|
||||
residuals_with_model(d, residual_model(d)).collect()
|
||||
}
|
||||
|
||||
fn residual_model(d: &Drawing) -> Model {
|
||||
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
|
||||
Model::build(d, &handles)
|
||||
}
|
||||
|
||||
fn residuals_with_model(d: &Drawing, mut model: Model) -> impl Iterator<Item = (u32, Option<f64>)> + '_ {
|
||||
let mut e = env(d);
|
||||
let mut out = Vec::new();
|
||||
d.constraints.iter().take(MAX_CONSTRAINTS).map(move |c| {
|
||||
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
|
||||
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
|
||||
out.clear();
|
||||
b.eval(&model, &model.x0, &mut out);
|
||||
lm::max_abs(&out)
|
||||
});
|
||||
(c.id, r)
|
||||
})
|
||||
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
|
||||
let mut model = Model::build(d, &handles);
|
||||
d.constraints
|
||||
.iter()
|
||||
.take(MAX_CONSTRAINTS)
|
||||
.map(|c| {
|
||||
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
|
||||
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
|
||||
let mut out = Vec::new();
|
||||
b.eval(&model, &model.x0, &mut out);
|
||||
lm::max_abs(&out)
|
||||
});
|
||||
(c.id, r)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Put back what each Fix locks where `before` had it, and report whether anything moved.
|
||||
@@ -686,9 +683,9 @@ pub fn moved_anchors(d: &Drawing, before: &Drawing) -> Vec<(u32, Vec2)> {
|
||||
|
||||
/// True when every interpretable constraint holds at the current geometry.
|
||||
pub fn all_satisfied(d: &Drawing) -> bool {
|
||||
let model = residual_model(d);
|
||||
let tol = scale_tol(&model.x0) * 10.0;
|
||||
residuals_with_model(d, model).all(|(_, r)| r.is_none_or(|v| v <= tol))
|
||||
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
|
||||
let tol = scale_tol(&Model::build(d, &handles).x0) * 10.0;
|
||||
residuals(d).iter().all(|(_, r)| r.is_none_or(|v| v <= tol))
|
||||
}
|
||||
|
||||
/// Check that a constraint's references make sense for its type.
|
||||
|
||||
@@ -222,27 +222,6 @@ pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec<Vec
|
||||
(rank, basis)
|
||||
}
|
||||
|
||||
/// Weighted normal matrix J W⁻¹ Jᵀ. Most constraint rows depend on only a few free coordinates.
|
||||
fn normal_matrix(jac: &[f64], inverse_weights: &[f64], rows: usize) -> Vec<f64> {
|
||||
let mut matrix = vec![0.0; rows * rows];
|
||||
let mut terms = Vec::new();
|
||||
let width = inverse_weights.len();
|
||||
for (i, row) in jac.chunks_exact(width).enumerate() {
|
||||
terms.clear();
|
||||
terms.extend(row.iter().enumerate().filter(|(_, value)| **value != 0.0).map(|(col, &value)| (col, value, inverse_weights[col])));
|
||||
for (k, other) in jac.chunks_exact(width).enumerate().skip(i) {
|
||||
let sum = if terms.len() == width {
|
||||
row.iter().zip(other).zip(inverse_weights).fold(0.0, |sum, ((&v, &other_v), &weight)| sum + v * other_v * weight)
|
||||
} else {
|
||||
terms.iter().fold(0.0, |sum, &(col, v, weight)| sum + v * other[col] * weight)
|
||||
};
|
||||
matrix[i * rows + k] = sum;
|
||||
matrix[k * rows + i] = sum;
|
||||
}
|
||||
}
|
||||
matrix
|
||||
}
|
||||
|
||||
/// Run the solver from `x0`. Only `free` parameters change.
|
||||
pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize], weights: &[f64], tol: f64, max_iter: usize) -> Outcome {
|
||||
let mut x = x0.to_vec();
|
||||
@@ -264,7 +243,22 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
|
||||
while iter < max_iter {
|
||||
iter += 1;
|
||||
let jac = jacobian(f, &x, free, rows);
|
||||
let a = normal_matrix(&jac, &winv, rows);
|
||||
// A = J W⁻¹ Jᵀ
|
||||
let mut a = vec![0.0; rows * rows];
|
||||
for i in 0..rows {
|
||||
for k in i..rows {
|
||||
let mut s = 0.0;
|
||||
for (c, w) in winv.iter().enumerate() {
|
||||
s += jac.get(i * nf + c).copied().unwrap_or(0.0) * jac.get(k * nf + c).copied().unwrap_or(0.0) * w;
|
||||
}
|
||||
if let Some(v) = a.get_mut(i * rows + k) {
|
||||
*v = s;
|
||||
}
|
||||
if let Some(v) = a.get_mut(k * rows + i) {
|
||||
*v = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
let diag_max = (0..rows).map(|i| a.get(i * rows + i).copied().unwrap_or(0.0)).fold(0.0f64, f64::max).max(1e-12);
|
||||
let mut improved = false;
|
||||
for _ in 0..12 {
|
||||
@@ -316,20 +310,6 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sparse_and_dense_constraints_keep_their_weighted_cross_terms() {
|
||||
// Includes an empty row, an unconstrained column in a sparse row, and a tiny derivative.
|
||||
let rows = [[-0., 0., -0., -0.], [2., 0., -3., 0.], [0., 0., 0., 1e-12], [1., 3., 2., -5.]];
|
||||
let weights = [1., 0.25, 0.5, 2.];
|
||||
let matrix = normal_matrix(&rows.concat(), &weights, rows.len());
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
for (k, other) in rows.iter().enumerate() {
|
||||
let reference = (0..weights.len()).fold(0.0, |sum, c| sum + row[c] * other[c] * weights[c]);
|
||||
assert_eq!(matrix[i * rows.len() + k].to_bits(), reference.to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dense_and_rank() {
|
||||
let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap();
|
||||
|
||||
+47
-246
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
+162
-1368
File diff suppressed because it is too large
Load Diff
@@ -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,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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
|
||||
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
|
||||
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
|
||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||
@@ -271,10 +271,8 @@ impl EntityKind {
|
||||
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
|
||||
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
|
||||
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
|
||||
// What its proxy graphics draw, so a proxy can be picked and snapped to. A filled
|
||||
// shape's hatch is left out: its outline is drawn too, and the hatch's sides (72 for an
|
||||
// ellipse) would offer snaps inside it.
|
||||
EntityKind::Unknown(u) => u.graphics.iter().filter(|g| !matches!(g.kind, EntityKind::Hatch(_))).flat_map(|g| g.kind.prims()).collect(),
|
||||
// What its proxy graphics draw, so a proxy can be picked and snapped to.
|
||||
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -399,9 +397,7 @@ impl EntityKind {
|
||||
t3(p);
|
||||
}
|
||||
if let DimKind::Linear { rotation } = &mut d.kind {
|
||||
// A mirror reflects the dimension line's direction about the mirror line:
|
||||
// `rot` is twice the mirror line's angle, so `a` lands at `rot - a`.
|
||||
*rotation = cadcraft_geom::norm_angle(if mirror { rot - *rotation } else { *rotation + rot });
|
||||
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
|
||||
}
|
||||
d.marks.transform(&t3, rot, s, mirror);
|
||||
d.block = None;
|
||||
@@ -619,8 +615,7 @@ impl EntityKind {
|
||||
EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(),
|
||||
EntityKind::Spline(s) => {
|
||||
if s.fit.is_empty() {
|
||||
// One grip per control vertex: a closed spline's repeats have none (#3566).
|
||||
s.control.iter().take(s.distinct_controls()).copied().collect()
|
||||
s.control.clone()
|
||||
} else {
|
||||
s.fit.clone()
|
||||
}
|
||||
@@ -630,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(),
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::common::{Common, Lineweight};
|
||||
use super::text::{MText, Text};
|
||||
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
|
||||
@@ -145,43 +142,6 @@ impl AttribProps {
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
|
||||
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
|
||||
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
|
||||
/// each definition costs their product on a block with many of both (#1923). It orders, rather
|
||||
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
|
||||
/// build's `RandomState`), as in the layer and block name index.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TagKey<'a>(pub &'a str);
|
||||
|
||||
impl TagKey<'_> {
|
||||
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
|
||||
/// finds equal.
|
||||
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
|
||||
self.0.bytes().map(|b| b.to_ascii_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for TagKey<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.eq_ignore_ascii_case(other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for TagKey<'_> {}
|
||||
|
||||
impl Ord for TagKey<'_> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.folded().cmp(other.folded())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for TagKey<'_> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Insert {
|
||||
@@ -231,12 +191,6 @@ fn one_u() -> u32 {
|
||||
}
|
||||
|
||||
impl Insert {
|
||||
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
|
||||
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
|
||||
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
|
||||
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
|
||||
}
|
||||
|
||||
/// Block-to-world transform (2D part).
|
||||
pub fn transform(&self, base: Vec2) -> Mat3 {
|
||||
Mat3::translate(self.insert.xy())
|
||||
@@ -244,31 +198,4 @@ impl Insert {
|
||||
.then_before(Mat3::scale(self.scale.x, self.scale.y))
|
||||
.then_before(Mat3::translate(-base))
|
||||
}
|
||||
|
||||
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
|
||||
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
|
||||
/// one lookup instead of a pass over the attributes per definition (#1923).
|
||||
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
|
||||
let mut by_tag = BTreeMap::new();
|
||||
for a in &self.attribs {
|
||||
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
|
||||
}
|
||||
by_tag
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Block {
|
||||
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
|
||||
/// first in the block's order, the one an attribute of that tag takes its properties from.
|
||||
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
|
||||
/// pass over the block per attribute (#1923).
|
||||
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
|
||||
let mut by_tag = BTreeMap::new();
|
||||
for e in self.entities.iter() {
|
||||
if let EntityKind::AttDef(a) = &e.kind {
|
||||
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
|
||||
}
|
||||
}
|
||||
by_tag
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,9 +100,7 @@ impl DimMarks {
|
||||
/// Transform the points and angles (part of [`super::EntityKind::transform`]).
|
||||
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
|
||||
if let Some(a) = &mut self.oblique {
|
||||
// A mirror reflects a direction about the mirror line: `rot` is the transformed X
|
||||
// axis (twice the mirror line's angle), so a direction `a` lands at `rot - a`.
|
||||
*a = cadcraft_geom::norm_angle(if mirror { rot - *a } else { *a + rot });
|
||||
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
|
||||
}
|
||||
if let Some(j) = &mut self.jog_line {
|
||||
t3(j);
|
||||
|
||||
+59
-753
@@ -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
|
||||
|
||||
+61
-510
@@ -1,10 +1,10 @@
|
||||
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
|
||||
|
||||
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
|
||||
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
|
||||
|
||||
/// Nested block references deeper than this are ignored (cyclic or hostile files).
|
||||
pub const MAX_BLOCK_DEPTH: usize = 16;
|
||||
@@ -246,68 +246,23 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
|
||||
/// the same way the renderer places it (the stroke font is about 0.88 of the height per character).
|
||||
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
|
||||
use crate::{HAlign, VAlign};
|
||||
let natural = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64;
|
||||
let w = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64;
|
||||
// Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11).
|
||||
let origin = t.justify_point();
|
||||
// Aligned and Fit text span their two points (groups 10 and 11) whatever rotation is stored:
|
||||
// the line runs from the first to the second, Fit at its own height with its width stretched,
|
||||
// Aligned at the height that keeps its proportions. With no second point, or one on the
|
||||
// first, they are placed like left-justified text, as the renderer places them.
|
||||
let second = t.align_pt.map(|p| p.xy()).filter(|_| matches!(t.halign, HAlign::Aligned | HAlign::Fit));
|
||||
let span = second.map(|p| origin.dist(p)).filter(|d| d.is_finite() && *d > 1e-12);
|
||||
// The fonts shape with the width factor as it is, not floored like the fallback width above,
|
||||
// with 1 when it is unusable, and with a height of 1 when the height is.
|
||||
let usable = t.width_factor.is_finite() && t.width_factor.abs() > 1e-6;
|
||||
let wf = if usable { t.width_factor.abs() } else { 1.0 };
|
||||
let height = if t.height.is_finite() && t.height > 0.0 { t.height } else { 1.0 };
|
||||
let shaped = height * 0.9 * wf * len.max(1) as f64;
|
||||
// Fit text is stretched by scaling its width factor by span / shaped width and shaping again.
|
||||
// When the scaled factor is one the fonts cannot use (the stored one is, or the span is a tiny
|
||||
// part of the text's width), the text is not stretched: it is drawn at a factor of 1.
|
||||
// The shaped width here is an estimate, and the fonts decide by their own: it is taken to be
|
||||
// within this factor of the estimate. Where the fonts decide by a cutoff, the box is the larger
|
||||
// of the two outcomes unless the estimate is clear of the cutoff by this factor.
|
||||
const MARGIN: f64 = 4.0;
|
||||
let fits = |d: f64| {
|
||||
let fitted = wf * d / shaped;
|
||||
usable && fitted.is_finite() && fitted > 1e-6 * MARGIN
|
||||
};
|
||||
let unstretched = height * 0.9 * len.max(1) as f64;
|
||||
// The fonts leave a line of next to no width as it is, neither stretched nor scaled.
|
||||
let no_width = shaped * MARGIN <= 1e-12;
|
||||
let (w, h, rotation) = match (span, second) {
|
||||
(Some(_), Some(p)) if no_width => (shaped, height, origin.angle_to(p)),
|
||||
// Unstretched is the larger outcome: a span this near the cutoff is far shorter than the text.
|
||||
(Some(d), Some(p)) if t.halign == HAlign::Fit && !fits(d) => (unstretched, height, origin.angle_to(p)),
|
||||
(Some(d), Some(p)) if t.halign == HAlign::Fit => (d, height, origin.angle_to(p)),
|
||||
// Shrunk into a span shorter than its width, Aligned text is no taller than its own height,
|
||||
// however narrow its characters are.
|
||||
(Some(d), Some(p)) => (d, (height * d / shaped).max(height), origin.angle_to(p)),
|
||||
_ => (natural, t.height, t.rotation),
|
||||
};
|
||||
let dx = match t.halign {
|
||||
HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0,
|
||||
HAlign::Center | HAlign::Middle => -w / 2.0,
|
||||
HAlign::Right => -w,
|
||||
};
|
||||
let dy = match (t.halign, t.valign) {
|
||||
(HAlign::Middle, _) => -h / 2.0,
|
||||
(HAlign::Middle, _) => -t.height / 2.0,
|
||||
(_, VAlign::Baseline) => 0.0,
|
||||
(_, VAlign::Bottom) => h / 3.0,
|
||||
(_, VAlign::Middle) => -h / 2.0,
|
||||
(_, VAlign::Top) => -h,
|
||||
(_, VAlign::Bottom) => t.height / 3.0,
|
||||
(_, VAlign::Middle) => -t.height / 2.0,
|
||||
(_, VAlign::Top) => -t.height,
|
||||
};
|
||||
let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + h), Vec2::new(dx, dy + h)];
|
||||
Bounds2::from_points(local.map(|p| origin + p.rotate(rotation)))
|
||||
}
|
||||
|
||||
/// Whether `e` is a point on the layer Defpoints (the name in any case), as the block of a
|
||||
/// dimension holds the dimension's definition points. The reference app selects a dimension and a
|
||||
/// block reference by such a point of its block whatever a viewport freezes, the layer Defpoints
|
||||
/// too, where a line on that layer follows the viewport. So a selection through a viewport counts
|
||||
/// such a part of a block ([`ViewportBounds`]); the viewport itself does not draw it.
|
||||
pub fn point_on_defpoints(e: &Entity) -> bool {
|
||||
matches!(e.kind, EntityKind::Point(_)) && e.common.layer.eq_ignore_ascii_case("Defpoints")
|
||||
let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + t.height), Vec2::new(dx, dy + t.height)];
|
||||
Bounds2::from_points(local.map(|p| origin + p.rotate(t.rotation)))
|
||||
}
|
||||
|
||||
/// Whether an entity inside a block definition shows: its own invisible flag and its layer count,
|
||||
@@ -315,124 +270,25 @@ pub fn point_on_defpoints(e: &Entity) -> bool {
|
||||
/// entities a visibility state hides are invisible this way, and they sit far from the block's
|
||||
/// 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`]).
|
||||
/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]); a
|
||||
/// point on the layer Defpoints counts whatever that viewport freezes ([`point_on_defpoints`]).
|
||||
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool {
|
||||
let frozen: &[String] = if point_on_defpoints(e) { &[] } else { frozen };
|
||||
// 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.
|
||||
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen)
|
||||
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).
|
||||
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
|
||||
}
|
||||
|
||||
/// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which
|
||||
/// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`.
|
||||
/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through,
|
||||
/// which does not draw them (the names compared as the renderer compares them).
|
||||
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool {
|
||||
layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen_in(frozen, layer))
|
||||
}
|
||||
|
||||
/// Whether `layer` is one of the layers in `frozen`, those frozen in a layout viewport (the names
|
||||
/// compared as the renderer compares them).
|
||||
fn frozen_in(frozen: &[String], layer: &str) -> bool {
|
||||
frozen.iter().any(|f| f.eq_ignore_ascii_case(layer))
|
||||
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
|
||||
layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts))
|
||||
}
|
||||
|
||||
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
|
||||
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
|
||||
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
|
||||
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
|
||||
}
|
||||
|
||||
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
|
||||
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
|
||||
/// only a block reference draws (a dimension's block does not), and only when the reference
|
||||
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
|
||||
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
|
||||
/// of an attribute that has none of its own.
|
||||
struct Contents<'a> {
|
||||
geometry: Bounds2,
|
||||
constants: Vec<(&'a str, Bounds2)>,
|
||||
defs: BTreeMap<TagKey<'a>, &'a Entity>,
|
||||
}
|
||||
|
||||
impl Contents<'_> {
|
||||
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
|
||||
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
|
||||
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
|
||||
if self.constants.is_empty() {
|
||||
return self.geometry;
|
||||
}
|
||||
// The reference's tags are gathered once, not scanned again for each constant (#1923).
|
||||
let carried = ins.attribs_by_tag();
|
||||
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`: the parts that
|
||||
/// count there ([`in_block_visible`], and a constant value by its layer as [`layer_counts`] says),
|
||||
/// so those on a layer in `frozen` are left out ([`bounds_in`] says what the maps hold and why the
|
||||
/// depth is part of the key).
|
||||
fn contents<'a, 'm>(
|
||||
d: &'a Drawing,
|
||||
blk: &'a crate::Block,
|
||||
depth: usize,
|
||||
blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
off_counts: bool,
|
||||
frozen: &[String],
|
||||
) -> Option<&'m Contents<'a>> {
|
||||
let key = (blk.name.as_str(), depth);
|
||||
if !blocks.contains_key(&key) {
|
||||
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
|
||||
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
|
||||
// ones, 2 all of them.
|
||||
let attmode = d.header.i64("ATTMODE", 1);
|
||||
for be in blk.entities.iter() {
|
||||
match &be.kind {
|
||||
EntityKind::AttDef(a)
|
||||
if a.constant
|
||||
&& attmode != 0
|
||||
&& (!a.invisible || attmode == 2)
|
||||
&& be.common.visible
|
||||
&& layer_counts(d, &be.common.layer, off_counts, frozen) =>
|
||||
{
|
||||
c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation())));
|
||||
}
|
||||
_ if in_block_visible(d, be, off_counts, frozen) => {
|
||||
c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
blocks.insert(key, c);
|
||||
}
|
||||
blocks.get(&key)
|
||||
}
|
||||
|
||||
/// [`Contents`] of the block `blk`, referenced at `depth`, as the drawing shows them: no viewport's
|
||||
/// frozen layers are left out. For a clipped reference measured through a viewport ([`bounds_in`]).
|
||||
/// `in_drawing` keeps them, apart from that viewport's own block bounds.
|
||||
fn drawing_contents<'a, 'm>(
|
||||
d: &'a Drawing,
|
||||
blk: &'a crate::Block,
|
||||
depth: usize,
|
||||
off_counts: bool,
|
||||
in_drawing: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
) -> Option<&'m Contents<'a>> {
|
||||
// With no layer left out, the measure never asks for the drawing's boxes itself.
|
||||
contents(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[])
|
||||
}
|
||||
|
||||
/// The box of a constant attribute definition's value, as a block reference draws it: upright
|
||||
/// when the definition matches the layout's orientation, like other text (#2498).
|
||||
fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
|
||||
let turn = |r: f64| if upright { 0.0 } else { r };
|
||||
match a.multiline_text() {
|
||||
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
|
||||
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, a.text.value.chars().count()),
|
||||
_ => Bounds2::EMPTY,
|
||||
}
|
||||
/// definition's (layer "0" being the insert's).
|
||||
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
|
||||
a.props.layer.as_deref().unwrap_or_else(|| {
|
||||
d.block(&ins.block)
|
||||
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
|
||||
.map_or("0", |be| be.common.layer.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
/// A text that draws no glyph (empty, or only blanks and non-breaking spaces) takes no room.
|
||||
@@ -471,13 +327,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 {
|
||||
|
||||
/// The box of what `e` draws (block contents on layers turned off left out).
|
||||
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
|
||||
bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new())
|
||||
bounds_of(d, e, depth, false, &mut HashMap::new())
|
||||
}
|
||||
|
||||
/// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer
|
||||
/// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not).
|
||||
pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
|
||||
bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new())
|
||||
bounds_of(d, e, 0, true, &mut HashMap::new())
|
||||
}
|
||||
|
||||
/// The bounds of block contents measured so far, kept across the entities of one unchanged
|
||||
@@ -488,102 +344,42 @@ 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`.
|
||||
pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
|
||||
bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new())
|
||||
bounds_of(d, e, depth, false, &mut cache.drawn)
|
||||
}
|
||||
|
||||
/// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
|
||||
pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
|
||||
bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new())
|
||||
bounds_of(d, e, 0, true, &mut cache.extents)
|
||||
}
|
||||
|
||||
/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the
|
||||
/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It
|
||||
/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while
|
||||
/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through
|
||||
/// one viewport never answer for another. Two things a selection counts whatever the viewport
|
||||
/// draws stay in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box the
|
||||
/// drawing gives it, and a dimension by its definition points, which its block holds as points on
|
||||
/// the layer Defpoints, so such a point counts in any block ([`point_on_defpoints`]).
|
||||
pub struct ViewportBounds<'a> {
|
||||
/// The layers frozen in the viewport.
|
||||
frozen: &'a [String],
|
||||
/// By block name and depth, the box of the block contents the viewport draws.
|
||||
blocks: HashMap<(&'a str, usize), Contents<'a>>,
|
||||
/// The same with no layer of the viewport left out: the box the drawing gives the contents,
|
||||
/// which a clipped reference keeps.
|
||||
in_drawing: HashMap<(&'a str, usize), Contents<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> ViewportBounds<'a> {
|
||||
/// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere).
|
||||
pub fn new(frozen: &'a [String]) -> Self {
|
||||
ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() }
|
||||
}
|
||||
|
||||
/// The layers frozen in the viewport.
|
||||
pub fn frozen(&self) -> &'a [String] {
|
||||
self.frozen
|
||||
}
|
||||
|
||||
/// Whether the viewport leaves `part` out for its layer. `part` is an entity of the block
|
||||
/// that an object the viewport draws is drawn from (a block reference, a dimension, a
|
||||
/// multileader), and it is left out when its layer is frozen in the viewport, as in the
|
||||
/// boxes above. A part on layer 0 never is: it takes the layer of the object, which the
|
||||
/// caller has checked. What the drawing itself hides (a layer frozen for the whole drawing
|
||||
/// or turned off) is not looked at here.
|
||||
pub fn leaves_out(&self, part: &Entity) -> bool {
|
||||
part.common.layer != "0" && frozen_in(self.frozen, &part.common.layer)
|
||||
}
|
||||
|
||||
/// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the
|
||||
/// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check.
|
||||
pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 {
|
||||
bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing)
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a
|
||||
/// top-level annotative object measured as it draws.
|
||||
fn bounds_of<'a>(
|
||||
d: &'a Drawing,
|
||||
e: &Entity,
|
||||
depth: usize,
|
||||
off_counts: bool,
|
||||
frozen: &[String],
|
||||
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
in_drawing: &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) {
|
||||
crate::AnnoDraw::Plain => {}
|
||||
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
|
||||
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
|
||||
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts),
|
||||
}
|
||||
}
|
||||
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
|
||||
bounds_in(d, e, depth, blocks, off_counts)
|
||||
}
|
||||
|
||||
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
|
||||
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
|
||||
/// OLE2FRAME as its frame. Measured through a viewport, the proxy graphics on a layer `frozen`
|
||||
/// there are left out as a block's parts are ([`in_block_visible`]), and a reference among them
|
||||
/// takes its boxes from `blocks` and `in_drawing` as any other does ([`bounds_in`]).
|
||||
/// OLE2FRAME as its frame.
|
||||
fn unknown_bounds<'a>(
|
||||
d: &'a Drawing,
|
||||
u: &crate::Unknown,
|
||||
depth: usize,
|
||||
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
|
||||
off_counts: bool,
|
||||
frozen: &[String],
|
||||
) -> Bounds2 {
|
||||
if u.graphics.is_empty() {
|
||||
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
|
||||
@@ -593,8 +389,8 @@ fn unknown_bounds<'a>(
|
||||
}
|
||||
u.graphics
|
||||
.iter()
|
||||
.filter(|g| in_block_visible(d, g, off_counts, frozen))
|
||||
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, in_drawing, off_counts, frozen)))
|
||||
.filter(|g| in_block_visible(d, g, off_counts))
|
||||
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
|
||||
}
|
||||
|
||||
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
|
||||
@@ -602,20 +398,8 @@ fn unknown_bounds<'a>(
|
||||
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
|
||||
/// definition per depth instead of one per reference (which grows exponentially with the nesting
|
||||
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
|
||||
/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in
|
||||
/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with
|
||||
/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen
|
||||
/// layer: a measure through a viewport takes from it the box the drawing gives the block of a
|
||||
/// clipped reference ([`drawing_contents`]). A measure with no frozen layer does not use it.
|
||||
fn bounds_in<'a>(
|
||||
d: &'a Drawing,
|
||||
e: &Entity,
|
||||
depth: usize,
|
||||
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
|
||||
off_counts: bool,
|
||||
frozen: &[String],
|
||||
) -> Bounds2 {
|
||||
/// bounds must not stand in for a shallower reference to the same block (#706).
|
||||
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>, 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,
|
||||
@@ -636,21 +420,19 @@ fn bounds_in<'a>(
|
||||
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
|
||||
// insertion point. Attributes below still count.
|
||||
let mut b = Bounds2::EMPTY;
|
||||
let mut defs = None;
|
||||
if let Some(blk) = d.block(&ins.block) {
|
||||
let m = ins.transform(blk.base.xy());
|
||||
let c = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen);
|
||||
defs = c.map(|c| &c.defs);
|
||||
let mut inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
|
||||
// XCLIP: the reference app selects a clipped reference by its boundary whatever a
|
||||
// viewport draws inside it, so a clipped reference keeps the box the drawing gives it.
|
||||
// One that is not inverted and has a part drawn gets the boundary's box below as it is.
|
||||
if !frozen.is_empty()
|
||||
&& let Some(c) = ins.clip.as_ref().filter(|c| c.active())
|
||||
&& (c.inverted || inner.is_empty())
|
||||
{
|
||||
inner = drawing_contents(d, blk, depth, off_counts, in_drawing).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).
|
||||
@@ -672,7 +454,7 @@ fn bounds_in<'a>(
|
||||
}
|
||||
}
|
||||
for a in &ins.attribs {
|
||||
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts, frozen) {
|
||||
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
|
||||
b = b.union(&match a.multiline_text() {
|
||||
Some(m) => mtext_box(&m),
|
||||
None => text_box(&a.text, a.text.value.chars().count()),
|
||||
@@ -709,7 +491,17 @@ fn bounds_in<'a>(
|
||||
// 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, in_drawing, off_counts, frozen).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();
|
||||
@@ -728,7 +520,7 @@ fn bounds_in<'a>(
|
||||
}
|
||||
if let Some(ins) = &m.block {
|
||||
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
|
||||
b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen));
|
||||
b = b.union(&bounds_in(d, &be, depth, blocks, off_counts));
|
||||
}
|
||||
b
|
||||
}
|
||||
@@ -748,7 +540,7 @@ fn bounds_in<'a>(
|
||||
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
|
||||
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
|
||||
// frame is, so the frame counts (#2422).
|
||||
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, in_drawing, off_counts, frozen),
|
||||
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
|
||||
kind => {
|
||||
let mut b = Bounds2::EMPTY;
|
||||
for p in kind.prims() {
|
||||
@@ -1032,247 +824,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A viewport leaves a part of a block out for its layer when that layer is frozen in the
|
||||
/// viewport, its name matched whatever its case. A part on layer 0 is never left out, also
|
||||
/// where the viewport freezes layer 0: it takes the layer of the object drawn from the block.
|
||||
/// A layer the drawing itself hides (frozen for the whole drawing, or turned off) is not the
|
||||
/// viewport's to leave out, and a viewport that freezes no layer leaves nothing out.
|
||||
#[test]
|
||||
fn a_viewport_leaves_out_the_parts_on_its_frozen_layers() {
|
||||
let part = |layer: &str| {
|
||||
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) });
|
||||
let mut e = Entity::new(crate::Handle(1), kind);
|
||||
e.common.layer = layer.into();
|
||||
e
|
||||
};
|
||||
let frozen = ["hidden".to_string(), "0".to_string()];
|
||||
let (through, plain) = (ViewportBounds::new(&frozen), ViewportBounds::new(&[]));
|
||||
assert!(through.leaves_out(&part("Hidden")), "a layer frozen in the viewport, its name in another case");
|
||||
assert!(!plain.leaves_out(&part("Hidden")), "the same part where no layer is frozen");
|
||||
assert!(!through.leaves_out(&part("0")), "layer 0 takes the object's layer");
|
||||
assert!(!through.leaves_out(&part("Other")), "a layer the viewport does not freeze");
|
||||
}
|
||||
|
||||
/// Through a layout viewport the block contents on a layer frozen in it take no room: a part
|
||||
/// of a reference, a part two blocks deep, a nested reference that is itself on that layer
|
||||
/// (with everything in it), an attribute, the parts of the block a dimension or a multileader
|
||||
/// draws (a reference nested in a dimension's block too), and the parts of an annotative
|
||||
/// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn
|
||||
/// of it. The layer's name is matched whatever its case. With no layer frozen
|
||||
/// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity
|
||||
/// the box a fresh one gives it.
|
||||
#[test]
|
||||
fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() {
|
||||
let line = |handle: u64, y: f64, layer: &str| {
|
||||
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
|
||||
let mut e = Entity::new(crate::Handle(handle), kind);
|
||||
e.common.layer = layer.into();
|
||||
e
|
||||
};
|
||||
let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() };
|
||||
let ins = |block: &str, layer: &str| {
|
||||
let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block)));
|
||||
e.common.layer = layer.into();
|
||||
e
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
d.ensure_layer("Hidden");
|
||||
let mut add = |name: &str, parts: Vec<Entity>| {
|
||||
let mut b = crate::Block::new(name);
|
||||
for part in parts {
|
||||
b.entities.push(part);
|
||||
}
|
||||
d.blocks.insert(name.into(), std::sync::Arc::new(b));
|
||||
};
|
||||
// B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a
|
||||
// reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden".
|
||||
add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]);
|
||||
add("N", vec![ins("B", "0")]);
|
||||
add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]);
|
||||
add("H", vec![line(1, 50.0, "Hidden")]);
|
||||
// A reference to B with an attribute on "Hidden" at y = 70.
|
||||
let mut tagged = ins("B", "0");
|
||||
if let EntityKind::Insert(i) = &mut tagged.kind {
|
||||
i.attribs.push(crate::Attrib {
|
||||
tag: "T".into(),
|
||||
text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) },
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() },
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
});
|
||||
}
|
||||
// References to H clipped to a boundary around its line, and with that clip inverted: no
|
||||
// part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B
|
||||
// with the inverted clip: its line along y = 0 is drawn there.
|
||||
let clip = |block: &str, inverted: bool| {
|
||||
let mut e = ins(block, "0");
|
||||
if let EntityKind::Insert(i) = &mut e.kind {
|
||||
let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]);
|
||||
i.clip = Some(crate::ClipBoundary { inverted, ..boundary });
|
||||
}
|
||||
e
|
||||
};
|
||||
let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true));
|
||||
// An annotative reference to B: measured as it draws at the annotation scale, here 1:1.
|
||||
let mut scaled = ins("B", "0");
|
||||
scaled.common.anno_scales = vec![crate::AnnoScale::unit()];
|
||||
// Dimensions that draw B and N, and a multileader that draws B.
|
||||
let dimension = |block: &str| {
|
||||
let kind = EntityKind::Dimension(crate::Dimension {
|
||||
kind: crate::DimKind::Aligned,
|
||||
defpt: Vec3::new(5.0, 1.0, 0.0),
|
||||
text_mid: Vec3::ZERO,
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(10.0, 0.0, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 0.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: Some(block.into()),
|
||||
insertion_point: Vec3::ZERO,
|
||||
overrides: Default::default(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
});
|
||||
Entity::new(crate::Handle(3), kind)
|
||||
};
|
||||
let (dim, dim_nested) = (dimension("B"), dimension("N"));
|
||||
let leader = Entity::new(
|
||||
crate::Handle(4),
|
||||
EntityKind::MLeader(crate::MLeader {
|
||||
leaders: vec![vec![Vec3::ZERO]],
|
||||
landing: Vec3::new(1.0, 0.0, 0.0),
|
||||
dogleg: 0.45,
|
||||
text: None,
|
||||
style: "Standard".into(),
|
||||
arrow_size: 1.0,
|
||||
spline: false,
|
||||
block: Some(reference("B")),
|
||||
}),
|
||||
);
|
||||
let frozen = ["HIDDEN".to_string()];
|
||||
let mut view = ViewportBounds::new(&frozen);
|
||||
let ys = |b: Bounds2| (b.min.y, b.max.y);
|
||||
assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0));
|
||||
assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer");
|
||||
assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep");
|
||||
assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0));
|
||||
assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer");
|
||||
assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty());
|
||||
assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn");
|
||||
let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0));
|
||||
let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped));
|
||||
assert_eq!((drawn.min, drawn.max), boundary);
|
||||
assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary");
|
||||
assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0));
|
||||
assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box");
|
||||
assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0));
|
||||
assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too");
|
||||
assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0);
|
||||
assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer");
|
||||
assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0));
|
||||
assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference");
|
||||
assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0);
|
||||
assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws");
|
||||
assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0);
|
||||
assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws");
|
||||
assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0);
|
||||
assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws");
|
||||
let clips = [clipped, clipped_inverted, clipped_partly];
|
||||
let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips);
|
||||
let all: Vec<Entity> = all.collect();
|
||||
let mut plain = ViewportBounds::new(&[]);
|
||||
for e in &all {
|
||||
let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e));
|
||||
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
|
||||
let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0));
|
||||
assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max));
|
||||
}
|
||||
}
|
||||
|
||||
/// With the layer Defpoints frozen in the viewport, a point on that layer that is a part of a
|
||||
/// block still counts: in the block of a reference, one block deeper, in the block of a
|
||||
/// dimension, as its definition points are held, and in that of a dimension that is itself a
|
||||
/// part of a block. Here the point lies far above all the rest. A line on Defpoints, a point
|
||||
/// on another frozen layer and a line on one are left out. One [`ViewportBounds`] gives each of
|
||||
/// them the box a fresh one gives it.
|
||||
#[test]
|
||||
fn a_viewport_keeps_the_points_on_defpoints_in_a_block() {
|
||||
let line = |handle: u64, y: f64, layer: &str| {
|
||||
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
|
||||
let mut e = Entity::new(crate::Handle(handle), kind);
|
||||
e.common.layer = layer.into();
|
||||
e
|
||||
};
|
||||
let point = |handle: u64, y: f64, layer: &str| {
|
||||
let mut e = Entity::new(crate::Handle(handle), EntityKind::Point(crate::Point { p: Vec3::new(5.0, y, 0.0), angle: 0.0 }));
|
||||
e.common.layer = layer.into();
|
||||
e
|
||||
};
|
||||
let ins = |block: &str| Entity::new(crate::Handle(9), EntityKind::Insert(crate::Insert { block: block.into(), ..crate::Insert::default() }));
|
||||
let dimension = |block: &str| {
|
||||
let kind = EntityKind::Dimension(crate::Dimension {
|
||||
kind: crate::DimKind::Aligned,
|
||||
defpt: Vec3::new(5.0, 1.0, 0.0),
|
||||
text_mid: Vec3::ZERO,
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(10.0, 0.0, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 0.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: Some(block.into()),
|
||||
insertion_point: Vec3::ZERO,
|
||||
overrides: Default::default(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
});
|
||||
Entity::new(crate::Handle(8), kind)
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
d.ensure_layer("Hidden");
|
||||
d.ensure_layer("Defpoints");
|
||||
let mut add = |name: &str, parts: Vec<Entity>| {
|
||||
let mut block = crate::Block::new(name);
|
||||
for part in parts {
|
||||
block.entities.push(part);
|
||||
}
|
||||
d.blocks.insert(name.into(), std::sync::Arc::new(block));
|
||||
};
|
||||
// P: a line along y = 0 on layer 0, a point on Defpoints at y = 200, a line on Defpoints
|
||||
// along y = 250 and a line on "Hidden" along y = 300. NP holds a reference to P, DP a
|
||||
// dimension that draws P. H is P with the point on "Hidden".
|
||||
add("P", vec![line(1, 0.0, "0"), point(2, 200.0, "Defpoints"), line(3, 250.0, "Defpoints"), line(4, 300.0, "Hidden")]);
|
||||
add("NP", vec![ins("P")]);
|
||||
add("DP", vec![dimension("P")]);
|
||||
add("H", vec![line(1, 0.0, "0"), point(2, 200.0, "Hidden")]);
|
||||
let ys = |b: Bounds2| (b.min.y, b.max.y);
|
||||
assert_eq!(ys(entity_bounds(&d, &ins("P"), 0)), (0.0, 300.0));
|
||||
let frozen = ["HIDDEN".to_string(), "defpoints".to_string()];
|
||||
let mut view = ViewportBounds::new(&frozen);
|
||||
assert_eq!(ys(view.entity_bounds(&d, &ins("P"))), (0.0, 200.0), "the point on Defpoints in a reference's block, not the lines");
|
||||
assert_eq!(ys(view.entity_bounds(&d, &ins("NP"))), (0.0, 200.0), "the same one block deeper");
|
||||
assert_eq!(view.entity_bounds(&d, &dimension("P")).max.y, 200.0, "a dimension's definition point");
|
||||
assert_eq!(view.entity_bounds(&d, &ins("DP")).max.y, 200.0, "the same for a dimension in a block");
|
||||
assert_eq!(ys(view.entity_bounds(&d, &ins("H"))), (0.0, 0.0), "a point on another frozen layer");
|
||||
// Where the viewport freezes only the other layer, the line on Defpoints counts too.
|
||||
let hidden = ["Hidden".to_string()];
|
||||
assert_eq!(ys(ViewportBounds::new(&hidden).entity_bounds(&d, &ins("P"))), (0.0, 250.0));
|
||||
for e in [ins("P"), ins("NP"), dimension("P"), ins("DP"), ins("H")] {
|
||||
let (shared, fresh) = (view.entity_bounds(&d, &e), ViewportBounds::new(&frozen).entity_bounds(&d, &e));
|
||||
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
|
||||
}
|
||||
}
|
||||
|
||||
/// A turned array of references reaches its side copies, not only the first and the last;
|
||||
/// a hostile count measures only the copies that are drawn.
|
||||
#[test]
|
||||
|
||||
@@ -113,43 +113,6 @@ impl Foreign {
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
/// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or
|
||||
/// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its
|
||||
/// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so
|
||||
/// saving writes its xdata, extension dictionary and reactors on the renamed record. Names
|
||||
/// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case
|
||||
/// changes nothing.
|
||||
pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) {
|
||||
let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
for kind in kinds {
|
||||
let old: ForeignKey = ((*kind).to_string(), from.clone());
|
||||
let new: ForeignKey = ((*kind).to_string(), to.clone());
|
||||
if let Some(extra) = self.records.remove(&old) {
|
||||
self.records.insert(new.clone(), extra);
|
||||
}
|
||||
self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether anything is kept for the record named `from` under one of `kinds`: what
|
||||
/// [`Foreign::rename`] would re-key.
|
||||
pub fn names(&self, kinds: &[&str], from: &str) -> bool {
|
||||
let from = from.trim().to_ascii_uppercase();
|
||||
let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str());
|
||||
self.records.keys().any(hit) || self.targets.values().any(hit)
|
||||
}
|
||||
|
||||
/// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps
|
||||
/// something for the renamed record and the name really changes (not only its case).
|
||||
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
|
||||
if !from.trim().eq_ignore_ascii_case(to.trim()) && this.names(kinds, from) {
|
||||
std::sync::Arc::make_mut(this).rename(kinds, from, to);
|
||||
}
|
||||
}
|
||||
|
||||
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
|
||||
/// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry.
|
||||
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
|
||||
@@ -427,42 +390,3 @@ pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> +
|
||||
pub fn class_index(number: Option<i64>) -> Option<usize> {
|
||||
usize::try_from(number?.checked_sub(500)?).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key(k: &str, n: &str) -> ForeignKey {
|
||||
(k.to_string(), n.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rekeys_records_and_targets_of_the_given_kinds_only() {
|
||||
let mut f = Foreign::default();
|
||||
let xdict = ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() };
|
||||
f.records.insert(key("BLOCK_RECORD", "DOOR"), xdict.clone());
|
||||
f.records.insert(key("LAYER", "DOOR"), ForeignExtra { reactors: vec![Handle(0x41)], ..ForeignExtra::default() });
|
||||
f.targets.insert(Handle(0x10), key("BLOCK_RECORD", "DOOR"));
|
||||
f.targets.insert(Handle(0x11), key("BLOCK", "DOOR"));
|
||||
f.targets.insert(Handle(0x12), key("LAYER", "DOOR"));
|
||||
f.rename(&["BLOCK_RECORD", "BLOCK", "ENDBLK"], "Door", "Gate");
|
||||
assert_eq!(f.records.get(&key("BLOCK_RECORD", "GATE")), Some(&xdict));
|
||||
assert!(!f.records.contains_key(&key("BLOCK_RECORD", "DOOR")));
|
||||
assert!(f.records.contains_key(&key("LAYER", "DOOR")), "another kind with the same name stays");
|
||||
assert_eq!(f.targets.get(&Handle(0x10)), Some(&key("BLOCK_RECORD", "GATE")));
|
||||
assert_eq!(f.targets.get(&Handle(0x11)), Some(&key("BLOCK", "GATE")));
|
||||
assert_eq!(f.targets.get(&Handle(0x12)), Some(&key("LAYER", "DOOR")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_shared_leaves_an_unrelated_drawing_shared() {
|
||||
let mut f = Foreign::default();
|
||||
f.records.insert(key("LAYER", "A"), ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() });
|
||||
let mut a = std::sync::Arc::new(f);
|
||||
let snapshot = a.clone();
|
||||
Foreign::rename_shared(&mut a, &["LAYER"], "B", "C");
|
||||
assert!(std::sync::Arc::ptr_eq(&a, &snapshot));
|
||||
Foreign::rename_shared(&mut a, &["LAYER"], "a", "c");
|
||||
assert!(a.records.contains_key(&key("LAYER", "C")) && snapshot.records.contains_key(&key("LAYER", "A")));
|
||||
}
|
||||
}
|
||||
|
||||
+25
-51
@@ -14,7 +14,6 @@ mod format;
|
||||
mod gdt;
|
||||
mod header;
|
||||
pub mod library;
|
||||
mod names;
|
||||
mod plotstyle;
|
||||
mod plotter;
|
||||
mod raster;
|
||||
@@ -31,17 +30,16 @@ pub use cadcraft_geom as geom;
|
||||
pub use constraint::*;
|
||||
pub use entity::*;
|
||||
pub use extents::{
|
||||
BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame,
|
||||
ole_frame_accepts, ole_frame_transform, point_on_defpoints,
|
||||
BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts,
|
||||
ole_frame_transform,
|
||||
};
|
||||
pub use format::Format;
|
||||
pub use gdt::*;
|
||||
pub use header::{HVal, Header};
|
||||
pub use names::{Named, NamedList, NamedMap};
|
||||
pub use plotstyle::*;
|
||||
pub use plotter::*;
|
||||
pub use raster::{Raster, Rasters};
|
||||
pub use refedit::{RefEdit, WorkItem, XrefSource};
|
||||
pub use refedit::{RefEdit, WorkItem};
|
||||
pub use store::EntityStore;
|
||||
pub use tables::*;
|
||||
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
|
||||
@@ -103,26 +101,17 @@ pub struct Drawing {
|
||||
pub header: Header,
|
||||
/// File data CADCraft does not model, written back on save.
|
||||
pub foreign: std::sync::Arc<foreign::Foreign>,
|
||||
/// Layers in table order; [`Drawing::layer`] looks them up by name.
|
||||
pub layers: NamedList<Layer>,
|
||||
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
|
||||
pub linetypes: NamedList<Linetype>,
|
||||
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
|
||||
pub text_styles: NamedList<TextStyle>,
|
||||
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
|
||||
pub dim_styles: NamedList<DimStyle>,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<Linetype>,
|
||||
pub text_styles: Vec<TextStyle>,
|
||||
pub dim_styles: Vec<DimStyle>,
|
||||
pub mleader_styles: Vec<MLeaderStyle>,
|
||||
/// Table styles in table order; looked up by name with [`NamedList::by_name`].
|
||||
pub table_styles: NamedList<TableStyle>,
|
||||
pub table_styles: Vec<TableStyle>,
|
||||
/// Multiline styles (MLSTYLE); STANDARD is always there.
|
||||
pub mline_styles: Vec<MLineStyle>,
|
||||
/// Block definitions by name; [`Drawing::block`] looks them up.
|
||||
pub blocks: NamedMap<std::sync::Arc<Block>>,
|
||||
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
|
||||
pub model: EntityStore,
|
||||
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
||||
pub model_page: Option<PageSetup>,
|
||||
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
|
||||
pub layouts: NamedList<Layout>,
|
||||
pub layouts: Vec<Layout>,
|
||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
|
||||
pub active_layout: Option<String>,
|
||||
@@ -169,11 +158,6 @@ pub struct Drawing {
|
||||
pub portable_fonts: bool,
|
||||
/// The pixels of the raster images that are loaded (IMAGE). Never written to a file.
|
||||
pub rasters: Rasters,
|
||||
/// The LAYER table of the file this drawing was read from, in the file's order and under
|
||||
/// the layers' current names: proxy graphics name layers by their index in it, and saving
|
||||
/// turns those indices into the written table's (#3094). An empty name stands for a record
|
||||
/// without one. Empty for a drawing not read from a file.
|
||||
pub proxy_layers: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for Drawing {
|
||||
@@ -196,7 +180,7 @@ impl Drawing {
|
||||
d.scales = metric_scales();
|
||||
d.dim_styles.push(DimStyle::iso25());
|
||||
d.mleader_styles = vec![MLeaderStyle::metric()];
|
||||
d.table_styles = vec![TableStyle::metric()].into();
|
||||
d.table_styles = vec![TableStyle::metric()];
|
||||
d.header.set_str("DIMSTYLE", "ISO-25");
|
||||
d
|
||||
}
|
||||
@@ -204,22 +188,20 @@ impl Drawing {
|
||||
Drawing {
|
||||
header: Header::default(),
|
||||
foreign: std::sync::Arc::default(),
|
||||
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
|
||||
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
|
||||
linetypes: vec![
|
||||
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype::continuous(),
|
||||
]
|
||||
.into(),
|
||||
text_styles: vec![TextStyle::default()].into(),
|
||||
dim_styles: vec![DimStyle::default()].into(),
|
||||
],
|
||||
text_styles: vec![TextStyle::default()],
|
||||
dim_styles: vec![DimStyle::default()],
|
||||
mleader_styles: vec![MLeaderStyle::default()],
|
||||
table_styles: vec![TableStyle::default()].into(),
|
||||
table_styles: vec![TableStyle::default()],
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: NamedMap::default(),
|
||||
blocks: BTreeMap::new(),
|
||||
model: EntityStore::new(),
|
||||
model_page: None,
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
|
||||
active_layout: None,
|
||||
views: Vec::new(),
|
||||
vports: Vec::new(),
|
||||
@@ -239,7 +221,6 @@ impl Drawing {
|
||||
skipped_records: BTreeMap::new(),
|
||||
portable_fonts: false,
|
||||
rasters: Rasters::default(),
|
||||
proxy_layers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,25 +304,20 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first layer named `name`, without case.
|
||||
pub fn layer(&self, name: &str) -> Option<&Layer> {
|
||||
self.layers.by_name(name)
|
||||
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first layer named `name`, without case, to change.
|
||||
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
|
||||
self.layers.by_name_mut(name)
|
||||
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first linetype named `name`, without case.
|
||||
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
|
||||
self.linetypes.by_name(name)
|
||||
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first text style named `name`, without case.
|
||||
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
|
||||
self.text_styles.by_name(name)
|
||||
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first dimension style named `name`, without case.
|
||||
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
|
||||
self.dim_styles.by_name(name)
|
||||
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The DIM* variables in the header that differ from the current dimension style, as
|
||||
@@ -409,13 +385,11 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The block named exactly `name`, else the first by name order named `name` without case.
|
||||
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
|
||||
self.blocks.by_name(name)
|
||||
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
|
||||
}
|
||||
/// The first layout named `name`, without case.
|
||||
pub fn layout(&self, name: &str) -> Option<&Layout> {
|
||||
self.layouts.by_name(name)
|
||||
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// Add a layer if missing; returns whether it was created.
|
||||
|
||||
@@ -250,39 +250,6 @@ pub fn pattern_for(d: &Drawing, name: &str) -> Option<HatchPattern> {
|
||||
Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p })
|
||||
}
|
||||
|
||||
/// The pattern name of a user-defined hatch, as the DXF Reference writes it (group 2). Its families
|
||||
/// are not a named pattern's: a hatch stores them at unit scale, turned by its angle and spaced by
|
||||
/// its scale (groups 52, 41 and 77 of a DXF file), so [`user_defined_lines`] makes them for a file
|
||||
/// that lists none (AutoCAD's own are written with 78 = 0).
|
||||
pub const USER_PATTERN: &str = "_USER";
|
||||
|
||||
/// Whether `name` is a user-defined hatch's pattern name ([`USER_PATTERN`], in any case).
|
||||
pub fn is_user_pattern(name: &str) -> bool {
|
||||
name.eq_ignore_ascii_case(USER_PATTERN)
|
||||
}
|
||||
|
||||
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
|
||||
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
|
||||
|
||||
/// Whether the scale can be used for hatch pattern lines.
|
||||
pub fn is_supported_hatch_pattern_scale(scale: f64) -> bool {
|
||||
scale.is_finite() && scale > MIN_HATCH_PATTERN_SCALE
|
||||
}
|
||||
|
||||
/// The effective scale of a stored hatch. Use unit scale when its scale is unusable.
|
||||
pub fn effective_hatch_pattern_scale(scale: f64) -> f64 {
|
||||
if is_supported_hatch_pattern_scale(scale) { scale } else { 1.0 }
|
||||
}
|
||||
|
||||
/// The line families of a user-defined hatch at unit scale, as a pattern definition has them: lines
|
||||
/// along the hatch's angle, its scale apart, and with `double` a second family at right angles to
|
||||
/// them. The hatch's angle turns the families and its scale spaces them, so a hatch of spacing
|
||||
/// `s` and lines at `a` stores angle `a`, scale `s` and these families.
|
||||
pub fn user_defined_lines(double: bool) -> Vec<PatternLine> {
|
||||
let family = || PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 1.0), dashes: Vec::new() };
|
||||
if double { vec![family(), PatternLine { angle: 90.0, ..family() }] } else { vec![family()] }
|
||||
}
|
||||
|
||||
/// `p` with every length (origins, offsets, dashes) multiplied by `k`.
|
||||
fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern {
|
||||
for l in &mut p.lines {
|
||||
|
||||
@@ -1,575 +0,0 @@
|
||||
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles,
|
||||
//! table styles and layouts), whose names are looked up without case through an index instead of a
|
||||
//! scan once a table is large and looked up often.
|
||||
//!
|
||||
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
|
||||
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
|
||||
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
|
||||
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
|
||||
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
|
||||
//!
|
||||
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
|
||||
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
|
||||
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
|
||||
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
|
||||
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
|
||||
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
|
||||
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
|
||||
//! what scanning it always did, and one looked up many times in between is indexed once.
|
||||
|
||||
use std::collections::{BTreeMap, btree_map};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
|
||||
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
|
||||
const MIN_INDEXED: usize = 128;
|
||||
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
|
||||
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
|
||||
/// hundred lookups costs at most about 2.5 times what scanning it always did.
|
||||
const SCANS_BEFORE_INDEX: u32 = 256;
|
||||
|
||||
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
|
||||
struct Index<V>(BTreeMap<Box<[u8]>, V>);
|
||||
|
||||
impl<V> Index<V> {
|
||||
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
|
||||
let mut map = BTreeMap::new();
|
||||
for (name, v) in entries {
|
||||
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
|
||||
}
|
||||
Index(map)
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case.
|
||||
fn get(&self, name: &str) -> Option<&V> {
|
||||
with_folded(name, |folded| self.0.get(folded))
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
|
||||
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
|
||||
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
|
||||
let mut buf = [0u8; 64];
|
||||
match buf.get_mut(..name.len()) {
|
||||
Some(short) => {
|
||||
short.copy_from_slice(name.as_bytes());
|
||||
short.make_ascii_lowercase();
|
||||
f(short)
|
||||
}
|
||||
None => f(name.to_ascii_lowercase().as_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
|
||||
/// dropped when the table changes.
|
||||
struct Lazy<V> {
|
||||
index: OnceLock<Arc<Index<V>>>,
|
||||
/// Lookups that scanned the table since it last changed.
|
||||
scans: AtomicU32,
|
||||
}
|
||||
|
||||
impl<V> Lazy<V> {
|
||||
/// The index of a table of `len` entries, built with `build` once the table has been scanned
|
||||
/// often enough since it changed; `None` while it is to be scanned.
|
||||
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
|
||||
if let Some(ix) = self.index.get() {
|
||||
return Some(ix);
|
||||
}
|
||||
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
|
||||
return None;
|
||||
}
|
||||
Some(self.index.get_or_init(|| Arc::new(build())))
|
||||
}
|
||||
|
||||
/// Forget the index: the table may change.
|
||||
fn clear(&mut self) {
|
||||
self.index = OnceLock::new();
|
||||
*self.scans.get_mut() = 0;
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Default for Lazy<V> {
|
||||
fn default() -> Self {
|
||||
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for Lazy<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry of a [`NamedList`]: what it is looked up by.
|
||||
pub trait Named {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
/// Entries named by their `name` field.
|
||||
macro_rules! named_by_field {
|
||||
($($t:ty),*) => {$(
|
||||
impl Named for $t {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, crate::Layout);
|
||||
|
||||
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
|
||||
/// dimension styles, table styles and layouts). It reads and changes as a `Vec`;
|
||||
/// [`NamedList::by_name`] finds the first entry of a name without case.
|
||||
pub struct NamedList<T> {
|
||||
list: Vec<T>,
|
||||
index: Lazy<usize>,
|
||||
}
|
||||
|
||||
impl<T: Named> NamedList<T> {
|
||||
/// The position of the first entry named `name`, without case.
|
||||
pub fn position_by_name(&self, name: &str) -> Option<usize> {
|
||||
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
|
||||
Some(ix) => ix.get(name).copied(),
|
||||
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case.
|
||||
pub fn by_name(&self, name: &str) -> Option<&T> {
|
||||
self.position_by_name(name).and_then(|i| self.list.get(i))
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case, to change (which drops the index).
|
||||
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
|
||||
let i = self.position_by_name(name)?;
|
||||
self.get_mut(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for NamedList<T> {
|
||||
type Target = Vec<T>;
|
||||
fn deref(&self) -> &Vec<T> {
|
||||
&self.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for NamedList<T> {
|
||||
fn deref_mut(&mut self) -> &mut Vec<T> {
|
||||
self.index.clear();
|
||||
&mut self.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for NamedList<T> {
|
||||
fn default() -> Self {
|
||||
Vec::new().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for NamedList<T> {
|
||||
fn clone(&self) -> Self {
|
||||
NamedList { list: self.list.clone(), index: self.index.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.list.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for NamedList<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.list == other.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Vec<T>> for NamedList<T> {
|
||||
fn from(list: Vec<T>) -> Self {
|
||||
NamedList { list, index: Lazy::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<NamedList<T>> for Vec<T> {
|
||||
fn from(l: NamedList<T>) -> Self {
|
||||
l.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
self.list.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> FromIterator<T> for NamedList<T> {
|
||||
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
|
||||
Vec::from_iter(iter).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoIterator for NamedList<T> {
|
||||
type Item = T;
|
||||
type IntoIter = std::vec::IntoIter<T>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.list.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a NamedList<T> {
|
||||
type Item = &'a T;
|
||||
type IntoIter = std::slice::Iter<'a, T>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.list.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
|
||||
type Item = &'a mut T;
|
||||
type IntoIter = std::slice::IterMut<'a, T>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.deref_mut().iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
|
||||
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
|
||||
/// order whose name matches without case.
|
||||
pub struct NamedMap<V> {
|
||||
map: BTreeMap<String, V>,
|
||||
index: Lazy<Box<str>>,
|
||||
}
|
||||
|
||||
impl<V> NamedMap<V> {
|
||||
/// The entry named exactly `name`, else the first in name order named `name` without case.
|
||||
pub fn by_name(&self, name: &str) -> Option<&V> {
|
||||
if let Some(v) = self.map.get(name) {
|
||||
return Some(v);
|
||||
}
|
||||
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
|
||||
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
|
||||
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Deref for NamedMap<V> {
|
||||
type Target = BTreeMap<String, V>;
|
||||
fn deref(&self) -> &BTreeMap<String, V> {
|
||||
&self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> DerefMut for NamedMap<V> {
|
||||
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
|
||||
self.index.clear();
|
||||
&mut self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Default for NamedMap<V> {
|
||||
fn default() -> Self {
|
||||
BTreeMap::new().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Clone> Clone for NamedMap<V> {
|
||||
fn clone(&self) -> Self {
|
||||
NamedMap { map: self.map.clone(), index: self.index.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.map.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: PartialEq> PartialEq for NamedMap<V> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.map == other.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
|
||||
fn from(map: BTreeMap<String, V>) -> Self {
|
||||
NamedMap { map, index: Lazy::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> FromIterator<(String, V)> for NamedMap<V> {
|
||||
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
|
||||
BTreeMap::from_iter(iter).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> IntoIterator for NamedMap<V> {
|
||||
type Item = (String, V);
|
||||
type IntoIter = btree_map::IntoIter<String, V>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.map.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> IntoIterator for &'a NamedMap<V> {
|
||||
type Item = (&'a String, &'a V);
|
||||
type IntoIter = btree_map::Iter<'a, String, V>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.map.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
|
||||
type Item = (&'a String, &'a mut V);
|
||||
type IntoIter = btree_map::IterMut<'a, String, V>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.deref_mut().iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{MIN_INDEXED, Named, NamedList};
|
||||
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
|
||||
|
||||
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
|
||||
/// added (a miss).
|
||||
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
|
||||
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
|
||||
}
|
||||
|
||||
fn layers_indexed(d: &Drawing) -> bool {
|
||||
d.layers.index.index.get().is_some()
|
||||
}
|
||||
|
||||
fn indexed<T>(list: &NamedList<T>) -> bool {
|
||||
list.index.index.get().is_some()
|
||||
}
|
||||
|
||||
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
|
||||
/// name without case), by pointer, for the list's names and `extra`.
|
||||
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
|
||||
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
|
||||
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
|
||||
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
|
||||
/// order finds (the first of a name without case): while they scan, once the table is indexed,
|
||||
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
|
||||
/// changed the first of a name and dropped the index.
|
||||
#[test]
|
||||
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
|
||||
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
|
||||
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
|
||||
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
|
||||
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
|
||||
let check = |d: &Drawing, extra: &[&str]| {
|
||||
check_list(&d.linetypes, |n| d.linetype(n), extra);
|
||||
check_list(&d.text_styles, |n| d.text_style(n), extra);
|
||||
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
|
||||
check_list(&d.layouts, |n| d.layout(n), extra);
|
||||
};
|
||||
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
|
||||
// The first round scans until the index is built; the second reads only the index.
|
||||
check(&d, &["dash", "missing"]);
|
||||
assert!(all_indexed(&d));
|
||||
check(&d, &["dash", "missing"]);
|
||||
|
||||
// The first of a name changes, and the later one of that name is found after it.
|
||||
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
|
||||
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
|
||||
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
|
||||
check(&d, &["SEVEN", "n7"]);
|
||||
assert!(all_indexed(&d));
|
||||
// A miss changes nothing and keeps the index.
|
||||
assert!(d.dim_styles.by_name_mut("none").is_none());
|
||||
assert!(indexed(&d.dim_styles));
|
||||
check(&d, &["dash"]);
|
||||
}
|
||||
|
||||
fn blocks_indexed(d: &Drawing) -> bool {
|
||||
d.blocks.index.index.get().is_some()
|
||||
}
|
||||
|
||||
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
|
||||
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
|
||||
/// name without case), and a large table looked up this often is left indexed.
|
||||
fn check_layers(d: &mut Drawing, extra: &[&str]) {
|
||||
let p = extra.first().copied().unwrap_or("L1");
|
||||
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
|
||||
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
|
||||
assert!(want.is_none() || !layers_indexed(d));
|
||||
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
|
||||
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
|
||||
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
|
||||
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
|
||||
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
|
||||
}
|
||||
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
|
||||
}
|
||||
|
||||
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
|
||||
/// else the first in name order of that name without case. Only names that miss an exact name
|
||||
/// count towards building the index, so the names are looked up twice.
|
||||
fn check_blocks(d: &Drawing, extra: &[&str]) {
|
||||
let names: Vec<String> = d.blocks.keys().cloned().collect();
|
||||
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
|
||||
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
|
||||
}
|
||||
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
|
||||
}
|
||||
|
||||
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
|
||||
/// of its name without case, also names that differ only after a long shared prefix, names
|
||||
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
|
||||
/// case). Names are compared, not hashed, so no two names can share a slot.
|
||||
#[test]
|
||||
fn the_index_alone_finds_the_first_entry_of_every_name() {
|
||||
let long = "x".repeat(100);
|
||||
let names: Vec<String> = vec![
|
||||
"Door".into(),
|
||||
"DOOR".into(),
|
||||
"door2".into(),
|
||||
format!("{long}A"),
|
||||
format!("{long}a"),
|
||||
format!("{long}B"),
|
||||
format!("{}b", "P".repeat(63)),
|
||||
format!("{}B", "p".repeat(63)),
|
||||
"Ärea".into(),
|
||||
"ärea".into(),
|
||||
"ÄREA".into(),
|
||||
String::new(),
|
||||
];
|
||||
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
|
||||
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
|
||||
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
|
||||
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
|
||||
}
|
||||
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
|
||||
assert_eq!(ix.get("ärea"), Some(&9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
|
||||
check_layers(&mut d, &["l5", "missing"]);
|
||||
|
||||
// Renamed through layer_mut (RENAME).
|
||||
d.layer_mut("l7").unwrap().name = "Seven".into();
|
||||
assert!(!layers_indexed(&d));
|
||||
assert!(d.layer("L7").is_none());
|
||||
check_layers(&mut d, &["SEVEN", "L7"]);
|
||||
// Added (LAYER New, or a file's later record of a name it already has).
|
||||
d.layers.push(Layer::new("SEVEN"));
|
||||
assert!(!layers_indexed(&d));
|
||||
check_layers(&mut d, &["seven"]);
|
||||
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
|
||||
d.layers.retain(|l| l.name != "L5");
|
||||
assert!(!layers_indexed(&d));
|
||||
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
|
||||
check_layers(&mut d, &["L5"]);
|
||||
// Inserted before an earlier layer of the same name.
|
||||
d.layers.insert(0, Layer::new("l9"));
|
||||
assert!(!layers_indexed(&d));
|
||||
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
|
||||
check_layers(&mut d, &["L9"]);
|
||||
// Changed by position, and by a loop over all of them.
|
||||
d.layers[3].name = "Third".into();
|
||||
assert!(!layers_indexed(&d));
|
||||
check_layers(&mut d, &["third"]);
|
||||
for l in &mut d.layers {
|
||||
l.name.make_ascii_uppercase();
|
||||
}
|
||||
assert!(!layers_indexed(&d));
|
||||
check_layers(&mut d, &["doors"]);
|
||||
|
||||
// Undo: a snapshot keeps the table it was taken with, and its index.
|
||||
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
|
||||
assert!(layers_indexed(&d));
|
||||
let (snap, before) = (d.clone(), names(&d));
|
||||
d.layers.clear();
|
||||
d.layers.push(Layer::new("Only"));
|
||||
check_layers(&mut d, &["only", "L1"]);
|
||||
d = snap;
|
||||
assert!(layers_indexed(&d));
|
||||
assert_eq!(names(&d), before);
|
||||
check_layers(&mut d, &["THIRD"]);
|
||||
// The whole table replaced (LAYERP, LAYUNISO).
|
||||
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
|
||||
check_layers(&mut d, &["a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
|
||||
let block = |name: &str| Arc::new(Block::new(name));
|
||||
let mut d = Drawing::new_imperial();
|
||||
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
|
||||
d.blocks.insert(name.clone(), block(&name));
|
||||
}
|
||||
check_blocks(&d, &["dOOR", "missing"]);
|
||||
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
|
||||
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
|
||||
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
|
||||
|
||||
// Removed (PURGE, a definition replaced under another name).
|
||||
d.blocks.remove("DOOR");
|
||||
assert!(!blocks_indexed(&d));
|
||||
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
|
||||
check_blocks(&d, &["dOOR"]);
|
||||
// Added before the first of that name.
|
||||
d.blocks.insert("DoOr".into(), block("DoOr"));
|
||||
assert!(!blocks_indexed(&d));
|
||||
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
|
||||
check_blocks(&d, &["dOOR"]);
|
||||
// Renamed (RENAME takes the definition out and puts it back under the new name).
|
||||
let b1 = d.blocks.remove("B1").unwrap();
|
||||
d.blocks.insert("Renamed".into(), b1);
|
||||
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
|
||||
check_blocks(&d, &["b1", "RENAMED"]);
|
||||
// Redefined in place, and changed through get_mut: the names stay.
|
||||
d.blocks.insert("Door".into(), block("Door"));
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["DOOR"]);
|
||||
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["b2"]);
|
||||
// Many removed at once.
|
||||
d.blocks.retain(|k, _| !k.starts_with("B9"));
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["b9", "b90"]);
|
||||
// A loop over all of them.
|
||||
for (_, b) in &mut d.blocks {
|
||||
Arc::make_mut(b).description = "looped".into();
|
||||
}
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["b3"]);
|
||||
|
||||
// Undo: a snapshot keeps the table it was taken with, and its index.
|
||||
let snap = d.clone();
|
||||
d.blocks.clear();
|
||||
d.blocks.insert("Only".into(), block("Only"));
|
||||
check_blocks(&d, &["only", "door"]);
|
||||
d = snap;
|
||||
assert!(blocks_indexed(&d));
|
||||
check_blocks(&d, &["DOOR", "only"]);
|
||||
}
|
||||
}
|
||||
@@ -79,21 +79,15 @@ impl Default for DevicePaper {
|
||||
impl DevicePaper {
|
||||
/// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm
|
||||
/// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at
|
||||
/// most [`MAX_PLOTTER_NAME`] characters. A sheet wider than tall is stored turned 90° and
|
||||
/// its margins turn with it, so the printable area the caller measured against the sheet it
|
||||
/// named is the one the stored portrait paper holds.
|
||||
/// most [`MAX_PLOTTER_NAME`] characters.
|
||||
pub fn sanitized(mut self) -> DevicePaper {
|
||||
let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 };
|
||||
let (w, h) = (side(self.width), side(self.height));
|
||||
self.width = w.min(h);
|
||||
self.height = w.max(h);
|
||||
for m in &mut self.margins {
|
||||
*m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 };
|
||||
}
|
||||
if w > h {
|
||||
let [l, b, r, t] = self.margins;
|
||||
self.margins = [b, r, t, l];
|
||||
}
|
||||
self.width = w.min(h);
|
||||
self.height = w.max(h);
|
||||
let [l, b, r, t] = self.margins;
|
||||
if l + r >= self.width || b + t >= self.height {
|
||||
self.margins = [0.0; 4];
|
||||
@@ -249,9 +243,6 @@ mod tests {
|
||||
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
|
||||
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
|
||||
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
|
||||
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
|
||||
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
|
||||
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
|
||||
assert!(back.paper("a3 BORDERLESS").is_some());
|
||||
assert!(PlotterConfig::from_file_text("{}").is_err());
|
||||
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name");
|
||||
|
||||
@@ -42,36 +42,6 @@ pub struct RefEdit {
|
||||
/// Block objects taken out of the working set with their edits (block coordinates, the block
|
||||
/// object's handle).
|
||||
pub released: Vec<Entity>,
|
||||
/// The nested references picked through to reach the edited block: block references inside
|
||||
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
|
||||
pub path: Vec<Handle>,
|
||||
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
|
||||
/// into its source drawing.
|
||||
pub xref: Option<XrefSource>,
|
||||
}
|
||||
|
||||
/// Where an xref edited in place is written back to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct XrefSource {
|
||||
/// The xref (its block name in this drawing).
|
||||
pub xref: String,
|
||||
/// The source drawing file.
|
||||
pub file: String,
|
||||
/// `file` with every symbolic link resolved when the edit began: the file that is written.
|
||||
/// The save is refused when `file` leads somewhere else by then.
|
||||
pub real: String,
|
||||
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
|
||||
/// is written back in that version (`None`: in the drawing's own).
|
||||
pub version: Option<String>,
|
||||
/// Whether the file is a binary DXF (written back as one).
|
||||
pub binary: bool,
|
||||
/// The block of the source drawing being edited; `None` for its model space.
|
||||
pub block: Option<String>,
|
||||
/// The file's size and modification time when the edit began.
|
||||
pub stamp: Option<(u64, std::time::SystemTime)>,
|
||||
/// Edited block objects (their handles in this drawing) and the objects of the source
|
||||
/// drawing they were loaded from.
|
||||
pub sources: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
impl RefEdit {
|
||||
|
||||
@@ -728,11 +728,6 @@ pub struct Block {
|
||||
/// The parameters of an associative array when this is an array block.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub array: Option<crate::ArrayParams>,
|
||||
/// An xref's file as its loaded objects were read from it: size and modification time (as the
|
||||
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
|
||||
/// the file changed since this drawing loaded it (session state; not saved).
|
||||
#[serde(skip)]
|
||||
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
|
||||
}
|
||||
|
||||
/// The load state of an external reference.
|
||||
@@ -779,7 +774,6 @@ impl Block {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -788,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).
|
||||
@@ -799,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],
|
||||
@@ -848,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,
|
||||
@@ -873,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 {
|
||||
@@ -1024,8 +1004,8 @@ impl LayerState {
|
||||
pub const ALL: u32 = 2047;
|
||||
|
||||
/// A state of every property of `layers`, with `current` the layer restoring makes current.
|
||||
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
|
||||
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
|
||||
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
|
||||
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-384
@@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() {
|
||||
|
||||
let i = Drawing::new_imperial();
|
||||
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
|
||||
assert_eq!(*i.table_styles, vec![TableStyle::default()]);
|
||||
assert_eq!(i.table_styles, vec![TableStyle::default()]);
|
||||
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
|
||||
}
|
||||
|
||||
@@ -271,46 +271,6 @@ fn transform_arc_mirror_keeps_shape() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirroring_a_rotated_dimension_reflects_its_direction() {
|
||||
let dim = |kind: DimKind, marks: DimMarks| {
|
||||
EntityKind::Dimension(Dimension {
|
||||
kind,
|
||||
defpt: Vec3::ZERO,
|
||||
text_mid: Vec3::ZERO,
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(7.071_067_811_865_475, 7.071_067_811_865_475, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 10.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
insertion_point: Vec3::ZERO,
|
||||
overrides: Default::default(),
|
||||
assoc: vec![],
|
||||
marks,
|
||||
})
|
||||
};
|
||||
// A dimension line at 45° mirrored across the X axis runs at -45° (315°) and still measures 10.
|
||||
let mut k = dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_4 }, DimMarks::default());
|
||||
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::X));
|
||||
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
|
||||
let DimKind::Linear { rotation } = d.kind else { panic!("a linear dimension") };
|
||||
assert!((rotation - 7.0 * std::f64::consts::FRAC_PI_4).abs() < 1e-9, "{rotation}");
|
||||
let p2 = Vec2::new(7.071_067_811_865_475, -7.071_067_811_865_475);
|
||||
assert!((p2.dot(Vec2::from_angle(rotation)).abs() - 10.0).abs() < 1e-9, "the mirrored measurement");
|
||||
|
||||
// Oblique extension lines reflect about the mirror line too (a 45° line here) instead of
|
||||
// being double-reflected (120° rather than 30°).
|
||||
let mut k = dim(DimKind::Aligned, DimMarks { oblique: Some(std::f64::consts::FRAC_PI_3), ..DimMarks::default() });
|
||||
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)));
|
||||
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
|
||||
assert!((d.marks.oblique.unwrap_or(0.0) - (std::f64::consts::FRAC_PI_2 - std::f64::consts::FRAC_PI_3)).abs() < 1e-9, "{:?}", d.marks.oblique);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_bounds_with_cyclic_block_terminate() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
@@ -560,21 +520,6 @@ fn block_entity_with_invisible_flag_is_ignored_in_insert_extents() {
|
||||
assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visible_constant_attribute_definition_counts_in_insert_extents() {
|
||||
// #3413: a reference draws a constant definition's value, so its extents reach it.
|
||||
let def = |constant: bool, invisible: bool| {
|
||||
let mut a = plain_attrib("C");
|
||||
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
|
||||
(a.constant, a.invisible) = (constant, invisible);
|
||||
Entity::new(Handle(2), EntityKind::AttDef(a))
|
||||
};
|
||||
let near = extents_pair(&drawing_with_block(def(false, false))).1;
|
||||
assert!(extents_pair(&drawing_with_block(def(true, false))).1.y > near.y + 40.0);
|
||||
// An invisible constant one, like a variable one, does not count.
|
||||
assert_eq!(extents_pair(&drawing_with_block(def(true, true))).1, near);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_entity_on_frozen_layer_is_ignored_and_on_a_layer_turned_off_counts() {
|
||||
let mut d = drawing_with_block(far_line("Hidden"));
|
||||
@@ -819,331 +764,3 @@ fn dim_style_spellings_of_one_field_apply_once() {
|
||||
assert!(st.apply_fields(m).is_empty());
|
||||
assert_eq!(st.text_height, want);
|
||||
}
|
||||
|
||||
/// A dimension's block in a parent block: `first` the dimension, or the reference to the same
|
||||
/// block "B" (a line and a visible constant attribute definition at y = 50).
|
||||
fn parent_of_dimension_and_insert(dimension_first: bool) -> Drawing {
|
||||
// Only "P" is referenced from model space, so "B" is measured inside it and nowhere else.
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut b = Block::new("B");
|
||||
b.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
|
||||
let mut a = plain_attrib("C");
|
||||
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
|
||||
a.constant = true;
|
||||
b.entities.push(Entity::new(Handle(2), EntityKind::AttDef(a)));
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(b));
|
||||
let dim = EntityKind::Dimension(Dimension {
|
||||
kind: DimKind::Linear { rotation: 0.0 },
|
||||
defpt: Vec3::new(1.0, 1.0, 0.0),
|
||||
text_mid: Vec3::new(0.5, 1.0, 0.0),
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(1.0, 0.0, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 1.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: Some("B".into()),
|
||||
overrides: Default::default(),
|
||||
assoc: vec![],
|
||||
marks: Default::default(),
|
||||
insertion_point: Vec3::ZERO,
|
||||
});
|
||||
let mut kids = vec![dim, plain_insert("B")];
|
||||
if !dimension_first {
|
||||
kids.reverse();
|
||||
}
|
||||
let mut parent = Block::new("P");
|
||||
for (i, k) in kids.into_iter().enumerate() {
|
||||
parent.entities.push(Entity::new(Handle(i as u64 + 10), k));
|
||||
}
|
||||
d.blocks.insert("P".into(), std::sync::Arc::new(parent));
|
||||
d.add(&Space::Model, Common::default(), plain_insert("P")).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_values_count_whichever_reference_measures_the_block_first() {
|
||||
// A dimension's block draws no constant value, a block reference does, and both read one
|
||||
// cache of block bounds: the reference's extents must not depend on which comes first.
|
||||
let first = extents_pair(&parent_of_dimension_and_insert(true));
|
||||
assert_eq!(first, extents_pair(&parent_of_dimension_and_insert(false)));
|
||||
assert!(first.1.y > 40.0, "the constant value at y = 50 counts: {first:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_constant_value_that_matches_the_layout_orientation_is_measured_upright() {
|
||||
// Drawn upright whatever rotation is stored (#2498), so the extents are those of rotation 0.
|
||||
let def = |rotation: f64, upright: bool| {
|
||||
let mut a = plain_attrib("C");
|
||||
a.text.value = "a long constant value".into();
|
||||
a.text.rotation = rotation;
|
||||
a.constant = true;
|
||||
let mut e = Entity::new(Handle(2), EntityKind::AttDef(a));
|
||||
if upright {
|
||||
e.common.xdata = vec![RawTag { code: 1001, value: "AcadAnnoPO".into() }, RawTag { code: 1070, value: "1".into() }];
|
||||
}
|
||||
e
|
||||
};
|
||||
let flat = extents_pair(&drawing_with_block(def(0.0, false)));
|
||||
assert_eq!(extents_pair(&drawing_with_block(def(std::f64::consts::FRAC_PI_2, true))), flat);
|
||||
assert_ne!(extents_pair(&drawing_with_block(def(std::f64::consts::FRAC_PI_2, false))), flat, "a plain one keeps its rotation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_constant_value_the_reference_has_an_attribute_for_does_not_count() {
|
||||
// Such a reference draws its attribute, not the definition's value, so a far-off definition
|
||||
// does not stretch its extents; a reference without that attribute still shows the value.
|
||||
let with = |attribs: Vec<Attrib>| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
|
||||
let mut a = plain_attrib("C");
|
||||
a.text.insert = Vec3::new(0.0, 5000.0, 0.0);
|
||||
a.constant = true;
|
||||
blk.entities.push(Entity::new(Handle(2), EntityKind::AttDef(a)));
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = attribs;
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
extents_pair(&d).1
|
||||
};
|
||||
assert!(with(vec![]).y > 4000.0);
|
||||
assert!(with(vec![plain_attrib("c")]).y < 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_values_count_in_extents_as_attmode_shows_them() {
|
||||
// The renderer shows no constant value at ATTMODE 0, and the invisible ones too at 2.
|
||||
let top = |attmode: i64, invisible: bool| {
|
||||
let mut a = plain_attrib("C");
|
||||
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
|
||||
(a.constant, a.invisible) = (true, invisible);
|
||||
let mut d = drawing_with_block(Entity::new(Handle(2), EntityKind::AttDef(a)));
|
||||
d.header.set_i64("ATTMODE", attmode);
|
||||
extents_pair(&d).1.y
|
||||
};
|
||||
assert!(top(1, false) > 40.0);
|
||||
assert!(top(0, false) < 40.0, "ATTMODE 0 hides it");
|
||||
assert!(top(1, true) < 40.0);
|
||||
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_and_fit_text_extents_span_their_two_points() {
|
||||
// Drawn from the first point to the second whatever rotation is stored: Fit at its own height,
|
||||
// Aligned at the height that keeps its proportions.
|
||||
let ext = |halign: HAlign, second: Option<Vec3>| {
|
||||
let mut t = plain_attrib("T").text;
|
||||
t.value = "AB".into();
|
||||
(t.halign, t.align_pt) = (halign, second);
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
|
||||
extents_pair(&d)
|
||||
};
|
||||
let left = ext(HAlign::Left, None);
|
||||
// Along x to a far second point: both reach it; only Aligned grows taller.
|
||||
let far = Some(Vec3::new(20.0, 0.0, 0.0));
|
||||
let (fit, aligned) = (ext(HAlign::Fit, far), ext(HAlign::Aligned, far));
|
||||
assert!((fit.1.x - 20.0).abs() < 1e-9 && (aligned.1.x - 20.0).abs() < 1e-9, "{fit:?} {aligned:?}");
|
||||
assert!(fit.1.x > left.1.x + 10.0, "wider than the same text left-justified");
|
||||
assert_eq!(fit.1.y, left.1.y, "Fit keeps its height");
|
||||
assert!(aligned.1.y > left.1.y * 5.0, "Aligned scales its height with its width");
|
||||
// Straight up: the line turns to run to the second point.
|
||||
let up = ext(HAlign::Fit, Some(Vec3::new(0.0, 20.0, 0.0)));
|
||||
assert!((up.1.y - 20.0).abs() < 1e-9 && up.1.x < 1.0 && up.0.x < -0.5, "{up:?}");
|
||||
// No second point, or one on the first: placed like left-justified text.
|
||||
assert_eq!(ext(HAlign::Fit, None), left);
|
||||
assert_eq!(ext(HAlign::Aligned, Some(Vec3::ZERO)), left);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_text_extents_keep_the_proportions_of_a_narrow_width_factor() {
|
||||
// The fonts shape with the width factor as stored, so a text ten times narrower fitted over
|
||||
// the same span is drawn ten times taller: its extents grow with it.
|
||||
let top = |width_factor: f64| {
|
||||
let mut t = plain_attrib("T").text;
|
||||
t.value = "AB".into();
|
||||
(t.halign, t.align_pt, t.width_factor) = (HAlign::Aligned, Some(Vec3::new(20.0, 0.0, 0.0)), width_factor);
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
|
||||
extents_pair(&d).1.y
|
||||
};
|
||||
assert!(top(0.001) > top(0.01) * 5.0, "{} {}", top(0.001), top(0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_and_fit_text_extents_follow_how_unusable_sizes_are_drawn() {
|
||||
let ext = |halign: HAlign, height: f64, width_factor: f64| {
|
||||
let mut t = plain_attrib("T").text;
|
||||
t.value = "AB".into();
|
||||
(t.halign, t.align_pt, t.height, t.width_factor) = (halign, Some(Vec3::new(1000.0, 0.0, 0.0)), height, width_factor);
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
|
||||
extents_pair(&d)
|
||||
};
|
||||
// A height of 0 is drawn as a height of 1: Aligned text still spans its points and has room.
|
||||
let flat = ext(HAlign::Aligned, 0.0, 1.0);
|
||||
assert!((flat.1.x - 1000.0).abs() < 1e-9 && flat.1.y > flat.0.y, "{flat:?}");
|
||||
assert_eq!(flat, ext(HAlign::Aligned, 1.0, 1.0));
|
||||
// Fit text with a width factor of 0 is not stretched to the second point.
|
||||
assert!(ext(HAlign::Fit, 1.0, 0.0).1.x < 100.0);
|
||||
assert!((ext(HAlign::Fit, 1.0, 1.0).1.x - 1000.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
|
||||
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
|
||||
// attribute without a layer of its own (in a third case) lies on the first one's.
|
||||
let top = |defs: [(&str, &str); 2]| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut frozen = Layer::new("AFRZ");
|
||||
frozen.frozen = true;
|
||||
d.layers.push(frozen);
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
|
||||
for (h, (layer, tag)) in (2..).zip(defs) {
|
||||
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
let mut a = plain_attrib("Tag");
|
||||
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
|
||||
ins.attribs.push(a);
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
extents_pair(&d).1.y
|
||||
};
|
||||
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
|
||||
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
|
||||
// Two constant definitions of one tag, in different case: a reference draws both values,
|
||||
// unless it carries an attribute of that tag (in a third case), which stands for both.
|
||||
let max = |attribs: Vec<Attrib>| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
|
||||
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
|
||||
let mut a = plain_attrib(tag);
|
||||
a.text.insert = at;
|
||||
a.constant = true;
|
||||
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = attribs;
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
extents_pair(&d).1
|
||||
};
|
||||
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
|
||||
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
|
||||
}
|
||||
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
|
||||
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
|
||||
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
|
||||
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
|
||||
// a definition's. Comparing each attribute with each definition, for its layer and for which
|
||||
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
|
||||
// here); one lookup per attribute or definition costs milliseconds.
|
||||
const N: usize = 4000;
|
||||
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
|
||||
for (h, i) in (2..).zip(0..N) {
|
||||
let mut a = plain_attrib(&tag('D', i));
|
||||
a.constant = true;
|
||||
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert!(!d.extents(&Space::Model).is_empty());
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
}
|
||||
|
||||
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
|
||||
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
|
||||
#[test]
|
||||
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
const N: usize = 60_000;
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
|
||||
for i in 0..N {
|
||||
let name = format!("B{i}");
|
||||
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
for i in 0..N {
|
||||
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
|
||||
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// Table entries for the cost tests below.
|
||||
const NAMED: usize = 40_000;
|
||||
|
||||
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
|
||||
/// about 50 bytes and not a length check, as in a crafted file.
|
||||
fn long_name(kind: &str, tail: &str) -> String {
|
||||
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
|
||||
}
|
||||
|
||||
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
|
||||
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
|
||||
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
|
||||
}
|
||||
|
||||
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
|
||||
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
|
||||
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
|
||||
/// comparisons (#1924).
|
||||
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
|
||||
let started = std::time::Instant::now();
|
||||
for i in 0..NAMED {
|
||||
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
|
||||
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
|
||||
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
|
||||
}
|
||||
|
||||
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
|
||||
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
|
||||
#[test]
|
||||
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
|
||||
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
|
||||
//! get new ones.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle};
|
||||
@@ -425,9 +425,6 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
|
||||
let all = all_handles(d);
|
||||
let ok_text = |d: &Drawing, n: &str| d.text_style(n).is_some();
|
||||
let ok_dim = |d: &Drawing, n: &str| d.dim_style(n).is_some();
|
||||
// Multileader style names, lower-cased, built once: a scan per multileader made a file of N of
|
||||
// them naming styles among N quadratic to audit (#1924).
|
||||
let mleader_styles: BTreeSet<String> = d.mleader_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect();
|
||||
// Missing names, counted: (what, name) → (objects, first location).
|
||||
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
|
||||
missing_layers(d, out);
|
||||
@@ -465,12 +462,12 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
|
||||
if let Some(t) = &mut m.text {
|
||||
text_style(&mut t.style);
|
||||
}
|
||||
if !mleader_styles.contains(&m.style.to_ascii_lowercase()) {
|
||||
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
|
||||
note("multileader style", &m.style);
|
||||
m.style = "Standard".into();
|
||||
}
|
||||
}
|
||||
EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => {
|
||||
EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => {
|
||||
note("table style", &t.style);
|
||||
t.style = "Standard".into();
|
||||
}
|
||||
|
||||
@@ -166,9 +166,6 @@ pub struct Autosaver {
|
||||
start: std::time::Instant,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
last_beat: Option<f64>,
|
||||
/// Who-has-it-open locks of the drawings open from files ([`crate::drawlock`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
drawing_locks: crate::drawlock::Locks,
|
||||
/// This app's lock files: one per folder, because SAVEFILEPATH can change while files remain
|
||||
/// in the old folder. Each with the file it holds open for the system lock, or `None` where
|
||||
/// locks don't work and only the file's age counts.
|
||||
@@ -190,8 +187,6 @@ impl Autosaver {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
last_beat: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
drawing_locks: crate::drawlock::Locks::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
locks: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -461,8 +456,7 @@ mod native {
|
||||
|
||||
impl Autosaver {
|
||||
/// Autosave what is due (writing in the background) and delete files no longer needed.
|
||||
/// Returns how long until the next autosave or drawing-lock heartbeat is due, so the host
|
||||
/// can wake up for it.
|
||||
/// Returns how long until the next autosave is due, so the host can wake up for it.
|
||||
pub fn tick(&mut self, s: &Session) -> Option<Duration> {
|
||||
let now = self.start.elapsed().as_secs_f64();
|
||||
self.reap();
|
||||
@@ -471,23 +465,7 @@ mod native {
|
||||
let jobs = self.plan(s, now, minutes, &dir);
|
||||
self.perform(jobs);
|
||||
self.heartbeat(&dir, now);
|
||||
self.drawing_locks.sync(s, &self.instance);
|
||||
// The drawing locks need their heartbeat even with nothing to autosave (SAVETIME 0,
|
||||
// every drawing saved): left untouched they go stale and another app takes them over.
|
||||
let due = self.next_due(now, minutes).map(Duration::from_secs_f64);
|
||||
due.into_iter().chain(self.drawing_locks.next_beat()).min()
|
||||
}
|
||||
|
||||
/// Keep the drawing locks with `locks` instead of the default ones (e.g. a shorter
|
||||
/// heartbeat, see [`crate::drawlock::Locks::with_heartbeat`]).
|
||||
pub fn with_locks(mut self, locks: crate::drawlock::Locks) -> Self {
|
||||
self.drawing_locks = locks;
|
||||
self
|
||||
}
|
||||
|
||||
/// What the drawing locks have to tell the user (someone else has a drawing open).
|
||||
pub fn take_lock_notes(&mut self) -> Vec<String> {
|
||||
self.drawing_locks.take_notes()
|
||||
self.next_due(now, minutes).map(Duration::from_secs_f64)
|
||||
}
|
||||
|
||||
/// Autosave every drawing with changes not yet autosaved right away, without waiting for
|
||||
@@ -663,7 +641,6 @@ mod native {
|
||||
let _ = h.join();
|
||||
}
|
||||
self.busy.clear();
|
||||
self.drawing_locks.release_all(&self.instance);
|
||||
for path in self.files() {
|
||||
discard(&path);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ mod draw;
|
||||
mod draw2;
|
||||
mod draworder;
|
||||
mod edit;
|
||||
pub mod exchange;
|
||||
mod exchange;
|
||||
pub mod file;
|
||||
mod gripcmds;
|
||||
mod griphot;
|
||||
@@ -47,10 +47,9 @@ mod qselect;
|
||||
mod selecttools;
|
||||
mod settings;
|
||||
mod spline_opts;
|
||||
pub mod table;
|
||||
mod table;
|
||||
mod tolerance;
|
||||
mod trimextend;
|
||||
pub use trimextend::PREVIEW_MAX_PICKS as TRIM_PREVIEW_MAX_PICKS;
|
||||
mod txt2mtxt;
|
||||
pub use txt2mtxt::Txt2MtxtOptions;
|
||||
mod ucs;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
|
||||
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
|
||||
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
|
||||
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
|
||||
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
|
||||
|
||||
@@ -19,7 +19,6 @@ mod edit;
|
||||
mod leader;
|
||||
mod linear;
|
||||
mod mleader;
|
||||
mod qleader;
|
||||
mod radial;
|
||||
|
||||
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
|
||||
@@ -28,7 +27,6 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
|
||||
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
|
||||
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
|
||||
use mleader::{MLeaderM, run_leader, run_mleader};
|
||||
use qleader::{QLeaderM, run_qleader};
|
||||
use radial::{RadialM, run_diameter, run_radius};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -95,10 +93,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["lead"])
|
||||
.params("{points: [[x,y]...], text?}")
|
||||
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
|
||||
CommandSpec::new("qleader", "Quick Leader", run_qleader)
|
||||
.alias(&["le"])
|
||||
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
|
||||
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
|
||||
CommandSpec::new("dimstyle.update", "Update", run_update)
|
||||
.menu(&["Dimension", "Update"])
|
||||
.params("{handles?}")
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -42,13 +42,8 @@ pub(super) struct LeaderM {
|
||||
}
|
||||
|
||||
/// What follows the leader.
|
||||
pub(super) enum Annotation {
|
||||
enum Annotation {
|
||||
Text(Vec<String>),
|
||||
/// QLEADER's text: its lines and its width.
|
||||
Quick {
|
||||
lines: Vec<String>,
|
||||
width: f64,
|
||||
},
|
||||
/// A copy of a text or multiline text: its contents, height, width and style.
|
||||
Copy(MText),
|
||||
None,
|
||||
@@ -247,25 +242,14 @@ struct Sizes {
|
||||
text: f64,
|
||||
above: bool,
|
||||
text_style: String,
|
||||
/// An annotative style: the annotation scale takes DIMSCALE's place, as for an annotative
|
||||
/// dimension, so the sizes are unscaled and the text is annotative.
|
||||
annotative: bool,
|
||||
}
|
||||
|
||||
fn sizes(s: &Session) -> Sizes {
|
||||
// The current style with the drawing's DIM* overrides (what SETVAR DIMTXT… sets).
|
||||
let st = s.doc().ok().and_then(|d| d.dim_style(&style(s)).map(|st| st.with_overrides(&d.dim_overrides()))).unwrap_or_default();
|
||||
let dimscale = s.doc().map_or(1.0, |d| d.header.f64("DIMSCALE", 1.0));
|
||||
let k = if st.annotative { 1.0 } else { st.effective_scale(dimscale) };
|
||||
let k = if st.scale > 0.0 { st.scale } else { 1.0 };
|
||||
let text_style = if st.text_style.is_empty() { "Standard".to_string() } else { st.text_style.clone() };
|
||||
Sizes {
|
||||
arrow: st.arrow_size * k,
|
||||
gap: st.text_gap.abs() * k,
|
||||
text: st.text_height * k,
|
||||
above: st.text_above != 0,
|
||||
text_style,
|
||||
annotative: st.annotative,
|
||||
}
|
||||
Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style }
|
||||
}
|
||||
|
||||
/// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at
|
||||
@@ -279,13 +263,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
|
||||
}
|
||||
|
||||
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
|
||||
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
|
||||
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
|
||||
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
|
||||
let z = sizes(s);
|
||||
// The side the leader runs to: right unless its last segment runs left.
|
||||
let dir = if end.x < before.x { -1.0 } else { 1.0 };
|
||||
let mut vertices = pts.to_vec();
|
||||
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
|
||||
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
|
||||
let d = end - before;
|
||||
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
|
||||
// the leader ends half the text height lower.
|
||||
@@ -326,23 +310,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
|
||||
columns: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Quick { lines, width } => {
|
||||
// The middle of the first line level with the end on the right, of the last line on
|
||||
// the left, whatever DIMTAD.
|
||||
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
|
||||
Some(s.add_entity(EntityKind::MText(MText {
|
||||
insert: v3(end + Vec2::new(dir * z.gap, lift)),
|
||||
height: z.text,
|
||||
width,
|
||||
attach,
|
||||
rotation: 0.0,
|
||||
style: z.text_style,
|
||||
contents: lines.join("\\P"),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Copy(m) => {
|
||||
let lift = if z.above { z.gap } else { 0.0 };
|
||||
let attach = if dir > 0.0 { 4 } else { 6 };
|
||||
@@ -359,12 +326,5 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
|
||||
}
|
||||
Annotation::None => None,
|
||||
};
|
||||
if let (true, Some(t)) = (z.annotative, annotation)
|
||||
&& matches!(s.doc()?.entity(t).map(|e| &e.kind), Some(EntityKind::MText(_)))
|
||||
{
|
||||
let d = s.doc_mut()?;
|
||||
let cur = d.current_anno_scale();
|
||||
d.modify_entity(t, |e| cadcraft_doc::set_annotative(e, true, &cur))?;
|
||||
}
|
||||
Ok(std::iter::once(leader).chain(annotation).collect())
|
||||
}
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
|
||||
//! synthetic drawings): up to three points, a text width, then lines of text.
|
||||
//!
|
||||
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
|
||||
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
|
||||
//! as wide as the width given: with the middle of its first line level with the end when the
|
||||
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
|
||||
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::leader::{Annotation, add_leader};
|
||||
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
|
||||
use crate::cmd::size_param;
|
||||
|
||||
/// QLEADER's default number of leader points.
|
||||
const MAX_POINTS: usize = 3;
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq)]
|
||||
enum Ask {
|
||||
#[default]
|
||||
Points,
|
||||
Width,
|
||||
FirstLine,
|
||||
NextLine,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct QLeaderM {
|
||||
ask: Ask,
|
||||
pts: Vec<Vec2>,
|
||||
width: f64,
|
||||
lines: Vec<String>,
|
||||
}
|
||||
|
||||
impl Interactive for QLeaderM {
|
||||
fn name(&self) -> &'static str {
|
||||
"QLEADER"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let last = self.pts.last().copied();
|
||||
match self.ask {
|
||||
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
|
||||
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
|
||||
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
|
||||
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
|
||||
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
|
||||
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match self.ask {
|
||||
Ask::Points => match i {
|
||||
Input::Point(p) => {
|
||||
self.pts.push(p);
|
||||
if self.pts.len() == MAX_POINTS {
|
||||
self.ask = Ask::Width;
|
||||
}
|
||||
}
|
||||
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
|
||||
// Enter after one point: no leader.
|
||||
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
|
||||
Input::Enter => self.ask = Ask::Width,
|
||||
_ => {}
|
||||
},
|
||||
Ask::Width => {
|
||||
// A point gives the width as its distance from the leader's end; a negative
|
||||
// width is none.
|
||||
let width = match i {
|
||||
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
|
||||
Input::Text(t) => crate::units::parse_distance(&t),
|
||||
Input::Enter => Some(0.0),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let finite = width.filter(|w| w.is_finite());
|
||||
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
|
||||
self.ask = Ask::FirstLine;
|
||||
}
|
||||
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
|
||||
Ask::FirstLine | Ask::NextLine => match i {
|
||||
Input::Text(t) if !t.is_empty() => {
|
||||
self.lines.push(t);
|
||||
self.ask = Ask::NextLine;
|
||||
}
|
||||
Input::Text(_) | Input::Enter => {
|
||||
let lines = std::mem::take(&mut self.lines);
|
||||
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
|
||||
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
|
||||
/// as `width`, placed as the command line places them. The handles of the leader and its text.
|
||||
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("points").is_none_or(Value::is_null) {
|
||||
return Err(bad("qleader", "`points` is required"));
|
||||
}
|
||||
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
|
||||
if !(2..=MAX_POINTS).contains(&pts.len()) {
|
||||
return Err(bad("qleader", "`points` takes 2 or 3 points"));
|
||||
}
|
||||
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
|
||||
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
|
||||
return Err(bad("qleader", "`text` must be a string"));
|
||||
}
|
||||
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
|
||||
// would otherwise sit level with a blank last line. Text with nothing left is no text.
|
||||
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
|
||||
while lines.last().is_some_and(String::is_empty) {
|
||||
lines.pop();
|
||||
}
|
||||
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
|
||||
let hs = add_leader(s, &pts, false, true, ann)?;
|
||||
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -318,46 +318,6 @@ fn dimtedit_and_dimspace() {
|
||||
assert!((dim(&s, b).defpt.y - 1.5).abs() < 1e-9, "{:?}", dim(&s, b).defpt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimspace_auto_uses_the_base_dimension_text_height_and_scale() {
|
||||
let mut s = Session::new();
|
||||
let text_height = 3.0;
|
||||
let scale = 1.5;
|
||||
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXT": 2, "DIMDLI": 7, "DIMSCALE": scale })).unwrap();
|
||||
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
|
||||
s.execute("dimoverride", &json!({ "handles": [base.hex()], "DIMTXT": text_height })).unwrap();
|
||||
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
|
||||
let first = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
|
||||
let second = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [30, 0], "at": [15, 36] })).unwrap());
|
||||
|
||||
s.execute("dimspace", &json!({ "base": base.hex(), "handles": [first.hex(), second.hex()] })).unwrap();
|
||||
|
||||
let positions = [base, first, second].map(|handle| dim(&s, handle).defpt.y);
|
||||
let expected_spacing = 2.0 * text_height * scale;
|
||||
assert!((positions[0] - 4.0).abs() < 1e-9, "positions: {positions:?}");
|
||||
assert!(positions.windows(2).all(|pair| (pair[1] - pair[0] - expected_spacing).abs() < 1e-9), "positions: {positions:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimspace_auto_uses_the_base_dimension_fixed_text_style_height() {
|
||||
let mut s = Session::new();
|
||||
let fixed_height = 2.5;
|
||||
s.execute("style", &json!({ "name": "Fixed", "height": fixed_height })).unwrap();
|
||||
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXSTY": "Fixed", "DIMTXT": 3, "DIMDLI": 7, "DIMSCALE": 2 })).unwrap();
|
||||
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
|
||||
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
|
||||
let target = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
|
||||
|
||||
s.start("dimspace").unwrap();
|
||||
s.input(Input::Pick(vec![base])).unwrap();
|
||||
s.input(Input::Pick(vec![target])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
s.input(Input::Text("Auto".into())).unwrap();
|
||||
|
||||
let spacing = dim(&s, target).defpt.y - dim(&s, base).defpt.y;
|
||||
assert!((spacing - 2.0 * fixed_height).abs() < 1e-9, "spacing: {spacing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_rename_follows_block_definition_text() {
|
||||
let mut s = Session::new();
|
||||
|
||||
+14
-156
@@ -368,36 +368,21 @@ fn preview_copies(s: &Session, hs: &[Handle], mats: impl Iterator<Item = Mat3>)
|
||||
fn other(m: impl Into<String>) -> EngineError {
|
||||
EngineError::Other(m.into())
|
||||
}
|
||||
/// The fill angle (degrees) that gives `b` between `items` items, with the command
|
||||
/// line's own rule and error messages.
|
||||
fn fill_for_between(items: u64, b: f64) -> Result<f64> {
|
||||
if !b.is_finite() || b.abs() < 1e-9 {
|
||||
return Err(other("Requires a nonzero angle."));
|
||||
}
|
||||
let n = items.max(1) as f64;
|
||||
let fill = if (b.abs() * n - 360.0).abs() < 1e-9 { 360.0 * b.signum() } else { b * (n - 1.0).max(1.0) };
|
||||
if fill.abs() > 360.0 + 1e-9 {
|
||||
return Err(other("The items would span more than 360 degrees; enter a smaller angle or fewer items."));
|
||||
}
|
||||
Ok(fill.clamp(-360.0, 360.0))
|
||||
}
|
||||
|
||||
fn fmt(v: f64) -> String {
|
||||
format!("{v:.4}")
|
||||
}
|
||||
|
||||
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
|
||||
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
|
||||
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
|
||||
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
|
||||
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
|
||||
match i {
|
||||
Input::Enter => Ok(Some(cur)),
|
||||
Input::Text(t) => t
|
||||
.trim()
|
||||
.parse::<u64>()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| (1..=max).contains(v))
|
||||
.map(Some)
|
||||
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
|
||||
.map(|v| Some(v as u64))
|
||||
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
|
||||
_ => Ok(None),
|
||||
}
|
||||
@@ -439,7 +424,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
|
||||
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
|
||||
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
|
||||
@@ -707,45 +692,6 @@ impl RectM {
|
||||
};
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
fn live(&self) -> crate::ArrayLive {
|
||||
crate::ArrayLive {
|
||||
kind: crate::ArrayLiveKind::Rectangular,
|
||||
cols: self.cols,
|
||||
rows: self.rows,
|
||||
col_spacing: self.cs,
|
||||
row_spacing: self.rs,
|
||||
levels: self.levels,
|
||||
level_spacing: self.ls,
|
||||
row_elevation: self.elev,
|
||||
associative: self.assoc,
|
||||
items: 0,
|
||||
fill: 0.0,
|
||||
rotate: false,
|
||||
center: None,
|
||||
between: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the array window's values: they are validated first, so a refused value leaves the
|
||||
/// command exactly as it was.
|
||||
fn apply_live(&mut self, s: &Session, v: &crate::ArrayLive) -> Result<()> {
|
||||
if v.kind != crate::ArrayLiveKind::Rectangular {
|
||||
return Err(other("That is a polar array; these are the rectangular parameters."));
|
||||
}
|
||||
if v.cols < 1 || v.rows < 1 || v.levels < 1 {
|
||||
return Err(other("Requires at least one column, row and level."));
|
||||
}
|
||||
let levels = if v.associative { v.levels } else { 1 };
|
||||
check_size(s, v.rows.saturating_mul(v.cols).saturating_mul(levels), self.objs.len())?;
|
||||
if ![v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation].iter().all(|d| d.is_finite()) {
|
||||
return Err(other("Requires finite distances."));
|
||||
}
|
||||
(self.cols, self.rows, self.levels) = (v.cols, v.rows, v.levels);
|
||||
(self.cs, self.rs, self.ls, self.elev) = (v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation);
|
||||
self.assoc = v.associative;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn yes(b: bool) -> &'static str {
|
||||
@@ -758,16 +704,6 @@ fn assoc_prompt(cur: bool) -> Prompt {
|
||||
}
|
||||
|
||||
impl Interactive for RectM {
|
||||
fn array_live(&self) -> Option<crate::ArrayLive> {
|
||||
Some(self.live())
|
||||
}
|
||||
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
|
||||
self.apply_live(s, v)
|
||||
}
|
||||
fn array_set_main(&mut self) -> bool {
|
||||
self.stage = RStage::Main;
|
||||
true
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"ARRAYRECT"
|
||||
}
|
||||
@@ -1060,15 +996,9 @@ impl PolarM {
|
||||
fn ready(&mut self, s: &mut Session) -> Step {
|
||||
self.stage = PStage::Center;
|
||||
self.assoc = assoc_default(s);
|
||||
// Start at the centre prompt, pre-filled with the selection's centre.
|
||||
self.center = Vec2::ZERO;
|
||||
// Rows and levels default to 1.5 × the selection's size apart.
|
||||
if let Ok(d) = s.doc() {
|
||||
let b = bounds(d, &self.objs);
|
||||
let c = b.center();
|
||||
if c.is_finite() {
|
||||
self.center = c;
|
||||
}
|
||||
let size = b.width().max(b.height());
|
||||
if size.is_finite() && size > 1e-9 {
|
||||
(self.rs, self.ls) = (size * 1.5, size * 1.5);
|
||||
@@ -1153,89 +1083,9 @@ impl PolarM {
|
||||
};
|
||||
d.filter(|d| d.is_finite() && d.abs() > 1e-12).map(Some).ok_or_else(|| other("Requires a nonzero distance."))
|
||||
}
|
||||
fn live(&self) -> crate::ArrayLive {
|
||||
crate::ArrayLive {
|
||||
kind: crate::ArrayLiveKind::Polar,
|
||||
cols: 0,
|
||||
rows: self.rows,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: self.rs,
|
||||
levels: self.levels,
|
||||
level_spacing: self.ls,
|
||||
row_elevation: self.elev,
|
||||
associative: self.assoc,
|
||||
items: self.items,
|
||||
fill: self.fill,
|
||||
rotate: self.rotate,
|
||||
center: Some(self.center),
|
||||
between: Some(self.between()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the array window's values: they are validated first, so a refused value leaves the
|
||||
/// command exactly as it was.
|
||||
fn apply_live(&mut self, s: &Session, v: &crate::ArrayLive) -> Result<()> {
|
||||
if v.kind != crate::ArrayLiveKind::Polar {
|
||||
return Err(other("That is a rectangular array; these are the polar parameters."));
|
||||
}
|
||||
if v.items < 1 || v.rows < 1 || v.levels < 1 {
|
||||
return Err(other("Requires at least one item, row and level."));
|
||||
}
|
||||
let levels = if v.associative { v.levels } else { 1 };
|
||||
check_size(s, v.rows.saturating_mul(v.items).saturating_mul(levels), self.objs.len())?;
|
||||
// The Angle between field derives the fill; an edited Fill angle always wins.
|
||||
let between_changed = v.between.is_some_and(|b| !b.is_finite() || (b - self.between()).abs() > 1e-9);
|
||||
let fill_changed = (v.fill - self.fill).abs() > 1e-9;
|
||||
let fill = match v.between {
|
||||
Some(b) if between_changed && !fill_changed => fill_for_between(v.items, b)?,
|
||||
_ => v.fill,
|
||||
};
|
||||
if !fill.is_finite() || fill.abs() <= 0.0 || fill.abs() > 360.0 {
|
||||
return Err(other("Requires a fill angle between -360 and 360 degrees (not 0)."));
|
||||
}
|
||||
if ![v.row_spacing, v.level_spacing, v.row_elevation].iter().all(|d| d.is_finite()) {
|
||||
return Err(other("Requires finite distances."));
|
||||
}
|
||||
if let Some(c) = v.center
|
||||
&& !c.is_finite()
|
||||
{
|
||||
return Err(other("Requires a finite center point."));
|
||||
}
|
||||
(self.items, self.rows, self.levels) = (v.items, v.rows, v.levels);
|
||||
(self.rs, self.ls, self.elev) = (v.row_spacing, v.level_spacing, v.row_elevation);
|
||||
self.fill = fill;
|
||||
self.rotate = v.rotate;
|
||||
self.assoc = v.associative;
|
||||
// The centre is always taken, but the command only moves on when it actually changed;
|
||||
// the window copying the prefilled centre straight back never advances.
|
||||
if let Some(c) = v.center {
|
||||
if c != self.center && self.stage == PStage::Center {
|
||||
self.stage = PStage::Main;
|
||||
}
|
||||
self.center = c;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for PolarM {
|
||||
fn array_live(&self) -> Option<crate::ArrayLive> {
|
||||
Some(self.live())
|
||||
}
|
||||
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
|
||||
self.apply_live(s, v)
|
||||
}
|
||||
fn array_set_main(&mut self) -> bool {
|
||||
if matches!(self.stage, PStage::Center | PStage::CenterBase | PStage::CenterBaseKey) {
|
||||
return false;
|
||||
}
|
||||
self.stage = PStage::Main;
|
||||
true
|
||||
}
|
||||
fn array_pick_center(&mut self) -> bool {
|
||||
self.stage = PStage::Center;
|
||||
true
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"ARRAYPOLAR"
|
||||
}
|
||||
@@ -1391,7 +1241,15 @@ impl Interactive for PolarM {
|
||||
(Between, Input::Enter) => Main,
|
||||
(Between, _) => match angle(&i, self.between(), &s.angle_settings())? {
|
||||
Some(b) => {
|
||||
self.fill = fill_for_between(self.items, b)?;
|
||||
if b.abs() < 1e-9 {
|
||||
return Err(other("Requires a nonzero angle."));
|
||||
}
|
||||
let n = self.items as f64;
|
||||
let fill = if (b.abs() * n - 360.0).abs() < 1e-9 { 360.0 * b.signum() } else { b * (n - 1.0).max(1.0) };
|
||||
if fill.abs() > 360.0 + 1e-9 {
|
||||
return Err(other("The items would span more than 360 degrees; enter a smaller angle or fewer items."));
|
||||
}
|
||||
self.fill = fill;
|
||||
Main
|
||||
}
|
||||
None => stage,
|
||||
|
||||
+69
-221
@@ -15,7 +15,7 @@ use super::machines::{SelOutcome, SelectPhase, number};
|
||||
use super::{CommandSpec, bad, bool_or, f64_or, find_command, ok, point_param, point_req, point_value, str_param, targets};
|
||||
|
||||
use super::has_doc;
|
||||
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step};
|
||||
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
mod attdef;
|
||||
mod attedit;
|
||||
@@ -43,14 +43,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.menu(&["Insert", "Block..."])
|
||||
.alias(&["i", "-insert", "ddinsert"])
|
||||
.params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}")
|
||||
.interactive(|s| Ok(Box::new(InsertM { person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
|
||||
.interactive(|_| Ok(Box::new(InsertM::default()))),
|
||||
CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette)
|
||||
.params("{references?: bool (default true; counting reads every object)} → {blocks: [{name, description, references?}], truncated} (the app opens the Blocks palette instead)")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("minsert", "Multiple Insert", run_minsert)
|
||||
.params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}")
|
||||
.interactive(|s| Ok(Box::new(InsertM { minsert: true, person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
|
||||
.interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))),
|
||||
CommandSpec::new("attdef", "Define Attributes...", run_attdef)
|
||||
.menu(&["Draw", "Block", "Define Attributes..."])
|
||||
.alias(&["att", "-attdef"])
|
||||
@@ -73,14 +73,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
|
||||
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
|
||||
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
|
||||
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
|
||||
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
|
||||
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
|
||||
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("purge", "Purge", purge::run)
|
||||
.alias(&["pu", "-purge"])
|
||||
@@ -403,14 +403,13 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// MINSERT's JSON form: INSERT's parameters and the grid.
|
||||
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
|
||||
let count = |key: &str| -> Result<u32> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(1),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|n| (1..=Grid::MAX).contains(n))
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
|
||||
.map(|n| n as u32)
|
||||
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
|
||||
}
|
||||
};
|
||||
@@ -834,35 +833,11 @@ enum InsStage {
|
||||
/// rows).
|
||||
Cell(Vec2),
|
||||
ColSpacing,
|
||||
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
|
||||
/// asks "Specify second point:"), from the first.
|
||||
Second(TwoPoints, Vec2),
|
||||
Attribs,
|
||||
/// A Verify attribute asked again.
|
||||
Verify,
|
||||
}
|
||||
|
||||
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
|
||||
/// distance, the preset rotation by their direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum TwoPoints {
|
||||
Scale,
|
||||
Axis(usize),
|
||||
Rotation,
|
||||
ColSpacing,
|
||||
}
|
||||
|
||||
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
|
||||
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
|
||||
// angle, where a point gives the distance from the insertion point, and where only a number does.
|
||||
const NONZERO: &str = "Value must be nonzero.";
|
||||
/// Exploded INSERT's scale factor, which must be positive.
|
||||
const POSITIVE: &str = "Value must be positive and nonzero.";
|
||||
const TWO_POINTS: &str = "Requires numeric distance or two points.";
|
||||
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
|
||||
const SECOND_POINT: &str = "Requires numeric distance or second point.";
|
||||
const NUMERIC: &str = "Requires numeric value.";
|
||||
|
||||
#[derive(Default)]
|
||||
struct InsertM {
|
||||
stage: InsStage,
|
||||
@@ -883,16 +858,6 @@ struct InsertM {
|
||||
rotation: Option<f64>,
|
||||
/// The attributes asked for: tag, prompt, default value, and Verify (asked again).
|
||||
attdefs: Vec<(String, String, String, bool)>,
|
||||
/// How many of `attdefs` have their value: counted here, not by `values`, whose key is the
|
||||
/// tag, so two definitions with one tag are still each asked once.
|
||||
asked: usize,
|
||||
/// ATTDIA 1 and a person started the command: the values are asked for in the Edit
|
||||
/// Attributes dialog. A script, LISP routine or JSON call that opened INSERT has nobody to
|
||||
/// answer a dialog, so it asks at the command line, even after the program is done.
|
||||
dialog: bool,
|
||||
/// A person started this command ([`Session::command_origin`]), fixed for its whole life:
|
||||
/// only then may ATTDIA 1 open the dialog.
|
||||
person: bool,
|
||||
values: serde_json::Map<String, Value>,
|
||||
/// Verify attributes asked again so far.
|
||||
verified: usize,
|
||||
@@ -924,7 +889,7 @@ impl InsertM {
|
||||
s.echo("Enter attribute values");
|
||||
}
|
||||
// Then the Verify attributes are asked again, with the values typed.
|
||||
if self.stage == InsStage::Attribs && self.asked >= self.attdefs.len() && self.verified < self.verifying().len() {
|
||||
if self.stage == InsStage::Attribs && self.values.len() >= self.attdefs.len() && self.verified < self.verifying().len() {
|
||||
if self.verified == 0 {
|
||||
s.echo("Verify attribute values");
|
||||
}
|
||||
@@ -932,7 +897,7 @@ impl InsertM {
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.stage == InsStage::Attribs
|
||||
&& self.asked >= self.attdefs.len()
|
||||
&& self.values.len() >= self.attdefs.len()
|
||||
&& let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation)
|
||||
{
|
||||
let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values, self.grid())?;
|
||||
@@ -983,8 +948,6 @@ impl InsertM {
|
||||
s.echo(format!("Block \"{name}\" not found."));
|
||||
return Ok(());
|
||||
};
|
||||
// A program cannot click the dialog: it asks at the command line, as ATTDIA 0 does.
|
||||
self.dialog = s.settings.attdia && self.person;
|
||||
self.attdefs = if self.explode || !s.settings.attreq {
|
||||
Vec::new()
|
||||
} else {
|
||||
@@ -999,7 +962,6 @@ impl InsertM {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
self.asked = 0;
|
||||
self.name = Some(b.name.clone());
|
||||
self.stage = InsStage::Point;
|
||||
Ok(())
|
||||
@@ -1043,66 +1005,6 @@ impl InsertM {
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// The Scale preset `f` for every axis.
|
||||
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
|
||||
self.scale = Some(Vec2::new(f, f));
|
||||
self.z_scale = Some(f.abs());
|
||||
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
|
||||
self.axes = [Some(f), Some(f), Some(f.abs())];
|
||||
// Exploded insertion asks its one scale factor after the insertion point.
|
||||
if self.at.is_some() {
|
||||
return self.advance(s);
|
||||
}
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
/// One axis preset: the others are 1, and no scale factors are asked after the point.
|
||||
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
|
||||
if let Some(a) = self.axes.get_mut(ax) {
|
||||
*a = Some(f);
|
||||
}
|
||||
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
self.z_scale = Some(z.abs());
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
|
||||
self.rotation = Some(r);
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
|
||||
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
|
||||
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
|
||||
/// the first prompt again.
|
||||
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
|
||||
let (first, refused) = match what {
|
||||
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
|
||||
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
|
||||
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
|
||||
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
|
||||
};
|
||||
self.stage = first;
|
||||
match (what, i) {
|
||||
(TwoPoints::ColSpacing, Input::Point(b)) => {
|
||||
self.col_spacing = Some(a.dist(b));
|
||||
self.advance(s)
|
||||
}
|
||||
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
|
||||
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
|
||||
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
|
||||
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
|
||||
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
|
||||
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
|
||||
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
|
||||
_ => Err(EngineError::Other(refused.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
|
||||
@@ -1110,14 +1012,8 @@ fn distance(t: &str) -> Result<f64> {
|
||||
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
|
||||
}
|
||||
|
||||
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
|
||||
/// isn't a number the prompt's own message.
|
||||
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
|
||||
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
|
||||
if v == 0.0 {
|
||||
return Err(EngineError::Other(NONZERO.into()));
|
||||
}
|
||||
Ok(v)
|
||||
fn nonzero(t: &str) -> Result<f64> {
|
||||
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
|
||||
}
|
||||
|
||||
impl Interactive for InsertM {
|
||||
@@ -1138,33 +1034,24 @@ impl Interactive for InsertM {
|
||||
}
|
||||
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
|
||||
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
|
||||
// Exploded, after the insertion point, it takes a number only.
|
||||
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
|
||||
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
|
||||
InsStage::PresetAxis(i) => {
|
||||
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
|
||||
}
|
||||
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
|
||||
// still comes from a click or LISP.
|
||||
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
|
||||
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
|
||||
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
|
||||
// Text is read here, not taken as a distance along the rubber band: the core console
|
||||
// refuses 5 at this prompt (measured).
|
||||
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
|
||||
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
|
||||
InsStage::XScale => {
|
||||
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
|
||||
}
|
||||
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
|
||||
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
|
||||
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
|
||||
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
|
||||
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
|
||||
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
|
||||
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
|
||||
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
|
||||
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
|
||||
InsStage::Attribs => {
|
||||
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
|
||||
let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
|
||||
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
|
||||
// No default shown when there is none ("Value:", AutoCAD 2024), not "<>".
|
||||
if default.is_empty() { p } else { p.default(default) }
|
||||
@@ -1238,58 +1125,45 @@ impl Interactive for InsertM {
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
}
|
||||
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
|
||||
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
|
||||
// nonzero.", measured).
|
||||
InsStage::PresetScale if self.at.is_some() => {
|
||||
return match i {
|
||||
Input::Text(t) => {
|
||||
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
|
||||
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
|
||||
self.preset_scale(s, f)
|
||||
}
|
||||
Input::Enter => self.preset_scale(s, 1.0),
|
||||
_ => Err(EngineError::Other(NUMERIC.into())),
|
||||
};
|
||||
}
|
||||
// A point at a preset is the first of two (AutoCAD 2024, measured).
|
||||
InsStage::PresetScale => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Scale, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
|
||||
Input::Enter => self.preset_scale(s, 1.0),
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
let f = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => 1.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
self.scale = Some(Vec2::new(f, f));
|
||||
self.z_scale = Some(f.abs());
|
||||
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
|
||||
self.axes = [Some(f), Some(f), Some(f.abs())];
|
||||
// Exploded insertion asks its one scale factor after the insertion point.
|
||||
if self.at.is_some() {
|
||||
return self.advance(s);
|
||||
}
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
// One axis preset: the others are 1, and no scale factors are asked after the point.
|
||||
InsStage::PresetAxis(ax) => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
|
||||
Input::Enter => self.preset_axis(ax, 1.0),
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
let f = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => 1.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if let Some(a) = self.axes.get_mut(ax) {
|
||||
*a = Some(f);
|
||||
}
|
||||
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
self.z_scale = Some(z.abs());
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
InsStage::PresetRotation => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Rotation, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => {
|
||||
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
|
||||
self.preset_rotation(r)
|
||||
}
|
||||
Input::Enter => self.preset_rotation(0.0),
|
||||
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
|
||||
};
|
||||
self.rotation = Some(match i {
|
||||
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
|
||||
Input::Enter => 0.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
});
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
|
||||
InsStage::XScale => match i {
|
||||
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
|
||||
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
|
||||
@@ -1298,7 +1172,7 @@ impl Interactive for InsertM {
|
||||
return self.corner_scale(s, sc);
|
||||
}
|
||||
Input::Text(t) => {
|
||||
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
|
||||
self.x_scale = Some(nonzero(&t)?);
|
||||
self.stage = InsStage::YScale;
|
||||
}
|
||||
Input::Enter => {
|
||||
@@ -1315,11 +1189,10 @@ impl Interactive for InsertM {
|
||||
}
|
||||
InsStage::YScale => {
|
||||
let x = self.x_scale.unwrap_or(1.0);
|
||||
// A number only: AutoCAD 2024 refuses a point here (measured).
|
||||
let y = match i {
|
||||
Input::Text(t) => nonzero(&t, NUMERIC)?,
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => x,
|
||||
_ => return Err(EngineError::Other(NUMERIC.into())),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
if self.xyz {
|
||||
@@ -1328,15 +1201,11 @@ impl Interactive for InsertM {
|
||||
}
|
||||
return self.advance(s);
|
||||
}
|
||||
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
|
||||
InsStage::ZScale => {
|
||||
self.z_scale = Some(match i {
|
||||
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
|
||||
Input::Point(p) => {
|
||||
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
|
||||
}
|
||||
_ => return Err(EngineError::Other(SECOND_POINT.into())),
|
||||
_ => return Ok(Step::Continue),
|
||||
});
|
||||
return self.advance(s);
|
||||
}
|
||||
@@ -1350,14 +1219,17 @@ impl Interactive for InsertM {
|
||||
return self.advance(s);
|
||||
}
|
||||
InsStage::Rows | InsStage::Cols => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
|
||||
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
|
||||
let n = match i {
|
||||
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
|
||||
Input::Enter => Some(1),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
|
||||
Input::Text(t) => t
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
|
||||
.map(|v| v as u32)
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
|
||||
Input::Enter => 1,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if self.stage == InsStage::Rows {
|
||||
self.rows = Some(n);
|
||||
} else {
|
||||
@@ -1379,31 +1251,19 @@ impl Interactive for InsertM {
|
||||
return self.advance(s);
|
||||
}
|
||||
}
|
||||
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
|
||||
InsStage::ColSpacing => {
|
||||
return match i {
|
||||
Input::Text(t) => {
|
||||
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
|
||||
self.advance(s)
|
||||
}
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
};
|
||||
if let Input::Text(t) = i {
|
||||
self.col_spacing = Some(distance(&t)?);
|
||||
return self.advance(s);
|
||||
}
|
||||
}
|
||||
InsStage::Attribs => {
|
||||
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
|
||||
let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
|
||||
let v = match i {
|
||||
Input::Text(t) => t,
|
||||
// A canvas click is no answer to a text prompt: the dialog stays up and the
|
||||
// attribute is asked for again, as Verify does. Enter keeps the default.
|
||||
Input::Point(_) => return Ok(Step::Continue),
|
||||
_ => default,
|
||||
};
|
||||
self.values.insert(tag, Value::String(v));
|
||||
self.asked += 1;
|
||||
return self.advance(s);
|
||||
}
|
||||
// Enter keeps the value typed.
|
||||
@@ -1441,18 +1301,6 @@ impl Interactive for InsertM {
|
||||
self.grid().apply(&mut ins);
|
||||
vec![EntityKind::Insert(ins)]
|
||||
}
|
||||
fn attribute_entry(&self) -> Option<AttribEntry> {
|
||||
// Only before the first answer: values typed at the command line go on there.
|
||||
if !self.dialog || self.stage != InsStage::Attribs || self.asked > 0 || self.attdefs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let rows = self
|
||||
.attdefs
|
||||
.iter()
|
||||
.map(|(tag, prompt, default, verify)| AttribAsk { tag: tag.clone(), prompt: prompt.clone(), default: default.clone(), verify: *verify })
|
||||
.collect();
|
||||
Some(AttribEntry::idle(self.name.clone().unwrap_or_default(), rows))
|
||||
}
|
||||
}
|
||||
|
||||
mod attribs;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
|
||||
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::curves::KW;
|
||||
@@ -102,14 +102,17 @@ impl Interactive for AttdispM {
|
||||
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
|
||||
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
|
||||
let m = ins.transform(blk.base.xy());
|
||||
// The reference's attributes by tag, gathered once for all the definitions (#1923).
|
||||
let carried = ins.attribs_by_tag();
|
||||
defs.iter()
|
||||
.map(|ad| {
|
||||
let mut k = EntityKind::Text(ad.text.clone());
|
||||
k.transform(&m);
|
||||
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
|
||||
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
t.value = ins
|
||||
.attribs
|
||||
.iter()
|
||||
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
|
||||
.map(|a| a.text.value.clone())
|
||||
.unwrap_or_else(|| ad.text.value.clone());
|
||||
Attrib {
|
||||
tag: ad.tag.clone(),
|
||||
text: t,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! become text with the values they show instead of the block's attribute definitions.
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::machines::SelectRun;
|
||||
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
|
||||
let EntityKind::Insert(ins) = &e.kind else { return None };
|
||||
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
|
||||
// The block's definitions by tag, gathered once for all the attributes (#1923).
|
||||
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
|
||||
for a in ins.attribs.iter().filter(|a| !a.invisible) {
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
None => EntityKind::Text(a.text.clone()),
|
||||
};
|
||||
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
|
||||
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
|
||||
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
|
||||
/// block's objects.
|
||||
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
|
||||
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
|
||||
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
|
||||
/// objects.
|
||||
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
|
||||
let def =
|
||||
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
|
||||
// An attribute without a definition follows the reference.
|
||||
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
|
||||
let mut c = props.over(&base);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
|
||||
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
|
||||
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
|
||||
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
|
||||
//! at a distance's grip sets the distance.
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
|
||||
use cadcraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -30,8 +30,7 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(Value::as_i64)
|
||||
.and_then(|n| i32::try_from(n).ok())
|
||||
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
|
||||
let part =
|
||||
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
|
||||
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
|
||||
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
|
||||
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
|
||||
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
|
||||
@@ -47,25 +46,11 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
|
||||
return Err("the reference is on a locked layer".into());
|
||||
}
|
||||
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
|
||||
drag_in(s, &mut d, h, node, part, to)?;
|
||||
dynblock::drag_grip(&mut d, h, node, part, to)?;
|
||||
*s.doc_mut().map_err(|e| e.to_string())? = d;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
|
||||
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
|
||||
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
|
||||
let alignment = dynblock::reference(d, h)
|
||||
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
|
||||
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
|
||||
if !alignment {
|
||||
return dynblock::drag_grip(d, h, node, part, to);
|
||||
}
|
||||
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, s.viewport_frozen(), h);
|
||||
dynblock::align_grip(d, h, node, to, near)
|
||||
}
|
||||
|
||||
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
|
||||
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
|
||||
/// reference's (as the renderer draws a block's contents).
|
||||
@@ -111,16 +96,13 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
|
||||
.collect();
|
||||
// An attribute draws with its definition's properties, except those set on it.
|
||||
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
|
||||
// The block's definitions by tag, gathered once for all the attributes (#1923).
|
||||
let defs = b.attdefs_by_tag();
|
||||
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
|
||||
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
|
||||
let def = b.entities.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
|
||||
_ => None,
|
||||
});
|
||||
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
None => EntityKind::Text(a.text.clone()),
|
||||
};
|
||||
Entity { handle: Handle(0), common, kind }
|
||||
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
|
||||
}));
|
||||
out
|
||||
}
|
||||
@@ -132,16 +114,11 @@ struct DynGripEdit {
|
||||
part: GripPart,
|
||||
/// Where the grip is (the rubber band's start).
|
||||
from: Vec2,
|
||||
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
|
||||
/// The property it changes, and whether it is a distance (a typed number sets it).
|
||||
property: String,
|
||||
shape: GripShape,
|
||||
/// Where the grip can stop (a value list or increments): tick marks across its travel.
|
||||
stops: Vec<(Vec2, Vec2)>,
|
||||
distance: bool,
|
||||
}
|
||||
|
||||
/// Half a tick mark's length, in pixels.
|
||||
const TICK_PX: f64 = 6.0;
|
||||
|
||||
impl Interactive for DynGripEdit {
|
||||
fn name(&self) -> &'static str {
|
||||
"GRIP"
|
||||
@@ -152,22 +129,19 @@ impl Interactive for DynGripEdit {
|
||||
}
|
||||
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let (msg, accept) = match self.shape {
|
||||
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
|
||||
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
|
||||
GripShape::Alignment => ("Specify point location", Accept::POINT),
|
||||
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
|
||||
let (msg, accept) = if self.distance {
|
||||
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
|
||||
} else {
|
||||
("** STRETCH ** Specify stretch point", Accept::POINT)
|
||||
};
|
||||
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
|
||||
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
|
||||
if self.shape == GripShape::Rotation { p.angle() } else { p }
|
||||
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
|
||||
}
|
||||
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let to = match i {
|
||||
Input::Point(p) => p,
|
||||
Input::Deferred(d) => d.at,
|
||||
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
|
||||
Input::Text(t) if self.distance => {
|
||||
let mut d = s.doc()?.clone();
|
||||
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
|
||||
*s.doc_mut()? = d;
|
||||
@@ -181,30 +155,9 @@ impl Interactive for DynGripEdit {
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
let half = TICK_PX * s.pixel_size();
|
||||
let mut out: Vec<EntityKind> = self
|
||||
.stops
|
||||
.iter()
|
||||
.map(|(at, way)| {
|
||||
let n = way.perp() * half;
|
||||
crate::cmd::helpers::line(*at - n, *at + n)
|
||||
})
|
||||
.collect();
|
||||
out.push(crate::cmd::helpers::line(self.from, c));
|
||||
out
|
||||
}
|
||||
|
||||
/// A rotation grip's angle at the cursor, as Properties will show it.
|
||||
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
|
||||
if self.shape != GripShape::Rotation {
|
||||
return None;
|
||||
}
|
||||
let mut d = s.doc().ok()?.clone();
|
||||
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
|
||||
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
|
||||
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
|
||||
/// The rubber band from the grip.
|
||||
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
vec![crate::cmd::helpers::line(self.from, c)]
|
||||
}
|
||||
|
||||
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
|
||||
@@ -212,7 +165,7 @@ impl Interactive for DynGripEdit {
|
||||
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let mut d = d.clone();
|
||||
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
|
||||
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
|
||||
Ok(()) => drawn(&d, self.handle),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
@@ -221,8 +174,8 @@ impl Interactive for DynGripEdit {
|
||||
|
||||
impl Session {
|
||||
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
|
||||
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
|
||||
/// its choices and sets them with `blocks.reference.set`.
|
||||
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
@@ -231,67 +184,17 @@ impl Session {
|
||||
.into_iter()
|
||||
.find(|g| g.node == node && g.part == part)
|
||||
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
|
||||
if matches!(g.shape, GripShape::List | GripShape::Flip) {
|
||||
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
|
||||
if g.shape == GripShape::List {
|
||||
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
|
||||
}
|
||||
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
|
||||
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
|
||||
let machine = crate::guard::Guarded::wrap(Box::new(edit));
|
||||
let st = self.state()?;
|
||||
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
|
||||
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
|
||||
self.pending_window = None;
|
||||
self.point_mods.clear();
|
||||
self.echo(label);
|
||||
self.echo("** STRETCH **");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
|
||||
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
|
||||
// alike up to their last characters, no attribute's a definition's. Looking for each
|
||||
// attribute's definition by comparing it with every one cost N x N comparisons of whole
|
||||
// tags for each preview (many seconds here); the definitions gathered by tag once cost
|
||||
// milliseconds.
|
||||
const N: usize = 4000;
|
||||
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
|
||||
let attrib = |tag: String| cadcraft_doc::Attrib {
|
||||
tag,
|
||||
text: cadcraft_doc::Text {
|
||||
insert: cadcraft_geom::Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: "v".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
},
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut blk = cadcraft_doc::Block::new("B");
|
||||
for (h, i) in (1..).zip(0..N) {
|
||||
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
|
||||
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert_eq!(drawn(&d, h).len(), N);
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,9 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{
|
||||
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
|
||||
};
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -48,7 +46,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some("*") => write(s, "wblock", &path, Source::Whole)?,
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
@@ -56,7 +54,6 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -67,7 +64,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -83,17 +80,16 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
|
||||
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
|
||||
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
|
||||
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
|
||||
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -119,19 +115,14 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
let version = own_version(&d, path);
|
||||
let lost = lost_writing(&d, path, version);
|
||||
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost, version, notes))
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
}
|
||||
|
||||
/// Say on the command line what the file written at `path` and `version` left out, and what a
|
||||
/// DWG keeps only in part (`notes`).
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
for note in notes {
|
||||
s.echo(note);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
|
||||
@@ -350,7 +341,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -361,8 +352,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost, version, notes)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost, notes);
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
@@ -134,7 +134,7 @@ struct Ctx {
|
||||
}
|
||||
|
||||
/// The folder of the host drawing at `host` (a file path).
|
||||
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
|
||||
fn folder(host: Option<&Path>) -> Option<PathBuf> {
|
||||
let p = host?.parent()?;
|
||||
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
|
||||
}
|
||||
@@ -293,17 +293,8 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
|
||||
Ok(out.is_file().then_some(out))
|
||||
}
|
||||
|
||||
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
|
||||
/// binary DXF sentinel).
|
||||
const HEAD_BYTES: usize = 4096;
|
||||
|
||||
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
|
||||
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
|
||||
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
|
||||
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
|
||||
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
|
||||
/// binary DXF) describes the same read.
|
||||
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
|
||||
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
@@ -312,9 +303,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
|
||||
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
|
||||
let limit = MAX_XREF_BYTES.min(left);
|
||||
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
|
||||
let meta = f.metadata().map_err(|e| e.to_string())?;
|
||||
let len = meta.len();
|
||||
let before = stamp_of(&meta);
|
||||
let len = f.metadata().map_err(|e| e.to_string())?.len();
|
||||
let too_big = || {
|
||||
if limit < MAX_XREF_BYTES {
|
||||
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
|
||||
@@ -332,10 +321,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
|
||||
return Err(too_big());
|
||||
}
|
||||
cx.bytes = cx.bytes.saturating_add(n);
|
||||
let after = f.metadata().ok().as_ref().and_then(stamp_of);
|
||||
let read_as = before.filter(|b| Some(*b) == after);
|
||||
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
|
||||
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
|
||||
(hooks.read)(&bytes, &file.to_string_lossy())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
@@ -344,33 +330,6 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
|
||||
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
|
||||
/// system gives it: counted from 1970, a file dated before then would have none and always look
|
||||
/// changed.
|
||||
pub(crate) type Stamp = (u64, std::time::SystemTime);
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
|
||||
Some((m.len(), m.modified().ok()?))
|
||||
}
|
||||
|
||||
/// The [`Stamp`] of the file at `file` now.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
|
||||
stamp_of(&std::fs::metadata(file).ok()?)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
|
||||
/// first bytes of the bytes read (see [`read`]).
|
||||
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
|
||||
read(file, &mut Ctx::new(None))
|
||||
}
|
||||
|
||||
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
|
||||
/// own path.
|
||||
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
|
||||
@@ -434,14 +393,8 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
|
||||
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
|
||||
clear(d, &key);
|
||||
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
|
||||
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
|
||||
Ok(()) => {
|
||||
// This drawing's own baseline: another drawing loading the file later doesn't move it.
|
||||
if let Some(b) = d.blocks.get_mut(&key) {
|
||||
Arc::make_mut(b).xref_stamp = read_as;
|
||||
}
|
||||
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
|
||||
}
|
||||
Ok((x, file)) => match import(d, &key, &x, cx) {
|
||||
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
|
||||
Err(e) => {
|
||||
// Whatever made it in before the failure goes again. A fetch that failed imported
|
||||
// nothing, so it doesn't pay for a second scan of the block table.
|
||||
@@ -456,13 +409,7 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
|
||||
}
|
||||
|
||||
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
|
||||
fn fetch(
|
||||
path: &str,
|
||||
host: Option<&Path>,
|
||||
chosen: bool,
|
||||
cx: &mut Ctx,
|
||||
depth: usize,
|
||||
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
|
||||
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
|
||||
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Err(unresolved("xrefs are nested too deeply"));
|
||||
@@ -476,7 +423,7 @@ fn fetch(
|
||||
return Err(unresolved("too many referenced files"));
|
||||
}
|
||||
cx.files += 1;
|
||||
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
|
||||
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
|
||||
cx.chain.push(canon);
|
||||
let nested: Vec<String> =
|
||||
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
|
||||
@@ -487,20 +434,15 @@ fn fetch(
|
||||
}
|
||||
}
|
||||
cx.chain.pop();
|
||||
Ok((x, file, read_as))
|
||||
}
|
||||
|
||||
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
|
||||
/// space and every block's.
|
||||
pub(crate) fn object_count(x: &Drawing) -> usize {
|
||||
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
|
||||
Ok((x, file))
|
||||
}
|
||||
|
||||
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
|
||||
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
|
||||
/// host's settings, so layer changes survive a reload).
|
||||
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
|
||||
cx.objects = cx.objects.saturating_add(object_count(x));
|
||||
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
|
||||
cx.objects = cx.objects.saturating_add(count);
|
||||
if cx.objects > MAX_XREF_OBJECTS {
|
||||
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
|
||||
}
|
||||
|
||||
@@ -79,27 +79,17 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
|
||||
let defs = s.clipboard_source.as_ref().map(|c| c.defs.clone());
|
||||
let space = s.space();
|
||||
let d = s.doc_mut()?;
|
||||
let renames = defs.as_ref().map(|x| merge(d, x)).unwrap_or_default();
|
||||
let renames = defs.map(|x| merge(d, &x)).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
let mut copies = Vec::new();
|
||||
for e in &ents {
|
||||
let old_h = e.handle;
|
||||
let mut e = adopt(d, e, &renames);
|
||||
e.kind.transform(m);
|
||||
d.ensure_layer(&e.common.layer);
|
||||
out.push(e.handle);
|
||||
copies.push((old_h, e.handle));
|
||||
if let Some(st) = d.space_mut(&space) {
|
||||
st.push(e);
|
||||
}
|
||||
}
|
||||
if let Some(c) = &defs
|
||||
&& !c.groups.is_empty()
|
||||
{
|
||||
super::groups::replicate_groups_from(d, &c.groups, &copies);
|
||||
} else {
|
||||
super::groups::replicate_groups_for_copies(d, &copies);
|
||||
}
|
||||
s.set_selection(out.clone());
|
||||
Ok(out)
|
||||
}
|
||||
@@ -275,15 +265,13 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
|
||||
}
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header = src.header.clone();
|
||||
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
|
||||
d.layers = pick(&src.layers, &used.layers, |l| &l.name);
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
|
||||
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
|
||||
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into();
|
||||
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
|
||||
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
|
||||
let ent_handles: HashSet<Handle> = ents.iter().map(|e| e.handle).collect();
|
||||
d.groups = src.groups.iter().filter(|g| !g.members.is_empty() && g.members.iter().all(|m| ent_handles.contains(m))).cloned().collect();
|
||||
d.layouts.clear();
|
||||
d
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
|
||||
if let Some(a) = annotative {
|
||||
st.annotative = a;
|
||||
}
|
||||
let name = match d.dim_styles.by_name_mut(&name) {
|
||||
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(existing) if replace => {
|
||||
let kept = existing.name.clone();
|
||||
*existing = DimStyle { name: kept.clone(), ..st };
|
||||
|
||||
@@ -9,7 +9,10 @@ use super::helpers::{arc, circle, line, lwpoly, polygon_from_edge, polygon_typed
|
||||
|
||||
use super::machines::number;
|
||||
use super::pline_opts::{Outcome, PlineAsk};
|
||||
use super::{CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param};
|
||||
use super::{
|
||||
CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, find_command, point_param, point_req, point_value, points_param, size_param,
|
||||
str_param,
|
||||
};
|
||||
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, snap};
|
||||
|
||||
@@ -29,8 +32,7 @@ use line_pline::{LineM, PlineM, run_line, run_pline};
|
||||
use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray};
|
||||
use polygon::{PolygonM, run_polygon};
|
||||
use solid::{SolidM, run_solid};
|
||||
pub(super) use spline::SplineM;
|
||||
use spline::run_spline;
|
||||
use spline::{SplineM, run_spline};
|
||||
|
||||
use text::{MTextM, TextM, run_mtext, run_text};
|
||||
pub(crate) use text::{justify, justify_prompt};
|
||||
@@ -47,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pline", "Polyline", run_pline)
|
||||
.menu(&["Draw", "Polyline"])
|
||||
.alias(&["pl"])
|
||||
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
|
||||
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
|
||||
.interactive(|_| Ok(Box::new(PlineM::default()))),
|
||||
CommandSpec::new("circle", "Circle", run_circle)
|
||||
.menu(&["Draw", "Circle", "Center, Radius"])
|
||||
@@ -62,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
|
||||
.menu(&["Draw", "Rectangle"])
|
||||
.alias(&["rec", "rectangle"])
|
||||
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
|
||||
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
|
||||
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
|
||||
CommandSpec::new("polygon", "Polygon", run_polygon)
|
||||
.menu(&["Draw", "Polygon"])
|
||||
|
||||
@@ -45,21 +45,15 @@ fn current_elevation(s: &Session) -> Result<f64> {
|
||||
|
||||
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
|
||||
let mut vertex_widths = false;
|
||||
for v in raw.into_iter().flatten() {
|
||||
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
|
||||
size_param("pline", v, "startWidth", true)?;
|
||||
size_param("pline", v, "endWidth", true)?;
|
||||
}
|
||||
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
|
||||
if vs.len() < 2 {
|
||||
return Err(bad("pline", "`vertices` needs at least 2 points"));
|
||||
}
|
||||
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
|
||||
// give their own widths).
|
||||
let width = match size_param("pline", p, "width", true)? {
|
||||
Some(w) => w,
|
||||
None if vertex_widths => 0.0,
|
||||
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
|
||||
};
|
||||
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
@@ -272,11 +266,8 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
let w = s.doc()?.header.f64("PLINEWID", 0.0);
|
||||
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
@@ -325,11 +316,6 @@ impl Interactive for PlineM {
|
||||
self.end_w = self.start_w;
|
||||
}
|
||||
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
|
||||
if self.asking_width == 0 {
|
||||
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
|
||||
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
|
||||
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
|
||||
@@ -393,10 +379,6 @@ impl Interactive for PlineM {
|
||||
l.bulge = 0.0;
|
||||
(l.start_width, l.end_width) = (0.0, 0.0);
|
||||
}
|
||||
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
|
||||
// to "Specify next point", where `_L` is Length, not arc mode's Line).
|
||||
let n = self.verts.len();
|
||||
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
|
||||
self.sync(s, false)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, points_param,
|
||||
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, find_command,
|
||||
points_param,
|
||||
};
|
||||
use crate::cmd::draw2::SplineCvM;
|
||||
|
||||
pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("object").is_some() {
|
||||
@@ -26,11 +26,11 @@ pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::cmd) struct SplineM {
|
||||
pub(super) struct SplineM {
|
||||
pts: Vec<Vec2>,
|
||||
asking_method: bool,
|
||||
/// Both entry points share Method and Object; CV handles its own points and degree.
|
||||
cv: Option<SplineCvM>,
|
||||
/// `Method` > `CV` hands over to the control-vertex machine (`spline.cv`).
|
||||
delegate: Option<Box<dyn Interactive>>,
|
||||
/// Knots, end tangents and fit tolerance chosen so far.
|
||||
opts: cadcraft_geom::FitOptions,
|
||||
/// An option asking a further question (Knots, Tangency, toLerance, Object).
|
||||
@@ -38,10 +38,6 @@ pub(in crate::cmd) struct SplineM {
|
||||
}
|
||||
|
||||
impl SplineM {
|
||||
pub(in crate::cmd) fn cv() -> Self {
|
||||
Self { cv: Some(SplineCvM::default()), ..Self::default() }
|
||||
}
|
||||
|
||||
fn make(&self, closed: bool) -> Spline {
|
||||
Spline::fit_with(&self.pts, closed, self.opts)
|
||||
}
|
||||
@@ -53,25 +49,18 @@ impl Interactive for SplineM {
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.opts.knots = crate::cmd::spline_opts::current_knots(s);
|
||||
if let Some(cv) = &mut self.cv {
|
||||
return cv.begin(s);
|
||||
}
|
||||
s.echo(format!("Current settings: Method=Fit Knots={}", self.opts.knots.name()));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if let Some(d) = &self.delegate {
|
||||
return d.prompt(s);
|
||||
}
|
||||
if let Some(a) = &self.ask {
|
||||
return a.prompt(&self.opts, &self.pts);
|
||||
}
|
||||
if self.asking_method {
|
||||
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default(if self.cv.is_some() {
|
||||
"CV"
|
||||
} else {
|
||||
"Fit"
|
||||
});
|
||||
}
|
||||
if let Some(cv) = &self.cv {
|
||||
return cv.prompt(s);
|
||||
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default("Fit");
|
||||
}
|
||||
match self.pts.len() {
|
||||
0 => Prompt::new("Specify first point", Accept::POINT).kw(&["Method", "Knots", "Object"]),
|
||||
@@ -83,6 +72,9 @@ impl Interactive for SplineM {
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if let Some(d) = &mut self.delegate {
|
||||
return d.input(s, i);
|
||||
}
|
||||
if let Some(a) = &mut self.ask {
|
||||
use crate::cmd::spline_opts::Outcome;
|
||||
return match a.input(s, i, &mut self.opts, &self.pts)? {
|
||||
@@ -104,32 +96,24 @@ impl Interactive for SplineM {
|
||||
if self.asking_method {
|
||||
match i {
|
||||
Input::Keyword(k) if k == "CV" => {
|
||||
let Some(factory) = find_command("spline.cv").and_then(|c| c.interactive) else {
|
||||
return Err(crate::EngineError::Other("CV: not available yet".into()));
|
||||
};
|
||||
let mut m = factory(s)?;
|
||||
self.asking_method = false;
|
||||
return self.cv.get_or_insert_with(SplineCvM::default).begin(s);
|
||||
let step = m.begin(s)?;
|
||||
self.delegate = Some(m);
|
||||
return Ok(step);
|
||||
}
|
||||
Input::Keyword(k) if k == "Fit" => {
|
||||
self.asking_method = false;
|
||||
self.cv = None;
|
||||
return self.begin(s);
|
||||
}
|
||||
Input::Enter => self.asking_method = false,
|
||||
Input::Keyword(_) | Input::Enter => self.asking_method = false,
|
||||
Input::Text(_) => return Err(crate::EngineError::Other("Invalid option keyword.".into())),
|
||||
_ => {}
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if let Some(cv) = &mut self.cv
|
||||
&& !matches!(&i, Input::Keyword(k) if k == "Method" || k == "Object")
|
||||
{
|
||||
return cv.input(s, i);
|
||||
}
|
||||
match i {
|
||||
Input::Point(p) => {
|
||||
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
|
||||
// nor a kink.
|
||||
if self.pts.last() != Some(&p) {
|
||||
self.pts.push(p);
|
||||
}
|
||||
self.pts.push(p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
@@ -164,8 +148,8 @@ impl Interactive for SplineM {
|
||||
}
|
||||
}
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
if let Some(cv) = &self.cv {
|
||||
return cv.preview(s, c);
|
||||
if let Some(d) = &self.delegate {
|
||||
return d.preview(s, c);
|
||||
}
|
||||
if self.pts.is_empty() {
|
||||
return Vec::new();
|
||||
@@ -179,8 +163,6 @@ impl Interactive for SplineM {
|
||||
}
|
||||
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
|
||||
Some(_) => {}
|
||||
// The cursor on the last point adds nothing, as a click there doesn't.
|
||||
None if pts.last() == Some(&c) => {}
|
||||
None => pts.push(c),
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user