mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-28 01:10:19 +01:00
Merge #3375 again: the eight review fixes, and main
This commit is contained in:
commit
bd520db235
260 files changed
+23271
-881
No files matched your search
@@ -0,0 +1,16 @@
|
||||
-----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-----
|
||||
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/cadcraft",
|
||||
"repository_id": 1408289866,
|
||||
"producer_workflow_id": null,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"release_branch": "release",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
"echelon",
|
||||
"FredApps",
|
||||
"skylartaylor"
|
||||
],
|
||||
"max_age_seconds": 86400,
|
||||
"candidate_policy": {
|
||||
"schema": "craft-nightly-candidate-policy/v3",
|
||||
"epoch": "cadcraft-nightly-20261124-initial",
|
||||
"repository": "storytold/cadcraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 380135820,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_cadcraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_cadcraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": []
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
name: CADCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on release. Main/release contents must match.
|
||||
# A reusable callee does not change context; this must be a real top-level release dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
producer_run_id:
|
||||
description: Exact untrusted producer Actions run ID
|
||||
required: true
|
||||
type: string
|
||||
producer_run_attempt:
|
||||
description: Exact untrusted producer Actions run attempt
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: cadcraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real release branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/cadcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment and export keys in its signing step.
|
||||
@@ -0,0 +1,34 @@
|
||||
name: CADCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
unsigned:
|
||||
# Actual context guards only; no inherited/platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/cadcraft' &&
|
||||
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
|
||||
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
|
||||
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
|
||||
# no OIDC, attestation write, release environment or platform secrets in compilation.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
app-name: cadcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
|
||||
# Linux/macOS signer (#342).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -49,3 +49,31 @@ 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
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
nightly: ${{ github.event_name == 'schedule' }}
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: cadcraft
|
||||
app-title: CADCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -9,3 +9,11 @@
|
||||
*.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__/
|
||||
+10
-2
@@ -19,7 +19,9 @@ Generated-in-code assets are original and have no file to list:
|
||||
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
|
||||
names, our own dash/spacing values);
|
||||
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
|
||||
- the sample drawings (`crates/engine/src/sample.rs`).
|
||||
- the sample drawings (`crates/engine/src/sample.rs`);
|
||||
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
|
||||
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
@@ -43,6 +45,12 @@ 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 |
|
||||
@@ -70,7 +78,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star; terminology pass by @YannFR81 | Original French translations of CADCraft English strings; AI-assisted consistency pass (imperative prompts, cote/espace objet/réseau/présentation) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
|
||||
|
||||
Generated
+13
@@ -697,6 +697,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
"hidapi",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -712,6 +713,7 @@ dependencies = [
|
||||
"windows",
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -2095,6 +2097,17 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
|
||||
|
||||
[[package]]
|
||||
name = "fmv-macos-events"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
|
||||
@@ -59,6 +59,7 @@ fn install_io() {
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
@@ -96,7 +97,7 @@ where
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
return match write!(to, "{}", e.render()) {
|
||||
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
|
||||
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
|
||||
let _ = writeln!(err, "error: can't write the output: {w}");
|
||||
1
|
||||
@@ -166,6 +167,25 @@ mod tests {
|
||||
assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
|
||||
}
|
||||
|
||||
struct FailingFlush(std::io::ErrorKind);
|
||||
|
||||
impl Write for FailingFlush {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_flush_of_help_exits_1_unless_the_pipe_is_closed() {
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::StorageFull), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
|
||||
let dir = scratch_dir("replace");
|
||||
|
||||
@@ -171,6 +171,10 @@ 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);
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
|
||||
if a.keep_saved {
|
||||
opts.keep_saved = Some(out.join("saved"));
|
||||
}
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
|
||||
for f in &report.files {
|
||||
let routes: Vec<String> = f
|
||||
.routes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::args::{CmdStep, Drawing, RunArgs, Step};
|
||||
use super::error::Result;
|
||||
use super::open;
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views};
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use serde_json::Value;
|
||||
@@ -216,7 +216,15 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
|
||||
export(&s, p, io)?;
|
||||
}
|
||||
if let Some(p) = export_to {
|
||||
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
|
||||
let window = if cadcraft_io::is_image(p) {
|
||||
let window = export_window(&s, framing, Some(&before))?;
|
||||
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
|
||||
io.errln(format_args!("{message}"));
|
||||
}
|
||||
window
|
||||
} else {
|
||||
None
|
||||
};
|
||||
export_framed(&s, p, window, io)?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
|
||||
//! leaving them out silently (#1208). The exit code stays 0.
|
||||
//! Image exports report how many model-space entities they can't draw, by type. The exit code
|
||||
//! stays 0 (#1208).
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
@@ -70,6 +70,28 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_image_export_warns_about_undrawn_entities() {
|
||||
let scratch = Scratch::new("run-undrawn");
|
||||
let input = scratch.0.join("proxies.dxf");
|
||||
std::fs::write(&input, PROXIES).unwrap();
|
||||
let image = scratch.0.join("out.svg");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(image.is_file());
|
||||
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
|
||||
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
|
||||
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
|
||||
|
||||
let copy = scratch.0.join("copy.dxf");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(copy.is_file());
|
||||
assert!(!err.contains("not drawn"), "{err}");
|
||||
}
|
||||
|
||||
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
|
||||
/// says once that the OLE content inside the frame is not drawn (review on #2587).
|
||||
#[test]
|
||||
|
||||
@@ -818,7 +818,8 @@ fn non_unicode_arguments() {
|
||||
assert!(err.starts_with("error: invalid UTF-8 was detected"), "{err}");
|
||||
}
|
||||
|
||||
/// An output name that isn't valid Unicode is written as given: only its extension picks the format.
|
||||
/// 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.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn non_unicode_output_names() {
|
||||
@@ -836,6 +837,18 @@ 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")),
|
||||
@@ -844,6 +857,12 @@ 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:?}");
|
||||
@@ -949,3 +968,11 @@ fn json_output_is_pretty_unless_compact() {
|
||||
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
|
||||
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_progress_uses_the_requested_stderr() {
|
||||
run_cases(
|
||||
"roundtrip-progress",
|
||||
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
|
||||
);
|
||||
}
|
||||
@@ -133,6 +133,7 @@ mod web {
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// 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);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
|
||||
@@ -62,6 +62,11 @@ 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.
|
||||
# Pinned exactly: review the implementation before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
# Rust HID backends: no proprietary SDK or C HID library.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
@@ -72,6 +77,9 @@ 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"] }
|
||||
+46
-5
@@ -1,23 +1,64 @@
|
||||
//! 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();
|
||||
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")
|
||||
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" })
|
||||
.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}");
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! macOS open-documents and quit Apple events (#158).
|
||||
//!
|
||||
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
|
||||
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
|
||||
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
|
||||
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
|
||||
//! `NSAppleEventManager` handler registered before Finder's
|
||||
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
|
||||
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
enum Event {
|
||||
Open(Vec<PathBuf>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
|
||||
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
|
||||
/// the drawing twice.
|
||||
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
|
||||
&& !out.iter().any(|o| o == s)
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
|
||||
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
|
||||
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
|
||||
let mut quit = false;
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in openable(paths) {
|
||||
app.open_path(std::path::Path::new(&p));
|
||||
}
|
||||
}
|
||||
Event::Quit => quit = true,
|
||||
}
|
||||
}
|
||||
quit && !app.request_quit()
|
||||
}
|
||||
|
||||
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
|
||||
if dispatch(inbox.drain(), app) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Event, dispatch, openable};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::closing::Choice;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> CadApp {
|
||||
crate::install_io();
|
||||
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
|
||||
// worker in `main`, which a test does not run.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
fn settle(app: &mut CadApp) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while app.opening.busy() && Instant::now() < deadline {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
assert!(!app.opening.busy(), "background opening completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_order_and_drops_duplicates_and_empty_paths() {
|
||||
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
|
||||
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
|
||||
assert!(openable(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn skips_paths_that_are_not_utf8() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
|
||||
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
|
||||
// Writing and opening the DWG here needs the converter in this process: each test is its own.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dir = TestDir::new();
|
||||
let dxf = dir.0.join("planta com espaços.dxf");
|
||||
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
|
||||
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
|
||||
std::fs::write(&dxf, bytes).unwrap();
|
||||
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
|
||||
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
|
||||
settle(&mut app);
|
||||
|
||||
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
for path in [&dxf, &dwg] {
|
||||
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
|
||||
let dir = TestDir::new();
|
||||
let missing = dir.0.join("missing drawing.dwg");
|
||||
let mut app = app();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), 1);
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
|
||||
assert!(app.close_prompt().is_some());
|
||||
assert!(!app.quit_confirmed);
|
||||
assert!(!app.quit_requested);
|
||||
app.answer_close(Choice::Cancel);
|
||||
assert!(app.close_prompt().is_none());
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!app.quit_requested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_can_close_a_clean_session() {
|
||||
let mut app = app();
|
||||
assert!(dispatch([Event::Quit], &mut app));
|
||||
assert!(app.close_prompt().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,10 @@ 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
|
||||
@@ -87,6 +91,17 @@ 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());
|
||||
@@ -124,6 +139,20 @@ 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()));
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old portable/config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::portable::probe)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
+228
-18
@@ -14,16 +14,25 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod apple_events;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
mod desktop_theme;
|
||||
mod env;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod graphics;
|
||||
mod launch_args;
|
||||
mod launch_profile;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod portable;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod sheet;
|
||||
mod single_instance;
|
||||
@@ -32,6 +41,7 @@ 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};
|
||||
|
||||
@@ -54,6 +64,9 @@ struct App {
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -102,6 +115,9 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
|
||||
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
|
||||
self.cad.guarded_logic(ctx);
|
||||
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
|
||||
@@ -143,6 +159,11 @@ 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.
|
||||
@@ -177,6 +198,7 @@ pub fn install_io() {
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// 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);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -191,6 +213,8 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,7 +267,8 @@ 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(APP_ID).map(|dir| dir.join("app.ron"))) else {
|
||||
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 {
|
||||
return false;
|
||||
};
|
||||
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
|
||||
@@ -280,14 +305,14 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
|
||||
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
|
||||
eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("CADCraft")
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false)
|
||||
.with_app_id(APP_ID),
|
||||
.with_app_id(os_window::app_id()),
|
||||
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
|
||||
// restored window on the monitors that are connected now.
|
||||
persist_window: true,
|
||||
@@ -304,8 +329,6 @@ fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
|
||||
}
|
||||
}
|
||||
|
||||
const APP_ID: &str = "ai.storyteller.cadcraft";
|
||||
|
||||
/// The key eframe saves the main window state under in its storage.
|
||||
const WINDOW_KEY: &str = "window";
|
||||
|
||||
@@ -329,22 +352,118 @@ fn app_icon() -> Option<egui::IconData> {
|
||||
eframe::icon_data::from_png_bytes(APP_ICON_PNG).map_err(|e| log::warn!("app icon: {e}")).ok()
|
||||
}
|
||||
|
||||
/// The version this build reports: the prepared nightly identity, or the workspace version.
|
||||
fn built_version() -> &'static str {
|
||||
env!("CADCRAFT_BUILT_VERSION")
|
||||
}
|
||||
|
||||
/// The stable line, exactly what clap prints for `--version`: `cadcraft <workspace version>`.
|
||||
fn version_string() -> String {
|
||||
format!("cadcraft {}", cadcraft_engine::build_version())
|
||||
}
|
||||
|
||||
/// The Nightly identity line every nightly script checks: `<App> <version> (nightly-v1)`, with the
|
||||
/// prepared nightly version embedded at build time. The app name never gains a "Nightly".
|
||||
fn nightly_version_line() -> String {
|
||||
format!("CADCraft {}", build_flavor::version(build_flavor::BuildFlavor::NightlyV1, built_version()))
|
||||
}
|
||||
|
||||
/// The identity this build reports in its log: the Nightly line on that channel, stable's otherwise.
|
||||
fn reported_version() -> String {
|
||||
match build_flavor::COMPILED {
|
||||
build_flavor::BuildFlavor::Stable => version_string(),
|
||||
build_flavor::BuildFlavor::NightlyV1 => nightly_version_line(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reported line with the commit, for the log: a bug report's log names the build it came from.
|
||||
fn log_version() -> String {
|
||||
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
|
||||
}
|
||||
|
||||
/// Whether this start runs the isolated Nightly flavor.
|
||||
fn is_nightly() -> bool {
|
||||
launch_profile::current().is_nightly()
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
|
||||
}
|
||||
|
||||
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
|
||||
/// error everywhere else (a headless runner must never wait for a modal).
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("CADCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("CADCraft launch profile: {error}");
|
||||
return;
|
||||
}
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title(os_window::name_for(LaunchIdentity::NightlyV1))
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer
|
||||
/// the version query before any of that: `None` means the query has been answered and the process
|
||||
/// should return success without opening a window.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, logging, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
|
||||
fn main() -> eframe::Result {
|
||||
// A copy of this program started to read or write a DWG file does only that.
|
||||
// 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.
|
||||
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.
|
||||
// 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.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if !is_nightly()
|
||||
&& let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &arguments)
|
||||
{
|
||||
if let Err(e) = done {
|
||||
eprintln!("CADCraft update helper failed: {e}");
|
||||
std::process::exit(1);
|
||||
@@ -354,14 +473,25 @@ 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(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
|
||||
let launch = launch_args::parse(launch_args::command(), arguments).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 {}", version_string(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
|
||||
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", log_version(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
|
||||
Some(Err(e)) => log::warn!("no log file: {e}"),
|
||||
None => {
|
||||
logger.stderr_only();
|
||||
@@ -372,13 +502,32 @@ 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) {
|
||||
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off, launch_profile::current().root()) {
|
||||
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));
|
||||
}
|
||||
@@ -395,12 +544,16 @@ fn main() -> eframe::Result {
|
||||
if stencil == 0 {
|
||||
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
|
||||
}
|
||||
let persistence_path = vars
|
||||
.portable_storage_file
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os("CADCRAFT_CONFIG_DIR").and_then(|_| vars.config_dir.as_ref().map(|d| d.join("app.ron"))));
|
||||
let mut options = eframe::NativeOptions {
|
||||
// The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11
|
||||
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
|
||||
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
|
||||
persistence_path: vars.portable_storage_file.clone(),
|
||||
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
|
||||
persistence_path: persistence_path.clone(),
|
||||
..window_options(restores_window(persistence_path.as_deref()), stencil)
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
@@ -439,11 +592,25 @@ fn main() -> eframe::Result {
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
eframe::run_native(
|
||||
"CADCraft",
|
||||
// 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);
|
||||
let result = eframe::run_native(
|
||||
os_window::name_for(os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut app = CadApp::new(Session::empty(), services());
|
||||
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
|
||||
// it, so nothing after `run_native` can be relied on there.
|
||||
app.services.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, previous_unclean)));
|
||||
if previous_unclean {
|
||||
app.set_status("CADCraft Nightly ended unexpectedly last time; your drawings were recovered where autosave had them.");
|
||||
}
|
||||
// File dialogs are sheets on macOS: a modal loop inside the event handler crashes the
|
||||
// app when the dialog is resized (#1527).
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -455,6 +622,17 @@ fn main() -> eframe::Result {
|
||||
app.ui = ui;
|
||||
}
|
||||
app.set_system_cursor_default(vars.system_cursor == Switch::On);
|
||||
// Native Wayland answers a clipboard request asynchronously; every other backend in the
|
||||
// next frame (egui-winit).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
use eframe::egui_wgpu::wgpu::rwh::{HasDisplayHandle, RawDisplayHandle};
|
||||
if let Ok(display) = cc.display_handle() {
|
||||
app.set_clipboard_late_answers(matches!(display.as_raw(), RawDisplayHandle::Wayland(_)));
|
||||
}
|
||||
}
|
||||
#[cfg(any(not(unix), target_os = "macos"))]
|
||||
app.set_clipboard_late_answers(false);
|
||||
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_native_menus(vars.no_native_menu != Switch::On);
|
||||
@@ -476,7 +654,10 @@ 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"));
|
||||
app.enable_update_check();
|
||||
// A nightly build is updated by the Launcher, never by the app's own update check.
|
||||
if !is_nightly() {
|
||||
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");
|
||||
@@ -502,6 +683,14 @@ fn main() -> eframe::Result {
|
||||
for f in &files {
|
||||
app.open_path(f);
|
||||
}
|
||||
// Start reading any launch-time documents before the first frame. Later events use
|
||||
// this same inbox, including the normal unsaved-changes handling for quit requests.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = {
|
||||
let inbox = apple_events.connect(&cc.egui_ctx);
|
||||
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
|
||||
inbox
|
||||
};
|
||||
if app.session.docs.is_empty() {
|
||||
// In the units the profile asks for (MEASUREINIT, restored above).
|
||||
let metric = app.session.settings.measureinit;
|
||||
@@ -529,14 +718,24 @@ fn main() -> eframe::Result {
|
||||
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::{STENCIL_BITS, filters_for_save, follow_desktop, saved_window, stencil_bits, window_options, without_tiny_window};
|
||||
use super::{
|
||||
STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
|
||||
without_tiny_window,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
|
||||
@@ -619,6 +818,17 @@ 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]
|
||||
|
||||
@@ -144,7 +144,12 @@ impl NativeMenu {
|
||||
self.last_refresh = now;
|
||||
let typing = menus::text_field_window(ctx).is_some();
|
||||
for (cmd, _, item) in self.items.values() {
|
||||
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
|
||||
// Open Recent rebuilds this item with the correct enabled state.
|
||||
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));
|
||||
item.set_enabled(en);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! 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,21 +3,39 @@
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// 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.
|
||||
/// 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()));
|
||||
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?;
|
||||
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)?;
|
||||
Ok(Some(data))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
|
||||
// Linux only, as the shared nightlies publish.
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
|
||||
// different names into the same replacement character and call them one folder.
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str();
|
||||
match (platform.ignores_case(), value.to_str()) {
|
||||
(true, Some(text)) => OsString::from(text.to_lowercase()),
|
||||
_ => value.to_os_string(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
/// Every stable CADCraft data root of this platform, plus the install folders and the running
|
||||
/// install ([`installation_boundary`]).
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
|
||||
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
|
||||
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
|
||||
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
|
||||
// here; the executable's own folder is fenced below.
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
|
||||
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
|
||||
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
|
||||
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/CADCraft"),
|
||||
library.join("Caches/CADCraft"),
|
||||
library.join("Caches/ai.storyteller.cadcraft"),
|
||||
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
|
||||
// Support), beside the settings folder env.rs uses.
|
||||
library.join("Application Support").join(EFRAME_APP_ID),
|
||||
library.join("Preferences/CADCraft"),
|
||||
library.join("Preferences/ai.storyteller.cadcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
|
||||
home.join("Applications/CADCraft.app"),
|
||||
PathBuf::from("/Applications/CADCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
|
||||
// fail halfway, so refuse it while the profile is still being validated.
|
||||
match std::fs::symlink_metadata(&child) {
|
||||
Ok(metadata) if !metadata.file_type().is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
|
||||
/// so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
|
||||
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
|
||||
// (in a user folder or at a drive root) does not refuse the profile.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
|
||||
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
|
||||
/// global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
let chosen = canonical_future(root)?;
|
||||
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
|
||||
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
|
||||
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
|
||||
// other value would redirect Nightly's settings folder, so it is refused.
|
||||
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
|
||||
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
|
||||
if !configured.starts_with(&chosen) {
|
||||
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
|
||||
}
|
||||
}
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
{
|
||||
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
|
||||
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
|
||||
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
|
||||
// other instance is the stable app's (or another app's), whose socket this profile must
|
||||
// not inherit.
|
||||
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
|
||||
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
|
||||
}
|
||||
}
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
|
||||
}
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
|
||||
// private profile, including toward a stable portable directory not in our known roots.
|
||||
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
|
||||
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
|
||||
/// bundle id differ on purpose, as they do for stable.
|
||||
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
|
||||
|
||||
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
|
||||
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
|
||||
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
|
||||
|
||||
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
|
||||
pub const AUTOSAVE: &str = "autosave";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/cadcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
|
||||
assert!(!probed.get(), "reject portable data before a writable probe");
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
|
||||
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("CADCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/state/cadcraft/autosave");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-self");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let recovery = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/cadcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
|
||||
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
|
||||
let storage = data.join(EFRAME_APP_ID);
|
||||
std::fs::create_dir_all(&storage).unwrap();
|
||||
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
|
||||
for candidate in [storage.clone(), storage.join("nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
|
||||
}
|
||||
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/CADCraft",
|
||||
"Application Support/ai.storyteller.cadcraft",
|
||||
"Caches/CADCraft",
|
||||
"Caches/ai.storyteller.cadcraft",
|
||||
"Preferences/CADCraft",
|
||||
"Saved Application State/ai.storyteller.cadcraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
// The bundle path and the Library fences fold case on macOS.
|
||||
let cased = library.join("application support/cadcraft/nightly");
|
||||
assert!(fixture.check(Platform::Mac, &cased).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_fences_roaming_local_and_both_install_folders() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
|
||||
for stable in [
|
||||
fixture.root.join("roaming/CADCraft"),
|
||||
fixture.root.join("roaming/ai.storyteller.cadcraft"),
|
||||
fixture.root.join("local/CADCraft"),
|
||||
fixture.root.join("program files/ArtCraft/CADCraft"),
|
||||
] {
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly")] {
|
||||
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
|
||||
}
|
||||
// Windows folder names ignore case.
|
||||
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
|
||||
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_dir_and_flatpak_are_refused() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
|
||||
let private = fixture.root.join("nightly-config");
|
||||
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
|
||||
assert!(!private.exists());
|
||||
fixture.env.remove("CADCRAFT_CONFIG_DIR");
|
||||
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
|
||||
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
|
||||
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
|
||||
assert!(!private.exists());
|
||||
}
|
||||
}
|
||||
|
||||
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
|
||||
/// channel's data root; that one instance is accepted, and its profile stays inside it.
|
||||
#[test]
|
||||
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
|
||||
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
|
||||
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
|
||||
// Stable's Flatpak folder is still fenced even inside the nightly instance.
|
||||
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
|
||||
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
|
||||
}
|
||||
|
||||
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
|
||||
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
|
||||
/// still a redirect.
|
||||
#[test]
|
||||
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
|
||||
let mut fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-wrapper");
|
||||
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
|
||||
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
|
||||
let inside = private.join("nested");
|
||||
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
|
||||
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-unwritable");
|
||||
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
|
||||
assert!(!fixture.home().join(".config/cadcraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
|
||||
let fixture = Fixture::new();
|
||||
let outside = fixture.root.join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let private = fixture.root.join("nightly-dangling");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(!probed.get());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -100,25 +100,30 @@ 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.
|
||||
pub fn claim(files: &[String], may_hand_off: bool) -> Claim {
|
||||
/// `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 {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
match socket_path() {
|
||||
match socket_path(profile) {
|
||||
Some(path) => claim_at(&path, files, may_hand_off),
|
||||
None => Claim::Alone,
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (files, may_hand_off);
|
||||
let _ = (files, may_hand_off, profile);
|
||||
Claim::Alone
|
||||
}
|
||||
}
|
||||
|
||||
/// The socket in `%LOCALAPPDATA%\CADCraft`.
|
||||
/// The socket in `%LOCALAPPDATA%\CADCraft`, or `<profile>\single-instance` for a Nightly launch.
|
||||
#[cfg(windows)]
|
||||
fn socket_path() -> Option<std::path::PathBuf> {
|
||||
fn socket_path(profile: Option<&std::path::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))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# 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.
|
After Width: | Height: | Size: 50 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 7.2 KiB |
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"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."
|
||||
}
|
||||
@@ -123,6 +123,11 @@ sync_github_name = true
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.whaslbeck]
|
||||
real_name = "Walter Haslbeck"
|
||||
display_name = "Walter Haslbeck"
|
||||
sync_github_name = false
|
||||
|
||||
[people.V1dalTheAbidal]
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
+246
-47
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
|
||||
mod apply;
|
||||
mod grips;
|
||||
mod reference;
|
||||
pub use apply::{drag_grip, set_property};
|
||||
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
|
||||
pub use grips::{DynGrip, GripPart, GripShape, grips};
|
||||
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
|
||||
|
||||
@@ -52,6 +52,13 @@ 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.
|
||||
@@ -87,16 +94,41 @@ 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.
|
||||
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 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 position (Position1).
|
||||
Point { at: Vec3, label: String, description: String },
|
||||
/// Named sets of visible objects.
|
||||
@@ -110,7 +142,9 @@ pub enum ParameterKind {
|
||||
},
|
||||
/// A named value chosen from a lookup table.
|
||||
Lookup { at: Vec3, label: String, description: String },
|
||||
/// Moves the block's base point.
|
||||
/// 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).
|
||||
BasePoint { at: Vec3 },
|
||||
/// A parameter type not modelled yet.
|
||||
Other { dxf_type: String },
|
||||
@@ -122,11 +156,23 @@ 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
|
||||
@@ -205,24 +251,46 @@ 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 {
|
||||
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>,
|
||||
multiplier: f64,
|
||||
angle_offset: f64,
|
||||
},
|
||||
Scale,
|
||||
Rotate,
|
||||
Flip,
|
||||
Array,
|
||||
PolarStretch,
|
||||
/// An action type not modelled yet.
|
||||
Other {
|
||||
dxf_type: String,
|
||||
},
|
||||
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,
|
||||
}
|
||||
|
||||
/// A lookup table column: the parameter value it reads or sets.
|
||||
@@ -383,7 +451,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::default();
|
||||
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
|
||||
for o in graph_members(&objects.0, xdict)? {
|
||||
let secs = sections(&o.tags);
|
||||
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
|
||||
@@ -398,6 +466,7 @@ 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());
|
||||
}
|
||||
@@ -406,15 +475,21 @@ 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); after a one-point parameter's point, its grip (93).
|
||||
/// 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).
|
||||
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
|
||||
let two = section(secs, "AcDbBlock2PtParameter");
|
||||
if !two.is_empty() {
|
||||
let mut c = Cursor::new(two);
|
||||
c.point(1010);
|
||||
c.point(1011);
|
||||
let n = c.count(170).min(2);
|
||||
return (0..n).map(|_| c.int(91)).collect();
|
||||
let 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 mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
|
||||
c.point(1010);
|
||||
@@ -446,15 +521,49 @@ 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() },
|
||||
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
|
||||
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
|
||||
// the value set.
|
||||
"BLOCKROTATIONPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
match kind {
|
||||
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
|
||||
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
|
||||
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
|
||||
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
|
||||
_ => ParameterKind::Flip { base, end },
|
||||
}
|
||||
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 }
|
||||
}
|
||||
other => ParameterKind::Other { dxf_type: other.to_string() },
|
||||
}
|
||||
@@ -463,11 +572,17 @@ 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 {
|
||||
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();
|
||||
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();
|
||||
ValueSet { flags, minimum, maximum, increment, list }
|
||||
}
|
||||
|
||||
@@ -507,16 +622,56 @@ 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 })
|
||||
}
|
||||
"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),
|
||||
// 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")),
|
||||
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)> {
|
||||
@@ -551,6 +706,42 @@ 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).
|
||||
@@ -598,5 +789,13 @@ 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}");
|
||||
}
|
||||
}
|
||||
+1141
-161
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,11 @@
|
||||
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
|
||||
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
|
||||
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
|
||||
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
|
||||
//! 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.
|
||||
//!
|
||||
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
|
||||
|
||||
@@ -26,6 +30,13 @@ 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 {
|
||||
@@ -34,6 +45,8 @@ 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> {
|
||||
@@ -41,11 +54,28 @@ 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")]
|
||||
@@ -56,6 +86,13 @@ 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.
|
||||
@@ -102,6 +139,15 @@ 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)
|
||||
}
|
||||
@@ -120,6 +166,7 @@ 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 {
|
||||
@@ -171,6 +218,87 @@ 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,
|
||||
@@ -189,6 +317,26 @@ 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,6 +29,8 @@ 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.
|
||||
@@ -51,8 +53,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, a
|
||||
/// position, or a lookup whose tables set only those.
|
||||
/// 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.
|
||||
pub editable: bool,
|
||||
}
|
||||
|
||||
@@ -91,7 +93,9 @@ 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 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).
|
||||
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() });
|
||||
@@ -100,7 +104,10 @@ 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,
|
||||
@@ -122,17 +129,52 @@ 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();
|
||||
dynamic_block(d, &definition)?;
|
||||
let m = 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);
|
||||
@@ -156,26 +198,7 @@ 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> {
|
||||
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,
|
||||
}
|
||||
super::apply::property_text(self.m, self.values, node, property)
|
||||
}
|
||||
|
||||
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
|
||||
@@ -239,6 +262,27 @@ 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,
|
||||
@@ -247,6 +291,21 @@ 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 });
|
||||
@@ -263,7 +322,8 @@ 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 and distances.
|
||||
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
|
||||
/// flip states.
|
||||
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
let mut any = false;
|
||||
for a in &m.actions {
|
||||
@@ -272,12 +332,29 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if !columns
|
||||
.iter()
|
||||
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
|
||||
{
|
||||
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) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ mod curves;
|
||||
mod dim;
|
||||
mod fill;
|
||||
mod layout;
|
||||
mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
|
||||
@@ -52,12 +53,18 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface
|
||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||
pub use fill::{Gradient, Hatch, HatchLoop};
|
||||
pub use layout::{Image, Table, TableCell, Viewport};
|
||||
pub use proxy::{ProxyTables, proxy_entities};
|
||||
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
||||
pub use wipeout::Wipeout;
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Unknown {
|
||||
pub dxf_type: String,
|
||||
pub tags: Vec<RawTag>,
|
||||
/// What an ACAD_PROXY_ENTITY draws: its proxy graphics as read-only entities, made when the
|
||||
/// drawing is read (the graphics refer to table rows by their place in the file). Drawn and
|
||||
/// measured like block contents; saving writes `tags` unchanged.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub graphics: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl Unknown {
|
||||
@@ -264,7 +271,10 @@ 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())],
|
||||
EntityKind::Unknown(_) => Vec::new(),
|
||||
// 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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,7 +627,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.attribs.iter().map(|a| a.text.justify_point())).collect(),
|
||||
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().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(),
|
||||
|
||||
@@ -191,6 +191,12 @@ 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())
|
||||
|
||||
@@ -7,6 +7,11 @@ pub struct HatchLoop {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
#[serde(default)]
|
||||
pub outer: bool,
|
||||
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
|
||||
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
|
||||
/// None uses the flags of a locally created loop.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub boundary_flags: Option<i64>,
|
||||
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
|
||||
/// hatch re-fills the loop from them when they change.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -37,7 +37,7 @@ pub struct RegionProps {
|
||||
impl Region {
|
||||
/// A region bounded by one closed loop.
|
||||
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }] }
|
||||
}
|
||||
|
||||
pub fn polylines(&self) -> Vec<Polyline> {
|
||||
@@ -170,7 +170,7 @@ mod tests {
|
||||
let mut vertices: Vec<PolyVertex> =
|
||||
(0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect();
|
||||
vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new));
|
||||
HatchLoop { vertices, outer, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -371,6 +371,28 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo
|
||||
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.
|
||||
fn unknown_bounds<'a>(
|
||||
d: &'a Drawing,
|
||||
u: &crate::Unknown,
|
||||
depth: usize,
|
||||
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
|
||||
off_counts: bool,
|
||||
) -> Bounds2 {
|
||||
if u.graphics.is_empty() {
|
||||
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
|
||||
}
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Bounds2::EMPTY;
|
||||
}
|
||||
u.graphics
|
||||
.iter()
|
||||
.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,
|
||||
/// by block name and depth: every further reference to a block at that depth reuses them instead of
|
||||
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
|
||||
@@ -516,8 +538,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
|
||||
Bounds2::from_points([o, o + u, o + v, o + u + v])
|
||||
}
|
||||
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
|
||||
// An OLE object's content is not drawn, but its frame is, so the frame counts (#2422).
|
||||
EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points),
|
||||
// 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, off_counts),
|
||||
kind => {
|
||||
let mut b = Bounds2::EMPTY;
|
||||
for p in kind.prims() {
|
||||
@@ -718,12 +741,15 @@ mod tests {
|
||||
#[test]
|
||||
fn ole_frame_counts_in_extents() {
|
||||
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]));
|
||||
assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0)));
|
||||
assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame");
|
||||
assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty());
|
||||
assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty());
|
||||
assert!(
|
||||
bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")], graphics: Vec::new() }))
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
|
||||
|
||||
@@ -53,6 +53,10 @@ impl ForeignExtra {
|
||||
/// Everything of a file CADCraft keeps without modelling it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Foreign {
|
||||
/// Original two-point text and style, by entity handle and attribute position.
|
||||
/// Kept with imported metadata so new entities never inherit another entity's fitting.
|
||||
pub text_fits: BTreeMap<Handle, Vec<(crate::Text, crate::TextStyle)>>,
|
||||
|
||||
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
|
||||
pub classes: Vec<Vec<RawTag>>,
|
||||
/// Classes retain every source position, including duplicate names.
|
||||
|
||||
@@ -111,6 +111,8 @@ pub struct Drawing {
|
||||
pub mline_styles: Vec<MLineStyle>,
|
||||
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
|
||||
pub model: EntityStore,
|
||||
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
||||
pub model_page: Option<PageSetup>,
|
||||
pub layouts: Vec<Layout>,
|
||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
|
||||
@@ -158,6 +160,11 @@ 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 {
|
||||
@@ -201,6 +208,7 @@ impl Drawing {
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: BTreeMap::new(),
|
||||
model: EntityStore::new(),
|
||||
model_page: None,
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
|
||||
active_layout: None,
|
||||
views: Vec::new(),
|
||||
@@ -221,6 +229,7 @@ impl Drawing {
|
||||
skipped_records: BTreeMap::new(),
|
||||
portable_fonts: false,
|
||||
rasters: Rasters::default(),
|
||||
proxy_layers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,10 @@ impl EntityStore {
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
|
||||
self.chunks.iter().flat_map(|c| c.items.iter())
|
||||
}
|
||||
/// Iterate from the top of the draw order down.
|
||||
pub fn iter_rev(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
|
||||
self.chunks.iter().rev().flat_map(|c| c.items.iter().rev())
|
||||
}
|
||||
pub fn handles(&self) -> Vec<Handle> {
|
||||
self.iter().map(|e| e.handle).collect()
|
||||
}
|
||||
@@ -346,6 +350,7 @@ mod tests {
|
||||
}
|
||||
assert!(s.move_next_to(Handle(1), Handle(3), true));
|
||||
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
|
||||
assert_eq!(s.iter_rev().map(|e| e.handle.0).collect::<Vec<_>>(), [5, 4, 1, 3, 2], "top down");
|
||||
assert!(s.move_next_to(Handle(5), Handle(2), false));
|
||||
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
|
||||
assert!(!s.move_next_to(Handle(5), Handle(5), true));
|
||||
|
||||
@@ -782,6 +782,10 @@ 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).
|
||||
@@ -789,7 +793,7 @@ pub struct PageSetup {
|
||||
pub height_mm: f64,
|
||||
pub margins_mm: [f64; 4],
|
||||
pub landscape: bool,
|
||||
/// "layout" | "extents" | "display" | "window" | "limits".
|
||||
/// "layout" | "extents" | "display" | "window" | "limits" | "view".
|
||||
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],
|
||||
@@ -838,6 +842,7 @@ 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,
|
||||
@@ -862,6 +867,15 @@ 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 {
|
||||
|
||||
@@ -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 on, definition points that sit on object endpoints,
|
||||
/// Add a dimension. With DIMASSOC 2, 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,8 +74,10 @@ 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 {
|
||||
s.doc().map(|d| d.header.i64("DIMASSOC", 2) != 0).unwrap_or(false)
|
||||
// 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)
|
||||
}
|
||||
|
||||
pub(super) fn with_assoc(k: EntityKind, assoc: Vec<DimAssoc>) -> EntityKind {
|
||||
|
||||
@@ -161,17 +161,22 @@ 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 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 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 dir = match b.kind {
|
||||
DimKind::Linear { rotation } => Vec2::from_angle(rotation),
|
||||
DimKind::Aligned => (b.p14.xy() - b.p13.xy()).normalized(),
|
||||
@@ -209,7 +214,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 takes the DIMDLI-based default).
|
||||
/// the spacing (Enter or Auto uses the base dimension's text height).
|
||||
#[derive(Default)]
|
||||
pub(super) struct DimSpaceM {
|
||||
base: Option<Handle>,
|
||||
|
||||
@@ -318,6 +318,46 @@ 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();
|
||||
|
||||
+124
-10
@@ -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, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, 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(|_| Ok(Box::new(InsertM::default()))),
|
||||
.interactive(|s| Ok(Box::new(InsertM { person: s.command_origin() == Origin::Person, ..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(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))),
|
||||
.interactive(|s| Ok(Box::new(InsertM { minsert: true, person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
|
||||
CommandSpec::new("attdef", "Define Attributes...", run_attdef)
|
||||
.menu(&["Draw", "Block", "Define Attributes..."])
|
||||
.alias(&["att", "-attdef"])
|
||||
@@ -60,6 +60,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
attedit::dash_attedit_spec(),
|
||||
wblock::wblock_spec(),
|
||||
wblock::dash_wblock_spec(),
|
||||
CommandSpec::new("wblockpick", "Write Block Pick", run_wblockpick)
|
||||
.params("{mode: \"objects\"|\"base\"}")
|
||||
.interactive(|_| Ok(Box::new(WblockPickM::default()))),
|
||||
CommandSpec::new("base", "Base", run_base).menu(&["Draw", "Block", "Base"]).params("{at: [x,y]}"),
|
||||
CommandSpec::new("blocks.dynamic", "Dynamic Block Data", run_dynamic)
|
||||
.params("{name (a block, or \"*Model_Space\" for a drawing that is a dynamic block's own)} → {parameters, actions, other} | null (not a dynamic block)")
|
||||
@@ -70,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 or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
|
||||
.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}")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
|
||||
.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)")
|
||||
.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)")
|
||||
.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, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
|
||||
.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")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("purge", "Purge", purge::run)
|
||||
.alias(&["pu", "-purge"])
|
||||
@@ -713,6 +716,88 @@ impl BlockM {
|
||||
}
|
||||
}
|
||||
|
||||
// ── WBLOCKPICK ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// The result kept for the Write Block dialog after a WBLOCKPICK session ends.
|
||||
pub struct WblockPicks {
|
||||
/// Selected handles (mode "objects") — empty for a "base" pick.
|
||||
pub handles: Vec<Handle>,
|
||||
/// Base point picked (mode "base") — `None` for an "objects" pick.
|
||||
pub base: Option<Vec2>,
|
||||
}
|
||||
|
||||
fn run_wblockpick(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Which pick session WBLOCKPICK is running.
|
||||
#[derive(Default)]
|
||||
enum WblockPickMode {
|
||||
/// Waiting for the mode keyword ("objects" or "base").
|
||||
#[default]
|
||||
Waiting,
|
||||
Objects(SelectPhase),
|
||||
Base,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct WblockPickM {
|
||||
mode: WblockPickMode,
|
||||
}
|
||||
|
||||
impl Interactive for WblockPickM {
|
||||
fn name(&self) -> &'static str {
|
||||
"WBLOCKPICK"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match &self.mode {
|
||||
WblockPickMode::Waiting => Prompt::new("Enter pick mode", Accept::TEXT).kw(&["Objects", "Base"]),
|
||||
WblockPickMode::Objects(sel) => sel.prompt(),
|
||||
WblockPickMode::Base => Prompt::new("Specify insertion base point", Accept::POINT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match &mut self.mode {
|
||||
WblockPickMode::Waiting => {
|
||||
match &i {
|
||||
Input::Keyword(k) | Input::Text(k) => {
|
||||
let k = k.to_ascii_lowercase();
|
||||
if k.starts_with('o') {
|
||||
self.mode = WblockPickMode::Objects(SelectPhase::default());
|
||||
} else {
|
||||
self.mode = WblockPickMode::Base;
|
||||
}
|
||||
}
|
||||
Input::Cancel | Input::Enter => return Ok(Step::Cancel),
|
||||
_ => {}
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
WblockPickMode::Objects(sel) => {
|
||||
if matches!(i, Input::Cancel) {
|
||||
return Ok(Step::Cancel);
|
||||
}
|
||||
match sel.feed(s, &i)? {
|
||||
SelOutcome::More => Ok(Step::Continue),
|
||||
SelOutcome::Empty => Ok(Step::Cancel),
|
||||
SelOutcome::Done(hs) => {
|
||||
s.wblock_picks = Some(WblockPicks { handles: hs, base: None });
|
||||
Ok(Step::Done)
|
||||
}
|
||||
}
|
||||
}
|
||||
WblockPickMode::Base => match i {
|
||||
Input::Cancel => Ok(Step::Cancel),
|
||||
Input::Point(p) => {
|
||||
s.wblock_picks = Some(WblockPicks { handles: Vec::new(), base: Some(p) });
|
||||
Ok(Step::Done)
|
||||
}
|
||||
_ => Ok(Step::Continue),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod insert_file;
|
||||
pub(crate) mod library;
|
||||
pub(crate) mod xref;
|
||||
@@ -773,6 +858,16 @@ 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,
|
||||
@@ -804,7 +899,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.values.len() >= self.attdefs.len() && self.verified < self.verifying().len() {
|
||||
if self.stage == InsStage::Attribs && self.asked >= self.attdefs.len() && self.verified < self.verifying().len() {
|
||||
if self.verified == 0 {
|
||||
s.echo("Verify attribute values");
|
||||
}
|
||||
@@ -812,7 +907,7 @@ impl InsertM {
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.stage == InsStage::Attribs
|
||||
&& self.values.len() >= self.attdefs.len()
|
||||
&& self.asked >= 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())?;
|
||||
@@ -863,6 +958,8 @@ 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 {
|
||||
@@ -877,6 +974,7 @@ impl InsertM {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
self.asked = 0;
|
||||
self.name = Some(b.name.clone());
|
||||
self.stage = InsStage::Point;
|
||||
Ok(())
|
||||
@@ -966,7 +1064,7 @@ impl Interactive for InsertM {
|
||||
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
|
||||
InsStage::Attribs => {
|
||||
let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
|
||||
let (_, prompt, default, _) = self.attdefs.get(self.asked).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) }
|
||||
@@ -1173,12 +1271,16 @@ impl Interactive for InsertM {
|
||||
}
|
||||
}
|
||||
InsStage::Attribs => {
|
||||
let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
|
||||
let (tag, _, default, _) = self.attdefs.get(self.asked).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.
|
||||
@@ -1216,6 +1318,18 @@ 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;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
|
||||
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
|
||||
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
|
||||
//! at a distance's grip sets the distance.
|
||||
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
|
||||
@@ -30,7 +30,8 @@ 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 or at"))?;
|
||||
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 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();
|
||||
@@ -46,11 +47,25 @@ 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();
|
||||
dynblock::drag_grip(&mut d, h, node, part, to)?;
|
||||
drag_in(s, &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).
|
||||
@@ -102,7 +117,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
|
||||
_ => None,
|
||||
});
|
||||
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
|
||||
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
None => EntityKind::Text(a.text.clone()),
|
||||
};
|
||||
Entity { handle: Handle(0), common, kind }
|
||||
}));
|
||||
out
|
||||
}
|
||||
@@ -114,11 +133,16 @@ struct DynGripEdit {
|
||||
part: GripPart,
|
||||
/// Where the grip is (the rubber band's start).
|
||||
from: Vec2,
|
||||
/// The property it changes, and whether it is a distance (a typed number sets it).
|
||||
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
|
||||
property: String,
|
||||
distance: bool,
|
||||
shape: GripShape,
|
||||
/// Where the grip can stop (a value list or increments): tick marks across its travel.
|
||||
stops: Vec<(Vec2, Vec2)>,
|
||||
}
|
||||
|
||||
/// Half a tick mark's length, in pixels.
|
||||
const TICK_PX: f64 = 6.0;
|
||||
|
||||
impl Interactive for DynGripEdit {
|
||||
fn name(&self) -> &'static str {
|
||||
"GRIP"
|
||||
@@ -129,19 +153,22 @@ impl Interactive for DynGripEdit {
|
||||
}
|
||||
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let (msg, accept) = if self.distance {
|
||||
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
|
||||
} else {
|
||||
("** STRETCH ** Specify stretch point", Accept::POINT)
|
||||
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),
|
||||
};
|
||||
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
|
||||
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 }
|
||||
}
|
||||
|
||||
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 self.distance => {
|
||||
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
|
||||
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;
|
||||
@@ -155,9 +182,30 @@ impl Interactive for DynGripEdit {
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// The rubber band from the grip.
|
||||
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
vec![crate::cmd::helpers::line(self.from, c)]
|
||||
/// 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 reference re-evaluated at the cursor, drawn as it will look (its own colours, so
|
||||
@@ -165,7 +213,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 dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
|
||||
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
|
||||
Ok(()) => drawn(&d, self.handle),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
@@ -174,8 +222,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) has no drag: the UI offers
|
||||
/// its choices and sets them with `blocks.reference.set`.
|
||||
/// 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`.
|
||||
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
@@ -184,17 +232,19 @@ impl Session {
|
||||
.into_iter()
|
||||
.find(|g| g.node == node && g.part == part)
|
||||
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
|
||||
if g.shape == GripShape::List {
|
||||
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
|
||||
if matches!(g.shape, GripShape::List | GripShape::Flip) {
|
||||
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
|
||||
}
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
|
||||
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 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("** STRETCH **");
|
||||
self.echo(label);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,8 @@ 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)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -188,6 +190,7 @@ 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)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,9 @@ use super::insert_file::stem;
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
pub(super) fn wblock_spec() -> CommandSpec {
|
||||
CommandSpec::new("wblock", "Write Block", run_wblock).alias(&["w"]).params("{path, name? | handles?, base?}")
|
||||
CommandSpec::new("wblock", "Write Block", run_wblock)
|
||||
.alias(&["w"])
|
||||
.params("{path, name? (a block, or \"*\" for the whole drawing) | handles?, base?}")
|
||||
}
|
||||
|
||||
/// -WBLOCK erases the objects it writes, whatever its mOde option says: AutoCAD 2024 does, and
|
||||
@@ -45,6 +47,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
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)))?,
|
||||
};
|
||||
|
||||
@@ -9,10 +9,7 @@ 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, find_command, point_param, point_req, point_value, points_param, size_param,
|
||||
str_param,
|
||||
};
|
||||
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 crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, snap};
|
||||
|
||||
@@ -32,7 +29,8 @@ 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};
|
||||
use spline::{SplineM, run_spline};
|
||||
pub(super) use spline::SplineM;
|
||||
use spline::run_spline;
|
||||
|
||||
use text::{MTextM, TextM, run_mtext, run_text};
|
||||
pub(crate) use text::{justify, justify_prompt};
|
||||
|
||||
@@ -39,6 +39,10 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
|
||||
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
|
||||
}
|
||||
|
||||
fn current_elevation(s: &Session) -> Result<f64> {
|
||||
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
|
||||
}
|
||||
|
||||
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);
|
||||
for v in raw.into_iter().flatten() {
|
||||
@@ -53,6 +57,7 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
pl.elevation = current_elevation(s)?;
|
||||
}
|
||||
added(s.add_entity(k)?)
|
||||
}
|
||||
@@ -174,6 +179,7 @@ impl Interactive for LineM {
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlineM {
|
||||
verts: Vec<PolyVertex>,
|
||||
elevation: f64,
|
||||
arc_mode: bool,
|
||||
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
|
||||
start_w: f64,
|
||||
@@ -191,6 +197,7 @@ impl PlineM {
|
||||
fn entity(&self, closed: bool) -> EntityKind {
|
||||
let mut k = lwpoly(self.verts.clone(), closed);
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.elevation = self.elevation;
|
||||
// Every segment the same uniform width: store it as the constant width, as before.
|
||||
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
|
||||
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
|
||||
@@ -259,6 +266,10 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if self.asking_width > 0 {
|
||||
let unit = if self.half { "half-width" } else { "width" };
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, find_command,
|
||||
points_param,
|
||||
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, 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(super) struct SplineM {
|
||||
pub(in crate::cmd) struct SplineM {
|
||||
pts: Vec<Vec2>,
|
||||
asking_method: bool,
|
||||
/// `Method` > `CV` hands over to the control-vertex machine (`spline.cv`).
|
||||
delegate: Option<Box<dyn Interactive>>,
|
||||
/// Both entry points share Method and Object; CV handles its own points and degree.
|
||||
cv: Option<SplineCvM>,
|
||||
/// Knots, end tangents and fit tolerance chosen so far.
|
||||
opts: cadcraft_geom::FitOptions,
|
||||
/// An option asking a further question (Knots, Tangency, toLerance, Object).
|
||||
@@ -38,6 +38,10 @@ pub(super) 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)
|
||||
}
|
||||
@@ -49,18 +53,25 @@ 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("Fit");
|
||||
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);
|
||||
}
|
||||
match self.pts.len() {
|
||||
0 => Prompt::new("Specify first point", Accept::POINT).kw(&["Method", "Knots", "Object"]),
|
||||
@@ -72,9 +83,6 @@ 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)? {
|
||||
@@ -96,21 +104,25 @@ 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;
|
||||
let step = m.begin(s)?;
|
||||
self.delegate = Some(m);
|
||||
return Ok(step);
|
||||
return self.cv.get_or_insert_with(SplineCvM::default).begin(s);
|
||||
}
|
||||
Input::Keyword(_) | Input::Enter => self.asking_method = false,
|
||||
Input::Keyword(k) if k == "Fit" => {
|
||||
self.asking_method = false;
|
||||
self.cv = None;
|
||||
return self.begin(s);
|
||||
}
|
||||
Input::Enter => self.asking_method = false,
|
||||
Input::Text(_) => return Err(crate::EngineError::Other("Invalid option keyword.".into())),
|
||||
_ => {}
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if let Some(cv) = &mut self.cv
|
||||
&& !matches!(&i, Input::Keyword(k) if k == "Method" || k == "Object")
|
||||
{
|
||||
return cv.input(s, i);
|
||||
}
|
||||
match i {
|
||||
Input::Point(p) => {
|
||||
self.pts.push(p);
|
||||
@@ -148,8 +160,8 @@ impl Interactive for SplineM {
|
||||
}
|
||||
}
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
if let Some(d) = &self.delegate {
|
||||
return d.preview(s, c);
|
||||
if let Some(cv) = &self.cv {
|
||||
return cv.preview(s, c);
|
||||
}
|
||||
if self.pts.is_empty() {
|
||||
return Vec::new();
|
||||
|
||||
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
|
||||
None => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
|
||||
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
|
||||
.base(a),
|
||||
.corner(a),
|
||||
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
|
||||
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
|
||||
}
|
||||
|
||||
@@ -28,7 +28,8 @@ mod xline;
|
||||
pub(crate) use arc::arc_machine;
|
||||
use arc::{ArcContinueM, ArcV, run_arc_continue, run_arc_variant, seq};
|
||||
use centermark::{CenterM, run_centerline, run_centermark};
|
||||
use curves3d::{HelixM, Poly3dM, SplineCvM, run_3dpoly, run_helix, run_spline_cv};
|
||||
pub(super) use curves3d::SplineCvM;
|
||||
use curves3d::{HelixM, Poly3dM, run_3dpoly, run_helix, run_spline_cv};
|
||||
use divide::{DivideM, run_divide, run_measure};
|
||||
use ellipse::{run_ellipse_arc, run_ellipse_axis};
|
||||
pub(crate) use rect::{RectM2, run_rectang2};
|
||||
@@ -149,7 +150,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("spline.cv", "Control Vertices", run_spline_cv)
|
||||
.menu(&["Draw", "Spline", "Control Vertices"])
|
||||
.params("{control: [[x,y],...], degree?: 1..10 (default 3), closed?}")
|
||||
.interactive(|_| Ok(Box::new(SplineCvM::default()))),
|
||||
.interactive(|_| Ok(Box::new(super::draw::SplineM::cv()))),
|
||||
CommandSpec::new("centermark", "Center Mark", run_centermark)
|
||||
.menu(&["Draw", "Center Mark"])
|
||||
.params("{handle | handles} (circles/arcs; lines on the CENTER linetype)")
|
||||
|
||||
@@ -284,7 +284,7 @@ pub(super) fn run_spline_cv(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SplineCvM {
|
||||
pub(in crate::cmd) struct SplineCvM {
|
||||
pts: Vec<Vec2>,
|
||||
degree: Option<usize>,
|
||||
asking_degree: bool,
|
||||
@@ -312,7 +312,9 @@ impl Interactive for SplineCvM {
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if self.asking_degree {
|
||||
if let Input::Text(t) = &i {
|
||||
let d = number(t).filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| other("Degree must be 1..10."))?;
|
||||
let d = number(t)
|
||||
.filter(|d| d.fract() == 0.0 && (1.0..=10.0).contains(d))
|
||||
.ok_or_else(|| other("Degree must be a whole number from 1 to 10."))?;
|
||||
self.degree = Some(d as usize);
|
||||
}
|
||||
self.asking_degree = false;
|
||||
@@ -340,7 +342,7 @@ impl Interactive for SplineCvM {
|
||||
s.add_entity(EntityKind::Spline(sp))?;
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
_ => s.echo(format!("{k}: use SPLINE for fit points.")),
|
||||
_ => return Err(other("Invalid option keyword.")),
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
@@ -593,7 +593,9 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if let Some(f) = points_param(p, "fence") {
|
||||
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
|
||||
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
targets(s, p)?
|
||||
// Handles named outright, less the proxies: no selection takes one in.
|
||||
let d = s.doc()?;
|
||||
targets(s, p)?.into_iter().filter(|h| !d.entity(*h).is_some_and(|e| crate::select::kept_as_read(&e.kind))).collect()
|
||||
} else {
|
||||
// Nothing to select with: the selection stays, also what the active viewport does not draw.
|
||||
s.stored_selection()
|
||||
|
||||
@@ -235,6 +235,11 @@ fn units_per_mm(d: &Drawing) -> f64 {
|
||||
18 => 1.0 / 1.495_978_707e14,
|
||||
19 => 1.0 / 9.460_730_472_580_8e18,
|
||||
20 => std::f64::consts::PI / (648_000.0 * 1.495_978_707e14),
|
||||
// US survey units: a survey foot is 1200/3937 m.
|
||||
21 => 3937.0 / 1_200_000.0,
|
||||
22 => 3937.0 / 100_000.0,
|
||||
23 => 3937.0 / 3_600_000.0,
|
||||
24 => 3937.0 / 6_336_000_000.0,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
@@ -740,6 +745,21 @@ mod tests {
|
||||
assert_eq!(s.doc().unwrap().model.len(), before, "no empty drawing was opened or imported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn survey_units_convert_like_their_international_counterparts() {
|
||||
let per_mm = |insunits: i64| {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_i64("INSUNITS", insunits);
|
||||
units_per_mm(&d)
|
||||
};
|
||||
// Survey feet, inches, yards and miles beside feet, inches, yards and miles.
|
||||
for (survey, international) in [(21, 2), (22, 1), (23, 10), (24, 3)] {
|
||||
let ratio = per_mm(survey) / per_mm(international);
|
||||
// The survey unit is two parts per million longer.
|
||||
assert!(ratio < 1.0 && ratio > 1.0 - 1e-5, "INSUNITS {survey}: {ratio}");
|
||||
}
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("cadcraft-exchange-{}-{name}", std::process::id()))
|
||||
}
|
||||
|
||||
@@ -95,6 +95,15 @@ pub fn set_proxies_lost(f: ProxiesLost) {
|
||||
let _ = PROXIES_LOST.set(f);
|
||||
}
|
||||
|
||||
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
|
||||
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
|
||||
|
||||
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
|
||||
let _ = DWG_COMPAT_LOST.set(f);
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
@@ -928,6 +937,12 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
if let Some(compatibility) = DWG_COMPAT_LOST.get() {
|
||||
for (kind, count) in compatibility(d, version) {
|
||||
let total = out.entry(kind).or_default();
|
||||
*total = total.saturating_add(count);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -232,7 +232,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let outer = found.outer;
|
||||
let ob = Bounds2::from_points(outer.iter().copied());
|
||||
let sources = handles_of(&owners, &found.outer_sources);
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }];
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
|
||||
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
|
||||
if let Some(store) = d.space(&space) {
|
||||
for e in store.iter() {
|
||||
@@ -248,7 +248,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let inside = pts.iter().all(|q| point_in_polygon(&outer, *q) || outer.iter().any(|o| o.near(*q, tol * 10.0)));
|
||||
let same_as_outer = (cadcraft_geom::shoelace(&pts).abs() - cadcraft_geom::shoelace(&outer).abs()).abs() < tol.max(1e-6) * 1000.0;
|
||||
if inside && !same_as_outer && !point_in_polygon(&pts, p) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, sources: vec![e.handle] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,7 +260,12 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
&& island.sources.iter().all(|&i| owners.get(i).and_then(|h| d.entity(*h)).is_some_and(|e| island_curve(d, e)));
|
||||
if open_curves {
|
||||
let sources = handles_of(&owners, &island.sources);
|
||||
loops.push(HatchLoop { vertices: island.outline.into_iter().map(PolyVertex::new).collect(), outer: false, sources });
|
||||
loops.push(HatchLoop {
|
||||
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
|
||||
outer: false,
|
||||
boundary_flags: None,
|
||||
sources,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(loops)
|
||||
@@ -271,7 +276,7 @@ pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<Hatch
|
||||
let mut loops = Vec::new();
|
||||
for h in hs {
|
||||
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
|
||||
}
|
||||
}
|
||||
if loops.is_empty() {
|
||||
|
||||
@@ -197,7 +197,7 @@ fn follow(before: &Drawing, after: &Drawing, handle: Handle, h: &Hatch, checked:
|
||||
match refill(from, after, l) {
|
||||
Refill::Loop(vertices) => {
|
||||
let sources = l.sources.iter().copied().filter(|s| exists(after, *s)).take(MAX_SOURCES).collect();
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, sources });
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
|
||||
}
|
||||
// An erased island: the hatch fills its area.
|
||||
Refill::Erased if !l.outer => {}
|
||||
|
||||
+143
-11
@@ -4,15 +4,15 @@
|
||||
//! the drawing as a crossed-out frame.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, Image, Raster};
|
||||
use cadcraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::file::base64_decode;
|
||||
use super::{CommandSpec, bad, f64_or, point_param, str_param};
|
||||
use super::{CommandSpec, bad, point_value, str_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Most image files loaded per drawing.
|
||||
@@ -27,6 +27,9 @@ const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
|
||||
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
|
||||
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
|
||||
const MAX_LOADED_BYTES: u64 = 2 << 30;
|
||||
/// Most bytes one decoded image takes: the image reader decodes at most 128 million pixels, four
|
||||
/// bytes each (`cadcraft_io::raster::MAX_IMAGE_PIXELS`).
|
||||
const MAX_DECODED_BYTES: u64 = 512_000_000;
|
||||
/// Most image files decoded at the same time when a drawing opens.
|
||||
const MAX_LOADERS: usize = 4;
|
||||
/// Longest image path taken from a caller.
|
||||
@@ -183,13 +186,11 @@ fn over_limit(path: &str) -> String {
|
||||
/// what opening a drawing with large images waits for). The results are in the order of `paths`.
|
||||
fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<Raster, String>> {
|
||||
// Decoded bytes so far, shared by the loaders: past the limit no further file is started.
|
||||
let decoded_bytes = AtomicU64::new(0);
|
||||
let budget = Budget::default();
|
||||
let load = |path: &str| -> std::result::Result<Raster, String> {
|
||||
if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES {
|
||||
return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20));
|
||||
}
|
||||
let mut decoding = budget.start().ok_or_else(|| format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20))?;
|
||||
let r = read_file(path, host).and_then(|bytes| decode(&bytes))?;
|
||||
decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed);
|
||||
decoding.bytes = bytes_of(&r);
|
||||
Ok(r)
|
||||
};
|
||||
let mut results: Vec<Option<std::result::Result<Raster, String>>> = paths.iter().map(|_| None).collect();
|
||||
@@ -224,6 +225,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<R
|
||||
results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect()
|
||||
}
|
||||
|
||||
/// The decoded bytes the loaders of one drawing share.
|
||||
#[derive(Default)]
|
||||
struct Budget {
|
||||
spent: Mutex<Spent>,
|
||||
/// Signaled when a file finishes decoding.
|
||||
finished: Condvar,
|
||||
}
|
||||
|
||||
/// Decoded bytes so far, and how many files are being decoded.
|
||||
#[derive(Default)]
|
||||
struct Spent {
|
||||
decoded: u64,
|
||||
decoding: u64,
|
||||
}
|
||||
|
||||
/// Whether a loader may start decoding a file.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Admit {
|
||||
Start,
|
||||
/// Not until another file finishes.
|
||||
Wait,
|
||||
/// The images decoded so far are past the limit.
|
||||
Full,
|
||||
}
|
||||
|
||||
impl Spent {
|
||||
/// A file starts while the images decoded so far, and the largest image each file being
|
||||
/// decoded can become, fit under `limit`. A file always starts when no other one is being
|
||||
/// decoded, so that the images run past `limit` by one image at most.
|
||||
fn admit(&mut self, limit: u64, largest: u64) -> Admit {
|
||||
if self.decoded > limit {
|
||||
return Admit::Full;
|
||||
}
|
||||
let reserved = self.decoding.saturating_add(1).saturating_mul(largest);
|
||||
if self.decoding > 0 && self.decoded.saturating_add(reserved) > limit {
|
||||
return Admit::Wait;
|
||||
}
|
||||
self.decoding = self.decoding.saturating_add(1);
|
||||
Admit::Start
|
||||
}
|
||||
|
||||
/// A file finished decoding into `bytes` (0 when it failed).
|
||||
fn finish(&mut self, bytes: u64) {
|
||||
self.decoding = self.decoding.saturating_sub(1);
|
||||
self.decoded = self.decoded.saturating_add(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
/// Wait until a file may start decoding; `None` once the images decoded so far are past the
|
||||
/// limit.
|
||||
fn start(&self) -> Option<Decoding<'_>> {
|
||||
let mut spent = self.spent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
loop {
|
||||
match spent.admit(MAX_LOADED_BYTES, MAX_DECODED_BYTES) {
|
||||
Admit::Start => return Some(Decoding { budget: self, bytes: 0 }),
|
||||
Admit::Full => return None,
|
||||
Admit::Wait => spent = self.finished.wait(spent).unwrap_or_else(PoisonError::into_inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A file being decoded. Dropping it counts `bytes` as decoded and lets a waiting loader check
|
||||
/// again, also when the decoding failed.
|
||||
struct Decoding<'a> {
|
||||
budget: &'a Budget,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
impl Drop for Decoding<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.budget.spent.lock().unwrap_or_else(PoisonError::into_inner).finish(self.bytes);
|
||||
self.budget.finished.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large
|
||||
/// image needs several hundred megabytes while it is decoded) and no more than there are files.
|
||||
fn loader_count(files: usize) -> usize {
|
||||
@@ -268,6 +346,9 @@ pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(ID, "`path` is too long"));
|
||||
}
|
||||
let place = placement(p)?;
|
||||
if p.get("name").is_some_and(|n| !(n.is_null() || n.is_string())) {
|
||||
return Err(bad(ID, "`name` must be text"));
|
||||
}
|
||||
let raster = pixels(s, p, &path)?;
|
||||
let (w, h) = (f64::from(raster.width()), f64::from(raster.height()));
|
||||
// One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`).
|
||||
@@ -305,18 +386,32 @@ struct Placement {
|
||||
|
||||
/// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1).
|
||||
fn placement(p: &Value) -> Result<Placement> {
|
||||
let at = point_param(p, "at").unwrap_or(Vec2::ZERO);
|
||||
let at = match p.get("at") {
|
||||
None | Some(Value::Null) => Vec2::ZERO,
|
||||
Some(v) => point_value(v).ok_or_else(|| bad(ID, "`at` must be a point"))?,
|
||||
};
|
||||
if !(at.x.is_finite() && at.y.is_finite()) {
|
||||
return Err(bad(ID, "`at` must be a point"));
|
||||
}
|
||||
// `scale` is checked even when `width` takes precedence over it.
|
||||
let scale = number(p, "scale")?;
|
||||
let width = match p.get("width") {
|
||||
Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?,
|
||||
None => f64_or(p, "scale", 1.0),
|
||||
None => scale.unwrap_or(1.0),
|
||||
};
|
||||
if !(width.is_finite() && width > 0.0) {
|
||||
return Err(bad(ID, "`scale` and `width` must be greater than zero"));
|
||||
}
|
||||
Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width })
|
||||
let rotation = number(p, "rotation")?.unwrap_or(0.0);
|
||||
Ok(Placement { at, rotation: rotation.to_radians(), width })
|
||||
}
|
||||
|
||||
/// The number `key` of `p`: `None` when it is omitted or null, an error when it is not a number.
|
||||
fn number(p: &Value, key: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| bad(ID, format!("`{key}` must be a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels of the image at `path`: decoded from `data` when the caller hands the file over,
|
||||
@@ -384,3 +479,40 @@ fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value {
|
||||
};
|
||||
json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A file starts only while the largest image each file being decoded can become still fits,
|
||||
/// one file always starts when none is being decoded, and none starts past the limit.
|
||||
#[test]
|
||||
fn loaders_start_files_within_the_limit() {
|
||||
let mut s = Spent::default();
|
||||
// Room for two of the largest images.
|
||||
assert_eq!(s.admit(10, 4), Admit::Start);
|
||||
assert_eq!(s.admit(10, 4), Admit::Start);
|
||||
assert_eq!(s.admit(10, 4), Admit::Wait);
|
||||
s.finish(3);
|
||||
assert_eq!(s.admit(10, 4), Admit::Wait, "3 decoded and two files that can become 4 each are past 10");
|
||||
s.finish(5);
|
||||
// Over the limit only by the one file being decoded.
|
||||
assert_eq!(s.admit(10, 4), Admit::Start);
|
||||
s.finish(4);
|
||||
assert_eq!(s.admit(10, 4), Admit::Full);
|
||||
// A failed file counts nothing.
|
||||
let mut s = Spent::default();
|
||||
assert_eq!(s.admit(10, 4), Admit::Start);
|
||||
s.finish(0);
|
||||
assert_eq!((s.decoded, s.decoding), (0, 0));
|
||||
}
|
||||
|
||||
/// Files that fail still let the other loaders go on: every file gets a result.
|
||||
#[test]
|
||||
fn decode_files_finishes_when_every_file_fails() {
|
||||
let paths = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"];
|
||||
let results = decode_files(&paths, None);
|
||||
assert_eq!(results.len(), paths.len());
|
||||
assert!(results.iter().all(std::result::Result::is_err), "none of these files exists");
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ mod prompts;
|
||||
mod state_prompts;
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Layer, Lineweight};
|
||||
use cadcraft_doc::{EntityKind, Layer, Lineweight};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::machines::SelectRun;
|
||||
@@ -101,7 +101,8 @@ fn run_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "layers": layers, "states": d.layer_states.iter().map(|st| st.name.clone()).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Lower-case names of layers that have objects on them (model, layouts and block definitions).
|
||||
/// Lower-case names of layers that have objects on them (model, layouts and block definitions),
|
||||
/// or that proxy graphics draw on: AutoCAD keeps those too.
|
||||
pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<String> {
|
||||
let mut set = std::collections::HashSet::new();
|
||||
let ents = d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter()));
|
||||
@@ -113,6 +114,9 @@ pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<Strin
|
||||
for layer in super::blocks::object_attribs(e).iter().filter_map(|a| a.props.layer.as_ref()) {
|
||||
set.insert(layer.to_ascii_lowercase());
|
||||
}
|
||||
if let EntityKind::Unknown(u) = &e.kind {
|
||||
set.extend(u.graphics.iter().map(|g| g.common.layer.to_ascii_lowercase()));
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
@@ -258,6 +262,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
merge::rename_in_viewports(d, &old, &nn);
|
||||
d.rename_proxy_layer(&old, &nn);
|
||||
if cur.eq_ignore_ascii_case(&old) {
|
||||
d.header.set_str("CLAYER", &nn);
|
||||
}
|
||||
@@ -302,10 +307,7 @@ fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if name == "0" || name.eq_ignore_ascii_case("Defpoints") || d.header.str("CLAYER", "0").eq_ignore_ascii_case(&name) {
|
||||
return Err(bad("layer.delete", "cannot delete layer 0, Defpoints or the current layer"));
|
||||
}
|
||||
let used = d.model.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name))
|
||||
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)))
|
||||
|| d.blocks.values().any(|b| b.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)));
|
||||
if used {
|
||||
if used_layers(d).contains(&name.to_ascii_lowercase()) {
|
||||
return Err(bad("layer.delete", "layer has objects on it"));
|
||||
}
|
||||
d.layers.retain(|l| !l.name.eq_ignore_ascii_case(&name));
|
||||
@@ -778,6 +780,61 @@ mod tests {
|
||||
assert!(s.doc().unwrap().layer("A").is_some());
|
||||
}
|
||||
|
||||
/// A session with layers A, B and C and a proxy on layer 0 whose graphics draw a line on B
|
||||
/// (#3094).
|
||||
fn proxy_on_b() -> Session {
|
||||
use cadcraft_doc::{Common, Entity, EntityKind, Handle, Line, Space, Unknown};
|
||||
let mut s = Session::new();
|
||||
for name in ["A", "B", "C"] {
|
||||
s.execute("layer.new", &json!({ "name": name })).unwrap();
|
||||
}
|
||||
let line = Entity {
|
||||
handle: Handle(0),
|
||||
common: Common { layer: "B".into(), ..Common::default() },
|
||||
kind: EntityKind::Line(Line { a: cadcraft_doc::geom::Vec3::ZERO, b: cadcraft_doc::geom::Vec3::new(1.0, 0.0, 0.0) }),
|
||||
};
|
||||
let proxy = EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![line] });
|
||||
s.doc_mut().unwrap().add(&Space::Model, Common::default(), proxy).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn graphics_layer(s: &Session) -> String {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Unknown(u) => u.graphics.first().map(|g| g.common.layer.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// As in AutoCAD, PURGE and layer.delete keep a layer only proxy graphics draw on.
|
||||
#[test]
|
||||
fn layers_proxy_graphics_draw_on_are_in_use() {
|
||||
let mut s = proxy_on_b();
|
||||
assert!(s.execute("layer.delete", &json!({ "name": "B" })).is_err());
|
||||
s.execute("purge", &json!({})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.layer("B").is_some() && d.layer("A").is_none() && d.layer("C").is_none());
|
||||
}
|
||||
|
||||
/// RENAME and LAYMRG take the graphics with the layer, LAYDEL drops them to layer 0.
|
||||
#[test]
|
||||
fn rename_merge_and_laydel_move_proxy_graphics() {
|
||||
let mut s = proxy_on_b();
|
||||
s.doc_mut().unwrap().proxy_layers = vec!["0".into(), "A".into(), "B".into(), "C".into()];
|
||||
s.execute("layer.set", &json!({ "name": "B", "newName": "B2" })).unwrap();
|
||||
assert_eq!(graphics_layer(&s), "B2");
|
||||
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "B2", "C"]);
|
||||
s.execute("laymrg", &json!({ "from": "B2", "to": "C" })).unwrap();
|
||||
assert_eq!(graphics_layer(&s), "C");
|
||||
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "C", "C"]);
|
||||
s.execute("laydel", &json!({ "name": "C" })).unwrap();
|
||||
assert_eq!(graphics_layer(&s), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_repoints_paper_space_and_block_entities() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -175,6 +175,10 @@ pub(super) fn run_laymrg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
hs.len()
|
||||
});
|
||||
forget_in_viewports(d, &set);
|
||||
// Proxy graphics drawn on a merged layer move to the target, as its objects do.
|
||||
for source in &sources {
|
||||
d.rename_proxy_layer(source, &target);
|
||||
}
|
||||
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
|
||||
let mut msg = format!("Merged {} into \"{target}\": {} moved.", quoted(&sources), plural(moved, "object"));
|
||||
if set.contains(&d.header.str("CLAYER", "0").to_ascii_lowercase()) {
|
||||
@@ -202,6 +206,11 @@ pub(super) fn run_laydel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
hs.len()
|
||||
});
|
||||
forget_in_viewports(d, &set);
|
||||
// A proxy isn't deleted for drawing on a deleted layer (its parts can't be); they fall back
|
||||
// to layer 0, the proxy's own layer.
|
||||
for source in &sources {
|
||||
d.rename_proxy_layer(source, "0");
|
||||
}
|
||||
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
|
||||
s.set_selection(Vec::new());
|
||||
let msg = format!("Deleted {} and {}.", quoted(&sources), plural(erased, "object"));
|
||||
|
||||
@@ -36,7 +36,7 @@ pub(crate) use oops::{Erased, erase_kept};
|
||||
use select_then::{DisplaceM, Op, SelectThen};
|
||||
use stretch::{StretchM, run_stretch};
|
||||
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
|
||||
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
|
||||
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
|
||||
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
@@ -2,7 +2,8 @@ use super::break_join::join;
|
||||
use super::explode::explode;
|
||||
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
|
||||
use super::{
|
||||
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, number,
|
||||
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line,
|
||||
mirror_entities, mirror_kind, number,
|
||||
};
|
||||
|
||||
// ---------------- interactive ----------------
|
||||
@@ -248,10 +249,11 @@ impl SelectThen {
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects whose text MIRROR keeps readable instead of mirroring it with the geometry.
|
||||
fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
|
||||
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
|
||||
fn needs_mirror_preview(k: &EntityKind) -> bool {
|
||||
match k {
|
||||
EntityKind::Insert(i) => !i.attribs.is_empty(),
|
||||
EntityKind::Hatch(h) => !h.solid || h.gradient.is_some(),
|
||||
k => matches!(
|
||||
k,
|
||||
EntityKind::Text(_)
|
||||
@@ -265,8 +267,8 @@ fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
|
||||
const MAX_MIRROR_TEXT_PREVIEW: usize = 1000;
|
||||
/// Objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
|
||||
const MAX_MIRROR_OBJECT_PREVIEW: usize = 1000;
|
||||
|
||||
/// A finite length greater than zero (rejects 0, negatives, NaN and infinity).
|
||||
fn positive_length(v: Option<f64>) -> Option<f64> {
|
||||
@@ -347,6 +349,7 @@ impl Interactive for SelectThen {
|
||||
_ => Prompt::new("", Accept::POINT),
|
||||
}
|
||||
}
|
||||
/// Advance the selected transform command, applying MIRROR fill policy at commit.
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if !self.sel.done {
|
||||
match self.sel.feed(s, &i)? {
|
||||
@@ -364,7 +367,7 @@ impl Interactive for SelectThen {
|
||||
if self.ask_erase {
|
||||
let yes = matches!(&i, Input::Keyword(k) if k == "Yes") || matches!(&i, Input::Text(t) if t.trim().to_ascii_lowercase().starts_with('y'));
|
||||
let (a, b) = (self.pts[0], self.pts[1]);
|
||||
transform_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
|
||||
mirror_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
@@ -456,6 +459,7 @@ impl Interactive for SelectThen {
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
/// Build bounded transform previews, retaining readable text and hatch fill directions.
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
if self.op == Op::Rotate && self.reference {
|
||||
return self.rotate_reference_preview(s, c);
|
||||
@@ -484,13 +488,18 @@ impl Interactive for SelectThen {
|
||||
.filter_map(|h| d.entity(*h))
|
||||
.map(|e| {
|
||||
let mut k = e.kind.clone();
|
||||
k.transform(&m);
|
||||
if self.op == Op::Mirror {
|
||||
mirror_kind(&mut k, &m);
|
||||
} else {
|
||||
k.transform(&m);
|
||||
}
|
||||
k
|
||||
})
|
||||
.collect();
|
||||
out.push(line(base, c));
|
||||
out
|
||||
}
|
||||
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
|
||||
fn drag(&self, s: &Session, c: Vec2) -> Option<crate::prompt::Drag> {
|
||||
if (self.op == Op::Rotate && self.reference) || !self.sel.done {
|
||||
return None;
|
||||
@@ -508,19 +517,19 @@ impl Interactive for SelectThen {
|
||||
if self.op != Op::Mirror {
|
||||
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
|
||||
}
|
||||
// Mirrored text keeps reading left to right (MIRRTEXT 0), which the matrix alone can't
|
||||
// draw: those objects are transformed one by one, the rest is mirrored on the GPU.
|
||||
// Readable text and unchanged hatch directions cannot be drawn by reflecting their
|
||||
// already-rendered primitives: preview those objects individually, the rest on the GPU.
|
||||
let d = s.doc().ok()?;
|
||||
let mut handles = Vec::with_capacity(self.objs.len());
|
||||
let mut texts = 0;
|
||||
let mut individual = 0;
|
||||
for h in &self.objs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
if !keeps_reading_when_mirrored(&e.kind) {
|
||||
if !needs_mirror_preview(&e.kind) {
|
||||
handles.push(*h);
|
||||
} else if texts < MAX_MIRROR_TEXT_PREVIEW {
|
||||
texts += 1;
|
||||
} else if individual < MAX_MIRROR_OBJECT_PREVIEW {
|
||||
individual += 1;
|
||||
let mut k = e.kind.clone();
|
||||
k.transform(&matrix);
|
||||
mirror_kind(&mut k, &matrix);
|
||||
extra.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use cadcraft_doc::EntityKind;
|
||||
use cadcraft_geom::Vec3;
|
||||
|
||||
use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets};
|
||||
@@ -9,6 +10,29 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy:
|
||||
edit_entities(s, hs, copy, |e| e.kind.transform(m))
|
||||
}
|
||||
|
||||
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
|
||||
/// Keep this in the command layer: a reflection of an entire inserted block still transforms
|
||||
/// all of its contents, rather than applying the policy for individually selected hatches.
|
||||
pub(super) fn mirror_kind(k: &mut EntityKind, m: &Mat3) {
|
||||
let angles = match k {
|
||||
EntityKind::Hatch(h) => Some((h.angle, h.gradient.as_ref().map(|g| g.angle))),
|
||||
_ => None,
|
||||
};
|
||||
k.transform(m);
|
||||
if let (EntityKind::Hatch(h), Some((angle, gradient_angle))) = (k, angles) {
|
||||
h.angle = angle;
|
||||
if let (Some(g), Some(angle)) = (&mut h.gradient, gradient_angle) {
|
||||
g.angle = angle;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reflect selected entities with the command policy that retains individual hatch fill directions.
|
||||
pub(super) fn mirror_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
|
||||
refuse_ole_frames(s, hs, m, copy)?;
|
||||
edit_entities(s, hs, copy, |e| mirror_kind(&mut e.kind, m))
|
||||
}
|
||||
|
||||
/// Scale `hs` by `f` about `base` in 3D, as AutoCAD 2024's SCALE does: about the base point's XY,
|
||||
/// and every height of the objects about its Z, their thickness too.
|
||||
pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result<Vec<Handle>> {
|
||||
@@ -151,6 +175,7 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Validate MIRROR parameters and apply the reflection, optionally replacing the source entities.
|
||||
pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
let a = point_req("mirror", p, "p1")?;
|
||||
@@ -159,6 +184,6 @@ pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("mirror", "mirror line points coincide"));
|
||||
}
|
||||
let erase_src = bool_or(p, "erase", false);
|
||||
let r = transform_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
|
||||
let r = mirror_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
|
||||
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -219,14 +219,18 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidate objects: the whole edit space, or the current selection.
|
||||
/// The candidate objects: the whole edit space (without proxies, which no selection takes in), or
|
||||
/// the current selection.
|
||||
fn candidates(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
let apply = str_param(p, "applyTo").unwrap_or("drawing").to_ascii_lowercase();
|
||||
if apply.starts_with("sel") || apply == "current" {
|
||||
return Ok(s.selection());
|
||||
}
|
||||
let space = s.space();
|
||||
Ok(s.doc()?.space(&space).map(|st| st.iter().take(MAX_SCAN).map(|e| e.handle).collect()).unwrap_or_default())
|
||||
Ok(s.doc()?
|
||||
.space(&space)
|
||||
.map(|st| st.iter().take(MAX_SCAN).filter(|e| !crate::select::kept_as_read(&e.kind)).map(|e| e.handle).collect())
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -238,6 +238,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"wblockpick",
|
||||
"overkill",
|
||||
"block",
|
||||
"-block",
|
||||
|
||||
@@ -170,13 +170,16 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
|
||||
if index == 0 {
|
||||
return Some(translated(kind, delta));
|
||||
}
|
||||
let a = i.attribs.get_mut(index - 1)?;
|
||||
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
|
||||
let a = i.attribs.get_mut(k)?;
|
||||
let ip = a.text.insert.xy() + delta;
|
||||
set_xy(&mut a.text.insert, ip);
|
||||
if let Some(al) = &mut a.text.align_pt {
|
||||
let q = al.xy() + delta;
|
||||
set_xy(al, q);
|
||||
}
|
||||
// A multiline attribute is drawn from its multiline text: it moves too.
|
||||
a.transform_multiline(&Mat3::translate(delta));
|
||||
}
|
||||
EntityKind::Dimension(d) => {
|
||||
match index {
|
||||
|
||||
@@ -92,6 +92,15 @@ impl Interactive for Guarded {
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in preview"));
|
||||
None
|
||||
})
|
||||
}
|
||||
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
@@ -128,6 +137,15 @@ impl Interactive for Guarded {
|
||||
None
|
||||
})
|
||||
}
|
||||
fn attribute_entry(&self) -> Option<crate::prompt::AttribEntry> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.attribute_entry())).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in prompt"));
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -52,9 +52,10 @@ pub use cadcraft_doc as doc;
|
||||
pub use cadcraft_fonts as fonts;
|
||||
pub use cadcraft_geom as geom;
|
||||
pub use cadcraft_render as render;
|
||||
pub use cmd::blocks::WblockPicks;
|
||||
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
|
||||
mod doc_state;
|
||||
mod error;
|
||||
@@ -79,6 +80,18 @@ pub fn build_version() -> &'static str {
|
||||
&VERSION
|
||||
}
|
||||
|
||||
/// Who started the command running now ([`Session::start`]): a person at the command line or
|
||||
/// from a menu, toolbar or palette, or a program (a script, an AutoLISP `(command …)`, a JSON
|
||||
/// call). The origin is fixed when the command starts and kept for its whole life: only a
|
||||
/// person's INSERT opens the Edit Attributes dialog, since nobody is there to answer one that a
|
||||
/// program opened, and nobody has seen it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Origin {
|
||||
#[default]
|
||||
Person,
|
||||
Program,
|
||||
}
|
||||
|
||||
/// The editor session: open drawings, settings, the running command and the command log.
|
||||
pub struct Session {
|
||||
pub docs: Vec<DocState>,
|
||||
@@ -90,11 +103,20 @@ pub struct Session {
|
||||
pub running: Option<Running>,
|
||||
/// How many commands were started, nested transparent ones left out.
|
||||
pub commands_started: u64,
|
||||
/// Who started the command running now ([`Origin`]): a command keeps the origin it started
|
||||
/// with, so a scripted or LISP-started INSERT never opens a dialog, even when the user then
|
||||
/// answers its prompts by hand.
|
||||
command_origin: Origin,
|
||||
/// The last command that ended by itself, not cancelled: its number in `commands_started`, and
|
||||
/// whether it took new handles (it added to the drawing, and nothing took that back).
|
||||
pub last_finished: Option<(u64, bool)>,
|
||||
/// A script is running ([`Session::script`]); a SCRIPT command inside it is refused.
|
||||
in_script: bool,
|
||||
/// The LISP evaluator is running ([`Session::lisp_drive`]): what a routine feeds the command
|
||||
/// line — the command it starts, or a `'command` token it types into a running one — is the
|
||||
/// program's input, so [`Session::start`] records [`Origin::Program`] for it. Saved and
|
||||
/// restored around each slice of a routine, so nesting keeps the outer answer.
|
||||
program_input: bool,
|
||||
/// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it;
|
||||
/// it resumes when that command ends. One level, as in AutoCAD.
|
||||
pub suspended: Option<Running>,
|
||||
@@ -158,6 +180,8 @@ pub struct Session {
|
||||
lisp_last: Option<std::result::Result<lisp::value::Value, String>>,
|
||||
/// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks).
|
||||
pub hatch_picks: Option<cmd::hatch::HatchPicks>,
|
||||
/// What the last WBLOCKPICK kept (the Write Block dialog's picks).
|
||||
pub wblock_picks: Option<cmd::blocks::WblockPicks>,
|
||||
/// The window's menu bar and tool bar as the UI shows them (it reports them every frame).
|
||||
pub bars_shown: cmd::interface::InterfaceBars,
|
||||
/// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply.
|
||||
@@ -189,8 +213,10 @@ impl Session {
|
||||
settings: Settings::default(),
|
||||
running: None,
|
||||
commands_started: 0,
|
||||
command_origin: Origin::Person,
|
||||
last_finished: None,
|
||||
in_script: false,
|
||||
program_input: false,
|
||||
suspended: None,
|
||||
log: Vec::new(),
|
||||
last_command: None,
|
||||
@@ -221,6 +247,7 @@ impl Session {
|
||||
lisp: lisp::LispState::default(),
|
||||
lisp_last: None,
|
||||
hatch_picks: None,
|
||||
wblock_picks: None,
|
||||
bars_shown: Default::default(),
|
||||
bars_request: Default::default(),
|
||||
pick_hint: None,
|
||||
|
||||
@@ -363,11 +363,17 @@ impl Session {
|
||||
let mut env = self.lisp_env_take();
|
||||
value::set_string_budget(run.string_bytes, self.lisp.limits.string_bytes);
|
||||
value::set_cell_limit(self.lisp.limits.cells.max(run.cells_at_start));
|
||||
// What the routine feeds the command line is the program's input: the command it
|
||||
// starts, even when another one is running and the token reaches
|
||||
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
|
||||
// in it included, so a person's later command keeps its own origin.
|
||||
let program_input = std::mem::replace(&mut self.program_input, true);
|
||||
let outcome = {
|
||||
let machine = &mut run.machine;
|
||||
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| machine.run(&mut ctx, SLICE)))
|
||||
};
|
||||
self.program_input = program_input;
|
||||
run.string_bytes = value::string_bytes_used();
|
||||
let outcome = match outcome {
|
||||
Ok(o) => o,
|
||||
|
||||
@@ -70,7 +70,9 @@ fn items(p: &PickSet) -> Vec<Handle> {
|
||||
/// selection set picks objects (a name, alone or with a point as `entsel` gives it, also answers
|
||||
/// a prompt picking one object: [`Session::input_object`]), and `pause` waits for the user. A
|
||||
/// command not finished by the arguments stays active for the next `command` call. No
|
||||
/// arguments: cancel the active command.
|
||||
/// arguments: cancel the active command. Whatever it feeds is the program's input
|
||||
/// ([`crate::Origin::Program`]): the command it starts here, and the one a `'command` token
|
||||
/// starts while another command runs, never open a dialog.
|
||||
pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
if a.is_empty() {
|
||||
if ctx.s.running.is_some() {
|
||||
@@ -91,7 +93,7 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
Value::Str(s) => {
|
||||
let r = if ctx.s.running.is_none() {
|
||||
if s.trim().is_empty() { Ok(()) } else { ctx.s.start(s) }
|
||||
if s.trim().is_empty() { Ok(()) } else { ctx.s.start_programmatic(s) }
|
||||
} else if s.is_empty() {
|
||||
ctx.s.input(Input::Enter)
|
||||
} else {
|
||||
@@ -813,7 +815,7 @@ fn interactive_ssget(ctx: &mut Ctx<'_>, filter: Option<Value>) -> Result<Flow, L
|
||||
if ctx.s.running.is_some() {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
if let Err(e) = ctx.s.start("select") {
|
||||
if let Err(e) = ctx.s.start_programmatic("select") {
|
||||
return Err(LispError::new(e.to_string()));
|
||||
}
|
||||
let f = super::eval::lookup(ctx.env, &super::value::Sym::new("SSGET"));
|
||||
|
||||
@@ -454,6 +454,19 @@ fn printing_many_lines_is_linear() {
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lisp_pline_keeps_current_elevation() {
|
||||
let mut s = session();
|
||||
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
|
||||
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
|
||||
|
||||
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
|
||||
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_draws_and_one_routine_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -79,7 +79,7 @@ pub struct Prompt {
|
||||
/// pick arrives as the plain point it was picked at.
|
||||
pub deferred: bool,
|
||||
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
||||
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub corner: bool,
|
||||
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
|
||||
@@ -103,6 +103,10 @@ pub struct Prompt {
|
||||
/// the routine writes, so it cannot be read for the word "Select" (#1598).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub picks_one: bool,
|
||||
/// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
|
||||
/// angle box, with the command's live value ([`Interactive::live_value`]).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub angle: bool,
|
||||
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
|
||||
/// block's name is that block, not a keyword read from its Latin keys.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -154,6 +158,11 @@ impl Prompt {
|
||||
self.grip = Some(g);
|
||||
self
|
||||
}
|
||||
/// An angle about the base is asked for (the `angle` field).
|
||||
pub fn angle(mut self) -> Self {
|
||||
self.angle = true;
|
||||
self
|
||||
}
|
||||
/// The visual chooser the UI can show (the `picker` field).
|
||||
pub fn picker(mut self, p: Picker) -> Self {
|
||||
self.picker = Some(p);
|
||||
@@ -326,6 +335,11 @@ pub trait Interactive: Send {
|
||||
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
|
||||
Vec::new()
|
||||
}
|
||||
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
|
||||
/// shows angles): what Dynamic Input shows in its box before anything is typed.
|
||||
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
|
||||
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
|
||||
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
|
||||
@@ -348,6 +362,11 @@ pub trait Interactive: Send {
|
||||
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
|
||||
None
|
||||
}
|
||||
/// The attribute values the command waits for, all at once, when the UI should ask for them
|
||||
/// in the Edit Attributes dialog (INSERT with ATTDIA 1). Typed answers still work.
|
||||
fn attribute_entry(&self) -> Option<AttribEntry> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Interactive::display_only`]: the only things drawn in the current view while a command
|
||||
@@ -389,6 +408,48 @@ pub enum EditorKind {
|
||||
Dimension { measured: String },
|
||||
}
|
||||
|
||||
/// See [`Interactive::attribute_entry`]: the block being inserted and the attributes asked for,
|
||||
/// in order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AttribEntry {
|
||||
pub block: String,
|
||||
pub rows: Vec<AttribAsk>,
|
||||
/// The drawing the command runs in ([`crate::DocState::uid`]) and its number in
|
||||
/// [`Session::commands_started`], stamped by [`Session::attribute_entry`]: a dialog draft
|
||||
/// belongs to one command, so a command started afterwards never takes it.
|
||||
pub drawing: u64,
|
||||
pub command: u64,
|
||||
}
|
||||
|
||||
/// One attribute an INSERT asks for: its tag, prompt and default value; the value of a Verify
|
||||
/// one is asked again once every value is in.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AttribAsk {
|
||||
pub tag: String,
|
||||
pub prompt: String,
|
||||
pub default: String,
|
||||
pub verify: bool,
|
||||
}
|
||||
|
||||
impl AttribEntry {
|
||||
/// An entry as the command builds it, before [`Session::attribute_entry`] stamps the drawing
|
||||
/// and command number it belongs to.
|
||||
pub(crate) fn idle(block: String, rows: Vec<AttribAsk>) -> Self {
|
||||
AttribEntry { block, rows, drawing: 0, command: 0 }
|
||||
}
|
||||
|
||||
/// The answers that give the attributes `values` (one per row, in order; a missing one is
|
||||
/// the default) when typed in turn: every value, then each Verify attribute's again, as
|
||||
/// INSERT asks them once the dialog has shown the values.
|
||||
pub fn answers(&self, values: &[String]) -> Vec<String> {
|
||||
let value = |i: usize| values.get(i).cloned().unwrap_or_else(|| self.rows.get(i).map(|r| r.default.clone()).unwrap_or_default());
|
||||
let mut out: Vec<String> = (0..self.rows.len()).map(value).collect();
|
||||
let verify: Vec<String> = self.rows.iter().enumerate().filter(|(_, r)| r.verify).map(|(i, _)| value(i)).collect();
|
||||
out.extend(verify);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Interactive::drag`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
|
||||
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
|
||||
EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
+648
-22
@@ -6,26 +6,64 @@ use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
|
||||
use crate::spatial::{self, SpatialIndex};
|
||||
use crate::{Accept, Prompt};
|
||||
|
||||
/// A dimension kept as read whose graphics are a reference to its `*D` block (#3438).
|
||||
fn draws_a_block(e: &Entity) -> bool {
|
||||
matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))))
|
||||
}
|
||||
|
||||
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
|
||||
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
|
||||
if matches!(e.kind, EntityKind::Insert(_)) {
|
||||
let list = insert_geometry(d, e, tol);
|
||||
return list
|
||||
.prims
|
||||
.iter()
|
||||
.flat_map(|p| match p.kind {
|
||||
cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask => {
|
||||
list.points(p).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect()
|
||||
}
|
||||
cadcraft_render::Kind::Infinite { ray } => match list.points(p) {
|
||||
[base, dir] => {
|
||||
let far = 1e9;
|
||||
vec![vec![if ray { *base } else { *base - *dir * far }, *base + *dir * far]]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
},
|
||||
// An image's points are its unclipped corners: it is hit on the outline of what
|
||||
// it shows, so a clipped-away part doesn't pick the reference.
|
||||
cadcraft_render::Kind::Image { index } => match list.images.get(index as usize) {
|
||||
Some(img) if img.clips.is_empty() => {
|
||||
let [a, b, c, d] = img.corners();
|
||||
vec![vec![a, b, c, d, a]]
|
||||
}
|
||||
Some(img) => shown_image_tris(img).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect(),
|
||||
None => Vec::new(),
|
||||
},
|
||||
_ => vec![list.points(p).to_vec()],
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
match &e.kind {
|
||||
EntityKind::Text(_)
|
||||
| EntityKind::MText(_)
|
||||
| EntityKind::Insert(_)
|
||||
| EntityKind::Dimension(_)
|
||||
| EntityKind::AttDef(_)
|
||||
| EntityKind::Table(_)
|
||||
| EntityKind::Tolerance(_)
|
||||
| EntityKind::MLeader(_)
|
||||
| EntityKind::Image(_) => {
|
||||
// Text-like objects are hit inside their box.
|
||||
| EntityKind::Image(_)
|
||||
| EntityKind::Unknown(_)
|
||||
if !matches!(e.kind, EntityKind::Unknown(_)) || draws_a_block(e) =>
|
||||
{
|
||||
// Text-like objects are hit inside their box; a dimension kept as read that draws its
|
||||
// block, like a dimension.
|
||||
let b = entity_bounds(d, e, 0);
|
||||
if b.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let c = b.corners();
|
||||
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
|
||||
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) {
|
||||
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) {
|
||||
let list = cadcraft_render::build_entities(
|
||||
d,
|
||||
std::iter::once(e),
|
||||
@@ -84,6 +122,44 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_geometry(d: &Drawing, e: &Entity, tol: f64) -> cadcraft_render::DisplayList {
|
||||
cadcraft_render::build_entities(d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() })
|
||||
}
|
||||
|
||||
/// The part of an image its clips leave showing, as triangles (three points each); empty when a
|
||||
/// clip has no outline to cut with.
|
||||
fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec<Vec2> {
|
||||
let [a, b, c, d] = img.corners();
|
||||
let mut tris = vec![a, b, c, a, c, d];
|
||||
for outline in &img.clips {
|
||||
let Some(clip) = cadcraft_render::clip::PolyClip::new(outline) else { return Vec::new() };
|
||||
tris = clip.clip_triangles(&tris);
|
||||
if tris.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tris
|
||||
}
|
||||
|
||||
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool {
|
||||
let list = insert_geometry(d, e, tol);
|
||||
list.prims.iter().any(|p| {
|
||||
if let cadcraft_render::Kind::Image { index } = p.kind {
|
||||
let Some(img) = list.images.get(index as usize) else { return false };
|
||||
return !cadcraft_render::clip::clip_triangles(&shown_image_tris(img), bx).is_empty();
|
||||
}
|
||||
if !matches!(p.kind, cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask) {
|
||||
return false;
|
||||
}
|
||||
list.points(p).as_chunks::<3>().0.iter().any(|t| {
|
||||
let triangle = [t[0], t[1], t[2]];
|
||||
bx.corners().iter().any(|q| point_in_polygon(&triangle, *q))
|
||||
|| triangle.iter().any(|q| bx.contains(*q))
|
||||
|| (0..3).any(|i| seg_hits_box(triangle[i], triangle[(i + 1) % 3], bx))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
|
||||
if pts.len() == 1 {
|
||||
return pts.first().map(|q| q.dist(p)).unwrap_or(f64::INFINITY);
|
||||
@@ -97,7 +173,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
|
||||
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
|
||||
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_))
|
||||
|| matches!(e.kind, EntityKind::Tolerance(_));
|
||||
if (filled && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, p) {
|
||||
if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) {
|
||||
best = 0.0;
|
||||
}
|
||||
// A solid hatch fills its loops with odd parity under its island style, as it is drawn, not
|
||||
@@ -161,28 +237,149 @@ pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
|
||||
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
|
||||
/// layers frozen in the layout viewport the selection is made through: what the Last option
|
||||
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
|
||||
/// A proxy is passed over: no selection takes one in ([`kept_as_read`]).
|
||||
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
|
||||
if frozen.is_empty() {
|
||||
return store.last().map(|e| e.handle);
|
||||
}
|
||||
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
|
||||
store.iter_rev().find(|e| !kept_as_read(&e.kind) && !on_frozen_layer(frozen, e)).map(|e| e.handle)
|
||||
}
|
||||
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]), it is not
|
||||
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
|
||||
/// model space, so `frozen` goes with a selection in model space only.
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else), and commands can
|
||||
/// edit it. A viewport shows model space, so `frozen` goes with a selection in model space only.
|
||||
/// A proxy (or another record CADCraft keeps as it was read) is drawn and snapped to, but never
|
||||
/// selected: commands can't edit it, and saving writes its record as it was read.
|
||||
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e)
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e) && !kept_as_read(&e.kind)
|
||||
}
|
||||
|
||||
/// Whether `k` is a record CADCraft keeps as it was read and commands can't edit: every
|
||||
/// [`EntityKind::Unknown`] but an OLE2FRAME, which moves and scales with its frame.
|
||||
pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
|
||||
matches!(k, EntityKind::Unknown(u) if !u.is_ole_frame())
|
||||
}
|
||||
|
||||
/// Entities to test, in the order to test them, each with its bounds when already known.
|
||||
pub(crate) type Cands<'a> = Box<dyn Iterator<Item = (&'a Entity, Option<Bounds2>)> + 'a>;
|
||||
|
||||
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
|
||||
known.unwrap_or_else(|| entity_bounds(d, e, 0))
|
||||
/// Whether an MTEXT's contents draw nothing (empty, or only spaces and `\~`): it has no glyph
|
||||
/// strokes, and the document's bounds for it are empty so it stays out of the drawing extents.
|
||||
/// Called for every MTEXT when the spatial index is built, so it does not allocate.
|
||||
fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool {
|
||||
t.contents.split(r"\~").all(|s| s.chars().all(char::is_whitespace))
|
||||
}
|
||||
|
||||
/// The frame a blank MTEXT is picked in (#2810), for a top-level MTEXT and for a multileader's
|
||||
/// MTEXT content: its insertion point, rotation and the box before turning (`x0, x1, y0, y1`
|
||||
/// about the insertion point): its width (the text height when it has none) by its text height,
|
||||
/// placed by its attachment point, at the size it draws at the current annotation scale (the
|
||||
/// shared `anno_scaled`, which also moves a multileader's text about its landing). `None` for any
|
||||
/// other entity, a multileader without text content, a blank MTEXT without a usable size or
|
||||
/// position, or an annotative one the current annotation scale hides.
|
||||
fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
|
||||
// Kind and blankness first: scaling clones the entity, so only blank text pays for it.
|
||||
let text = match &e.kind {
|
||||
EntityKind::MText(t) => t,
|
||||
EntityKind::MLeader(m) => m.text.as_ref()?,
|
||||
_ => return None,
|
||||
};
|
||||
if !is_blank_mtext(text) {
|
||||
return None;
|
||||
}
|
||||
let f = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => 1.0,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
|
||||
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
|
||||
cadcraft_doc::AnnoDraw::Hidden => return None,
|
||||
};
|
||||
let scaled;
|
||||
let e = if f != 1.0 {
|
||||
scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
&scaled
|
||||
} else {
|
||||
e
|
||||
};
|
||||
let t = match &e.kind {
|
||||
EntityKind::MText(t) => t,
|
||||
EntityKind::MLeader(m) => m.text.as_ref()?,
|
||||
_ => return None,
|
||||
};
|
||||
if !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height };
|
||||
let h = t.height;
|
||||
let insert = t.insert.xy();
|
||||
if !w.is_finite() || !h.is_finite() || !insert.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let dx = match t.attach {
|
||||
2 | 5 | 8 => -w / 2.0,
|
||||
3 | 6 | 9 => -w,
|
||||
_ => 0.0,
|
||||
};
|
||||
let top = match t.attach {
|
||||
4..=6 => h / 2.0,
|
||||
7..=9 => h,
|
||||
_ => 0.0,
|
||||
};
|
||||
// A top-level MTEXT that matches the layout orientation is drawn upright (the renderer draws
|
||||
// non-blank text that way), so its blank frame is too; a multileader keeps its text's stored rotation.
|
||||
let rotation = if matches!(e.kind, EntityKind::MText(_)) && e.common.matches_layout_orientation() { 0.0 } else { t.rotation };
|
||||
Some((insert, rotation, [dx, dx + w, top - h, top]))
|
||||
}
|
||||
|
||||
/// The box around a blank MTEXT's turned frame (a top-level MTEXT or a multileader's MTEXT
|
||||
/// content), for the spatial index and windows (a crossing window may catch a little extra near a
|
||||
/// corner, as it does for other text).
|
||||
fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option<Bounds2> {
|
||||
let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?;
|
||||
let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)];
|
||||
Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot))))
|
||||
}
|
||||
|
||||
/// Whether `p` is on a blank MTEXT or a multileader's blank MTEXT content: inside its box turned
|
||||
/// with the text, not the larger box around it.
|
||||
fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool {
|
||||
let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(d, e) else { return false };
|
||||
let q = (p - o).rotate(-rot);
|
||||
q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1
|
||||
}
|
||||
|
||||
/// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content.
|
||||
/// Use the same bounds for a scan and for the spatial index.
|
||||
pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 {
|
||||
match blank_mtext_box(d, e) {
|
||||
Some(frame) => drawn.union(&frame),
|
||||
None => drawn,
|
||||
}
|
||||
}
|
||||
|
||||
/// The insertion points snap's INS mode offers for a blank MTEXT or multileader (the stored
|
||||
/// points); empty for any other entity.
|
||||
fn blank_snap_points(e: &Entity) -> Vec<Vec2> {
|
||||
// select.rs blank_snap_points must offer the same points as snap.rs's INS arms.
|
||||
match &e.kind {
|
||||
EntityKind::MText(t) if is_blank_mtext(t) => vec![t.insert.xy()],
|
||||
EntityKind::MLeader(m) if m.text.as_ref().is_some_and(is_blank_mtext) => {
|
||||
m.text.iter().map(|t| t.insert.xy()).chain(m.block.iter().map(|b| b.insert.xy())).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn
|
||||
/// geometry (expanded by `aperture`) misses `probe`, and no insertion point INS would offer (text
|
||||
/// or block content) is a candidate: one counts only when `ins` is on and it is within `aperture`
|
||||
/// of `cursor`, the distance snap accepts a candidate by (a corner of the square probe is not).
|
||||
/// Such an entity is for picking and selection, not a snap candidate.
|
||||
pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor: Vec2, aperture: f64, ins: bool) -> bool {
|
||||
let points = blank_snap_points(e);
|
||||
!points.is_empty() && !(ins && points.iter().any(|p| p.dist(cursor) <= aperture)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe)
|
||||
}
|
||||
|
||||
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
|
||||
known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0)))
|
||||
}
|
||||
pub(crate) fn is_infinite(e: &Entity) -> bool {
|
||||
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
|
||||
}
|
||||
@@ -338,8 +535,15 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
|
||||
pl.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| seg_hits_box(*a, *b, bx)))
|
||||
}
|
||||
});
|
||||
// A crossing box entirely inside a text/block bounding rectangle also selects it.
|
||||
if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) {
|
||||
// A crossing box inside a text bounding rectangle selects the text.
|
||||
if hit
|
||||
|| (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_)))
|
||||
|| (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// Likewise inside a blank MTEXT's frame (a multileader's too), where picking also selects it.
|
||||
if blank_mtext_box(d, e).is_some_and(|frame| frame.contains_box(bx)) {
|
||||
return true;
|
||||
}
|
||||
// SOLID/TRACE are filled polygons. A crossing window wholly within the
|
||||
@@ -551,7 +755,7 @@ impl SelectMode {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use cadcraft_doc::{Common, RayLine};
|
||||
use cadcraft_doc::{Common, Image, Raster, RayLine};
|
||||
use cadcraft_geom::Vec3;
|
||||
|
||||
fn fence_hits(kind: EntityKind, fence: [(f64, f64); 2]) -> usize {
|
||||
@@ -594,12 +798,279 @@ mod tests {
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
|
||||
}
|
||||
|
||||
fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind {
|
||||
EntityKind::MText(cadcraft_doc::MText {
|
||||
insert: Vec3::new(0.0, 0.0, 0.0),
|
||||
height: 2.5,
|
||||
width: 10.0,
|
||||
attach,
|
||||
rotation,
|
||||
style: "Standard".into(),
|
||||
contents: contents.into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A blank MTEXT has no strokes and empty drawn bounds, but it is still an object: a click
|
||||
/// inside its width x height box picks it, and a click outside does not (#2810).
|
||||
#[test]
|
||||
fn a_blank_mtext_is_picked_inside_its_box() {
|
||||
let blank = |c: &str| matches!(mtext_at(c, 1, 0.0), EntityKind::MText(t) if is_blank_mtext(&t));
|
||||
assert!(!blank(r"a\~"));
|
||||
assert!(blank(r"\~ \~"));
|
||||
for contents in ["", " ", r"\~ "] {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), mtext_at(contents, 1, 0.0)).unwrap();
|
||||
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.1);
|
||||
assert_eq!(at(5.0, -1.0), Some(h), "{contents:?}");
|
||||
assert_eq!(at(0.5, -2.0), Some(h), "{contents:?}");
|
||||
assert_eq!(at(5.0, 3.0), None, "above the box, {contents:?}");
|
||||
assert_eq!(at(12.0, -1.0), None, "right of the box, {contents:?}");
|
||||
assert_eq!(pick_all(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), vec![h]);
|
||||
let w = Bounds2::new(Vec2::new(4.0, -2.0), Vec2::new(6.0, -1.0));
|
||||
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing {contents:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_mleader_text_is_picked_inside_its_box() {
|
||||
for contents in [" ", ""] {
|
||||
let mut s = crate::Session::new();
|
||||
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
|
||||
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
|
||||
// The command omits the text object for an empty string. Preserve the box here to
|
||||
// exercise a stored empty MTEXT, which can still exist in an imported MLEADER.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
|
||||
m.text.as_mut().unwrap().contents = contents.into();
|
||||
})
|
||||
.unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
|
||||
let t = m.text.as_ref().unwrap();
|
||||
let p = t.insert.xy() + Vec2::new(t.height / 2.0, -t.height / 4.0);
|
||||
let aperture = t.height / 100.0;
|
||||
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "{contents:?}");
|
||||
|
||||
let d = s.doc_mut().unwrap();
|
||||
for i in 0..spatial::MIN_INDEXED {
|
||||
let y = 100.0 + i as f64;
|
||||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
|
||||
d.add(&Space::Model, Common::default(), line).unwrap();
|
||||
}
|
||||
assert!(spatial::index(d, &Space::Model).is_some());
|
||||
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "indexed {contents:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_away_from_normal_mleader_text_and_lines_misses() {
|
||||
let mut s = crate::Session::new();
|
||||
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap();
|
||||
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(pick(s.doc().unwrap(), &Space::Model, Vec2::new(2.0, 8.0), 0.05), None);
|
||||
// Give the text a wide box: a click inside it, right of the glyphs and off the leader, is
|
||||
// still a miss, since only blank text is picked by its frame.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
|
||||
m.text.as_mut().unwrap().width = 5.0;
|
||||
})
|
||||
.unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
|
||||
let t = m.text.as_ref().unwrap();
|
||||
let p = t.insert.xy() + Vec2::new(t.width * 0.8, 0.0);
|
||||
assert_eq!(pick(d, &Space::Model, p, 0.02), None, "right of the glyphs, inside the frame");
|
||||
assert_eq!(pick(d, &Space::Model, t.insert.xy() + Vec2::new(0.3, 0.0), 0.02), Some(h), "on the glyphs");
|
||||
}
|
||||
|
||||
/// Only blank MTEXT has a frame: an annotative non-blank MTEXT and an annotative LINE have none
|
||||
/// (and the kind and blankness are decided before any annotation scaling).
|
||||
#[test]
|
||||
fn only_blank_mtext_has_a_frame_even_when_annotative() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_str("CANNOSCALE", "1:2");
|
||||
let half = d.anno_scale("1:2").cloned().unwrap();
|
||||
let common = || Common { anno_scales: vec![half.clone()], ..Common::default() };
|
||||
let text = d.add(&Space::Model, common(), mtext_at("Visible", 1, 0.0)).unwrap();
|
||||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) });
|
||||
let line = d.add(&Space::Model, common(), line).unwrap();
|
||||
let blank = d.add(&Space::Model, common(), mtext_at(" ", 1, 0.0)).unwrap();
|
||||
for (h, framed) in [(text, false), (line, false), (blank, true)] {
|
||||
let e = d.entity(h).unwrap();
|
||||
assert_eq!(blank_mtext_frame(&d, e).is_some(), framed);
|
||||
}
|
||||
}
|
||||
|
||||
/// A multileader whose text is blank, with the text 6 units right of the landing, 4 wide and
|
||||
/// 2 high, attached top-left.
|
||||
fn blank_mleader(s: &mut crate::Session) -> Handle {
|
||||
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
|
||||
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
|
||||
let landing = m.landing;
|
||||
let t = m.text.as_mut().unwrap();
|
||||
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
|
||||
t.width = 4.0;
|
||||
t.height = 2.0;
|
||||
t.attach = 1;
|
||||
t.rotation = 0.0;
|
||||
})
|
||||
.unwrap();
|
||||
h
|
||||
}
|
||||
|
||||
/// A crossing window wholly inside a blank multileader text's box selects it, as a click does.
|
||||
#[test]
|
||||
fn a_crossing_window_inside_a_blank_mleader_text_box_selects_it() {
|
||||
let mut s = crate::Session::new();
|
||||
let h = blank_mleader(&mut s);
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
|
||||
let o = m.text.as_ref().unwrap().insert.xy();
|
||||
let inside = Bounds2::new(o + Vec2::new(1.0, -1.5), o + Vec2::new(2.0, -0.5));
|
||||
assert_eq!(select_window(d, &Space::Model, inside, true), vec![h]);
|
||||
let outside = Bounds2::new(o + Vec2::new(5.0, -1.5), o + Vec2::new(6.0, -0.5));
|
||||
assert!(select_window(d, &Space::Model, outside, true).is_empty());
|
||||
}
|
||||
|
||||
/// An annotative multileader's blank text is picked where it draws at the current annotation
|
||||
/// scale: its size and its offset from the landing both scale.
|
||||
#[test]
|
||||
fn an_annotative_blank_mleader_text_is_picked_at_its_drawn_offset_and_size() {
|
||||
let mut s = crate::Session::new();
|
||||
let h = blank_mleader(&mut s);
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.header.set_str("CANNOSCALE", "1:2");
|
||||
let half = d.anno_scale("1:2").cloned().unwrap();
|
||||
d.modify_entity(h, |e| e.common.anno_scales = vec![half]).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
|
||||
let l = m.landing.xy();
|
||||
// At 1:2 the box is 8 x 4 from the landing + (12, 0) (top-left): x 12..20, y -4..0.
|
||||
let at = |x: f64, y: f64| pick(d, &Space::Model, l + Vec2::new(x, y), 0.02);
|
||||
assert_eq!(at(16.0, -1.0), Some(h), "inside the scaled box, outside the unscaled one");
|
||||
assert_eq!(at(19.5, -3.5), Some(h), "far corner of the scaled box");
|
||||
assert_eq!(at(8.0, -1.0), None, "inside the unscaled box, outside the scaled one");
|
||||
assert_eq!(at(22.0, -1.0), None, "right of the scaled box");
|
||||
}
|
||||
|
||||
/// The box follows the attachment point and the rotation, and a width of 0 falls back to the
|
||||
/// text height.
|
||||
#[test]
|
||||
fn a_blank_mtext_box_follows_attachment_and_rotation() {
|
||||
let mut d = Drawing::new_metric();
|
||||
// Middle-centre: the box spans x -5..5, y -1.25..1.25.
|
||||
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, 0.0)).unwrap();
|
||||
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
|
||||
assert_eq!(at(&d, -4.0, 1.0), Some(h));
|
||||
assert_eq!(at(&d, 4.0, -1.0), Some(h));
|
||||
assert_eq!(at(&d, 4.0, 2.0), None);
|
||||
// Turned a quarter turn about the insertion point: the box spans x -1.25..1.25, y -5..5.
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, std::f64::consts::FRAC_PI_2)).unwrap();
|
||||
assert_eq!(at(&d, 1.0, 4.0), Some(h));
|
||||
assert_eq!(at(&d, 4.0, 1.0), None);
|
||||
// No width: as wide as the text is high.
|
||||
let mut d = Drawing::new_metric();
|
||||
let EntityKind::MText(mut t) = mtext_at("", 1, 0.0) else { panic!("mtext") };
|
||||
t.width = 0.0;
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
assert_eq!(at(&d, 2.0, -1.0), Some(h));
|
||||
assert_eq!(at(&d, 5.0, -1.0), None);
|
||||
}
|
||||
|
||||
/// A top-level MTEXT that matches the layout orientation is drawn upright, ignoring its stored
|
||||
/// rotation, so its frame is the unturned one (the renderer and the extents do the same).
|
||||
#[test]
|
||||
fn rotated_blank_mtext_matching_layout_orientation_is_picked_in_its_unrotated_frame() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||||
let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() };
|
||||
let h = d.add(&Space::Model, common, mtext_at(" ", 1, std::f64::consts::FRAC_PI_2)).unwrap();
|
||||
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
|
||||
// Unrotated frame x 0..10, y -2.5..0; the rotated one would be x 0..2.5, y 0..10.
|
||||
assert_eq!(at(5.0, -1.0), Some(h), "inside the unrotated frame");
|
||||
assert_eq!(at(1.0, 5.0), None, "inside only the rotated frame");
|
||||
}
|
||||
|
||||
/// A turned blank MTEXT is hit in its turned box, not in the axis-aligned box around it (whose
|
||||
/// empty corners lie off the text).
|
||||
#[test]
|
||||
fn a_turned_blank_mtext_is_picked_in_its_turned_box() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 1, 30f64.to_radians())).unwrap();
|
||||
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
|
||||
// Local (5, -1.25), the centre of the box.
|
||||
assert_eq!(at(4.955, 1.418), Some(h));
|
||||
// Inside the box around the turned one, but local (2.87, 2.96) is above the text.
|
||||
assert_eq!(at(1.0, 4.0), None);
|
||||
}
|
||||
|
||||
/// An annotative blank MTEXT is picked in the box it draws at the current annotation scale,
|
||||
/// and not at all while that scale hides it.
|
||||
#[test]
|
||||
fn an_annotative_blank_mtext_is_picked_at_its_drawn_size() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_str("CANNOSCALE", "1:2");
|
||||
let half = d.anno_scale("1:2").cloned().unwrap();
|
||||
let common = Common { anno_scales: vec![half], ..Common::default() };
|
||||
// Middle-centre at 1:2: twice the size, x -10..10, y -2.5..2.5.
|
||||
let h = d.add(&Space::Model, common, mtext_at(" ", 5, 0.0)).unwrap();
|
||||
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
|
||||
assert_eq!(at(&d, 8.0, 2.0), Some(h), "inside the scaled box");
|
||||
assert_eq!(at(&d, 11.0, 0.0), None, "outside the scaled box");
|
||||
let w = Bounds2::new(Vec2::new(7.0, 1.0), Vec2::new(9.0, 2.0));
|
||||
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing the scaled box");
|
||||
// At 1:1 with only supported scales shown, the object is hidden: nothing to pick.
|
||||
d.header.set_str("CANNOSCALE", "1:1");
|
||||
d.header.set_i64("ANNOALLVISIBLE", 0);
|
||||
assert_eq!(at(&d, 0.0, 0.0), None, "hidden");
|
||||
let w = Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(1.0, 1.0));
|
||||
assert!(select_window(&d, &Space::Model, w, true).is_empty(), "hidden, crossing");
|
||||
}
|
||||
|
||||
/// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate.
|
||||
#[test]
|
||||
fn a_blank_mtext_is_picked_in_an_indexed_drawing() {
|
||||
let mut d = Drawing::new_metric();
|
||||
for i in 0..(crate::spatial::MIN_INDEXED + 10) {
|
||||
let y = 100.0 + i as f64;
|
||||
let l = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
|
||||
d.add(&Space::Model, Common::default(), l).unwrap();
|
||||
}
|
||||
let h = d.add(&Space::Model, Common::default(), mtext_at("", 1, 0.0)).unwrap();
|
||||
assert!(spatial::index(&d, &Space::Model).is_some());
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), Some(h));
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, 3.0), 0.1), None);
|
||||
}
|
||||
|
||||
/// Text with words is still picked by its drawn box only.
|
||||
#[test]
|
||||
fn a_click_far_from_a_normal_mtext_misses() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), mtext_at("AB", 1, 0.0)).unwrap();
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, -1.0), 0.1), Some(h));
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(8.0, -1.0), 0.1), None);
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, 5.0), 0.1), None);
|
||||
}
|
||||
|
||||
/// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in
|
||||
/// the middle of the frame, or on a frame without both corners, does not.
|
||||
#[test]
|
||||
fn clicking_an_ole_frame_edge_selects_it() {
|
||||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||||
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let frame =
|
||||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap();
|
||||
@@ -645,8 +1116,8 @@ mod tests {
|
||||
let e = d.entity(h).unwrap();
|
||||
let drawn = cadcraft_render::build_entities(&d, std::iter::once(e.as_ref()), &cadcraft_render::Options { text: false, ..Default::default() });
|
||||
assert!(drawn.prims.len() > 10_000, "the pattern draws {} dashes", drawn.prims.len());
|
||||
// The line, and the block's bounding rectangle.
|
||||
assert_eq!(hit_polylines(&d, e, 0.01).len(), 2);
|
||||
// Hit testing uses the line without laying out every dash.
|
||||
assert_eq!(hit_polylines(&d, e, 0.01).len(), 1);
|
||||
}
|
||||
|
||||
/// A dashed line in a block is hit across its gaps, as one outside a block is.
|
||||
@@ -661,6 +1132,126 @@ mod tests {
|
||||
let gap = end + (start - end) * 0.5;
|
||||
assert_eq!(pick(&d, &Space::Model, gap, end.dist(start) / 8.0), Some(h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_a_transformed_block_requires_its_drawn_geometry() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut block = cadcraft_doc::Block::new("two lines");
|
||||
for y in [0.0, 5.0] {
|
||||
block.entities.push(Entity::new(
|
||||
Handle(10 + y as u64),
|
||||
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }),
|
||||
));
|
||||
}
|
||||
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
|
||||
let insert = cadcraft_doc::Insert {
|
||||
block: "two lines".into(),
|
||||
insert: Vec3::new(30.0, 40.0, 0.0),
|
||||
scale: Vec3::new(2.0, 2.0, 1.0),
|
||||
rotation: std::f64::consts::FRAC_PI_2,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
|
||||
let bx = |a, b| Bounds2::new(a, b);
|
||||
let empty = bx(Vec2::new(24.0, 48.0), Vec2::new(26.0, 52.0));
|
||||
let crossed = bx(Vec2::new(19.0, 48.0), Vec2::new(21.0, 52.0));
|
||||
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
|
||||
assert_eq!(select_window(&d, &Space::Model, crossed, true), vec![h]);
|
||||
assert!(select_window(&d, &Space::Model, crossed, false).is_empty());
|
||||
assert_eq!(pick(&d, &Space::Model, Vec2::new(25.0, 40.0), 0.1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_a_block_fill_uses_the_filled_shape() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut block = cadcraft_doc::Block::new("filled triangle");
|
||||
let a = Vec3::new(0.0, 0.0, 0.0);
|
||||
let b = Vec3::new(10.0, 0.0, 0.0);
|
||||
let c = Vec3::new(0.0, 10.0, 0.0);
|
||||
block.entities.push(Entity::new(Handle(10), EntityKind::Solid(cadcraft_doc::Solid { corners: [a, b, c, c] })));
|
||||
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
|
||||
let insert = cadcraft_doc::Insert {
|
||||
block: "filled triangle".into(),
|
||||
insert: Vec3::new(0.0, 0.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
|
||||
let empty = Bounds2::new(Vec2::new(7.0, 7.0), Vec2::new(8.0, 8.0));
|
||||
let filled = Bounds2::new(Vec2::new(2.0, 2.0), Vec2::new(3.0, 3.0));
|
||||
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
|
||||
assert_eq!(select_window(&d, &Space::Model, filled, true), vec![h]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_a_block_ray_and_xline_uses_their_direction() {
|
||||
for (kind, behind) in [(true, false), (false, true)] {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut block = cadcraft_doc::Block::new("infinite");
|
||||
let line = RayLine { base: Vec3::new(100.0, 100.0, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) };
|
||||
block.entities.push(Entity::new(Handle(10), if kind { EntityKind::Ray(line) } else { EntityKind::XLine(line) }));
|
||||
block
|
||||
.entities
|
||||
.push(Entity::new(Handle(11), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(200.0, 0.0, 0.0) })));
|
||||
block.entities.push(Entity::new(
|
||||
Handle(12),
|
||||
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 0.0, 0.0), b: Vec3::new(200.0, 200.0, 0.0) }),
|
||||
));
|
||||
block.entities.push(Entity::new(
|
||||
Handle(13),
|
||||
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 200.0, 0.0), b: Vec3::new(0.0, 200.0, 0.0) }),
|
||||
));
|
||||
block
|
||||
.entities
|
||||
.push(Entity::new(Handle(14), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 200.0, 0.0), b: Vec3::new(0.0, 0.0, 0.0) })));
|
||||
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
|
||||
let insert = cadcraft_doc::Insert { block: "infinite".into(), ..Default::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
|
||||
let ahead = Bounds2::new(Vec2::new(149.0, 99.0), Vec2::new(151.0, 101.0));
|
||||
let back = Bounds2::new(Vec2::new(49.0, 99.0), Vec2::new(51.0, 101.0));
|
||||
assert_eq!(select_window(&d, &Space::Model, ahead, true), vec![h]);
|
||||
assert_eq!(select_window(&d, &Space::Model, back, true).contains(&h), behind);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_a_block_image_respects_its_clip() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.rasters.insert("map.png", std::sync::Arc::new(Raster::new(2, 2, vec![255; 16]).unwrap()));
|
||||
let mut block = cadcraft_doc::Block::new("picture");
|
||||
block.entities.push(Entity::new(
|
||||
Handle(10),
|
||||
EntityKind::Image(Image {
|
||||
insert: Vec3::ZERO,
|
||||
u: Vec3::new(5.0, 0.0, 0.0),
|
||||
v: Vec3::new(0.0, 5.0, 0.0),
|
||||
size: Vec2::new(2.0, 2.0),
|
||||
path: "map.png".into(),
|
||||
clipping: true,
|
||||
clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(0.5, 1.5)],
|
||||
..Default::default()
|
||||
}),
|
||||
));
|
||||
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
|
||||
let h = d
|
||||
.add(&Space::Model, Common::default(), EntityKind::Insert(cadcraft_doc::Insert { block: "picture".into(), ..Default::default() }))
|
||||
.unwrap();
|
||||
let visible = Bounds2::new(Vec2::new(2.0, 4.0), Vec2::new(3.0, 6.0));
|
||||
let hidden = Bounds2::new(Vec2::new(7.0, 4.0), Vec2::new(8.0, 6.0));
|
||||
assert_eq!(select_window(&d, &Space::Model, visible, true), vec![h]);
|
||||
assert!(select_window(&d, &Space::Model, hidden, true).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -722,7 +1313,7 @@ mod hatch_pattern_pick_tests {
|
||||
|
||||
fn square(lo: f64, hi: f64, outer: bool) -> HatchLoop {
|
||||
let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
|
||||
HatchLoop { vertices, outer, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
}
|
||||
|
||||
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
|
||||
@@ -788,6 +1379,7 @@ mod hatch_pattern_pick_tests {
|
||||
let tri = HatchLoop {
|
||||
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
|
||||
outer: true,
|
||||
boundary_flags: None,
|
||||
sources: Vec::new(),
|
||||
};
|
||||
let d = solid_hatch(vec![tri], 0);
|
||||
@@ -809,4 +1401,38 @@ mod hatch_pattern_pick_tests {
|
||||
let d = solid_hatch(loops(), 2);
|
||||
assert!(pick(&d, &Space::Model, Vec2::new(5.0, 5.0), 0.05).is_some());
|
||||
}
|
||||
|
||||
/// A window around everything a blank multileader draws (its geometry and its text frame)
|
||||
/// selects it, at either annotation scale: the stored insertion points snap offers do not
|
||||
/// widen the box a window has to contain (#2810).
|
||||
#[test]
|
||||
fn window_around_a_blank_multileader_still_selects_it() {
|
||||
use cadcraft_geom::Vec3;
|
||||
for scale in ["1:2", "2:1"] {
|
||||
let mut s = crate::Session::new();
|
||||
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.header.set_str("CANNOSCALE", scale);
|
||||
let sc = d.anno_scale(scale).cloned().unwrap();
|
||||
d.modify_entity(h, |e| {
|
||||
e.common.anno_scales = vec![sc];
|
||||
let EntityKind::MLeader(m) = &mut e.kind else { return };
|
||||
let landing = m.landing;
|
||||
if let Some(t) = m.text.as_mut() {
|
||||
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
|
||||
t.width = 4.0;
|
||||
t.height = 2.0;
|
||||
t.attach = 1;
|
||||
t.rotation = 0.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let d = &*d;
|
||||
let e = d.entity(h).unwrap();
|
||||
let frame = blank_mtext_box(d, e).expect("a blank multileader has a frame");
|
||||
let bx = entity_bounds(d, e, 0).union(&frame).expand(0.01);
|
||||
assert!(select_window(d, &Space::Model, bx, false).contains(&h), "scale {scale}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ use super::error::{EngineError, Result};
|
||||
use super::running::{PendingWindow, Running};
|
||||
use super::view::View;
|
||||
use super::{
|
||||
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp, pointmod,
|
||||
prompt, select, snap, sysvars, units,
|
||||
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp,
|
||||
pointmod, prompt, select, snap, sysvars, units,
|
||||
};
|
||||
|
||||
mod cmdline;
|
||||
|
||||
@@ -192,6 +192,7 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_lines(&mut self, text: &str) -> Result<()> {
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
for line in text.lines() {
|
||||
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
|
||||
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::DisplayOnly;
|
||||
|
||||
use super::{
|
||||
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2,
|
||||
assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
|
||||
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, Origin, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value,
|
||||
Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
|
||||
};
|
||||
|
||||
impl Session {
|
||||
@@ -41,8 +41,29 @@ impl Session {
|
||||
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
|
||||
}
|
||||
|
||||
/// Start a command by name or alias as if typed at the command line.
|
||||
/// Who started the command running now ([`Origin`]): fixed when it started, so a scripted or
|
||||
/// LISP-started command keeps its origin while it prompts.
|
||||
pub fn command_origin(&self) -> Origin {
|
||||
self.command_origin
|
||||
}
|
||||
|
||||
/// Start a command by name or alias as if typed at the command line. A script's commands are
|
||||
/// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so
|
||||
/// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command
|
||||
/// "LINE" "0,0" "'-INSERT" …)` replaces LINE with an INSERT the routine started.
|
||||
pub fn start(&mut self, name: &str) -> Result<()> {
|
||||
let origin = if self.in_script || self.program_input { Origin::Program } else { Origin::Person };
|
||||
self.start_from(name, origin)
|
||||
}
|
||||
|
||||
/// Start a command as a program does: an AutoLISP `(command …)` cannot answer a dialog, so
|
||||
/// none opens for what it starts, even after the routine ends.
|
||||
pub fn start_programmatic(&mut self, name: &str) -> Result<()> {
|
||||
self.start_from(name, Origin::Program)
|
||||
}
|
||||
|
||||
/// [`Session::start`] with the command's origin recorded for its whole life.
|
||||
fn start_from(&mut self, name: &str, origin: Origin) -> Result<()> {
|
||||
self.last_polar = None;
|
||||
self.pick_hint = None;
|
||||
let name = name.trim();
|
||||
@@ -74,7 +95,7 @@ impl Session {
|
||||
// A bare system variable name (ORTHOMODE, GRIDMODE…) acts as SETVAR on that variable.
|
||||
let var = lower.to_ascii_uppercase();
|
||||
if !name.starts_with(['_', '.', '-']) && sysvars::get(self, &var).is_some() {
|
||||
self.start(if transparent { "'setvar" } else { "setvar" })?;
|
||||
self.start_from(if transparent { "'setvar" } else { "setvar" }, origin)?;
|
||||
return self.input(Input::Text(var));
|
||||
}
|
||||
return Err(EngineError::UnknownCommand(typed.to_string()));
|
||||
@@ -101,10 +122,15 @@ impl Session {
|
||||
return self.input(Input::Keyword("Undo".into()));
|
||||
}
|
||||
if !nested {
|
||||
self.commands_started = self.commands_started.wrapping_add(1);
|
||||
// The command this one replaces is cancelled first: its cancellation can run a paused
|
||||
// LISP routine's `*error*` handler, and a handler that starts a command records that
|
||||
// command's Program origin. Origin and number go in after it, so they describe this
|
||||
// start and the factory below still sees the origin this command was started with.
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
}
|
||||
self.commands_started = self.commands_started.wrapping_add(1);
|
||||
self.command_origin = origin;
|
||||
}
|
||||
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
|
||||
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) {
|
||||
@@ -541,6 +567,17 @@ impl Session {
|
||||
self.running.as_ref().and_then(|r| r.machine.text_editor())
|
||||
}
|
||||
|
||||
/// The attribute values the running command asks for in the Edit Attributes dialog
|
||||
/// ([`Interactive::attribute_entry`]), stamped with the drawing it runs in and its number in
|
||||
/// [`Session::commands_started`]: a dialog draft kept for a cancelled command never belongs
|
||||
/// to the one started after it, even for the same block.
|
||||
pub fn attribute_entry(&self) -> Option<crate::AttribEntry> {
|
||||
let mut entry = self.running.as_ref().and_then(|r| r.machine.attribute_entry())?;
|
||||
entry.drawing = self.docs.get(self.active).map_or(0, |d| d.uid);
|
||||
entry.command = self.commands_started;
|
||||
Some(entry)
|
||||
}
|
||||
|
||||
pub fn current_prompt(&self) -> Option<Prompt> {
|
||||
if let Some(p) = self.lisp_prompt() {
|
||||
return Some(p);
|
||||
@@ -608,6 +645,12 @@ impl Session {
|
||||
out
|
||||
}
|
||||
|
||||
/// The value the cursor would give at the active command's prompt (see
|
||||
/// [`Interactive::live_value`]).
|
||||
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
|
||||
self.running.as_ref()?.machine.live_value(self, cursor)
|
||||
}
|
||||
|
||||
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
|
||||
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
|
||||
/// `None`: the drawing.
|
||||
|
||||
@@ -138,6 +138,9 @@ pub struct Settings {
|
||||
/// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them
|
||||
/// (default: 1).
|
||||
pub attreq: bool,
|
||||
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
|
||||
/// dialog; on by default, as in AutoCAD (Initial value 1).
|
||||
pub attdia: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -205,6 +208,7 @@ impl Default for Settings {
|
||||
ucs_angle: 0.0,
|
||||
auditctl: false,
|
||||
attreq: true,
|
||||
attdia: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
+274
-18
@@ -7,7 +7,7 @@ mod viewport;
|
||||
|
||||
pub use viewport::ViewportPoint;
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
|
||||
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -385,7 +385,7 @@ fn osnap_in_with_prims(
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
// that don't reach each other).
|
||||
@@ -475,9 +475,60 @@ pub(crate) fn gather(
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[])
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
|
||||
}
|
||||
|
||||
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
||||
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
||||
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
||||
/// block reference with. Objects on the layers `frozen` in the active viewport aren't drawn there,
|
||||
/// so they are passed over.
|
||||
pub(crate) fn nearest_with_direction(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
frozen: &[String],
|
||||
skip: Handle,
|
||||
) -> Option<(Vec2, Vec2)> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, frozen, Some(skip))?;
|
||||
let mut best: Option<(f64, Vec2, Vec2)> = None;
|
||||
let mut consider = |at: Vec2, dir: Vec2| {
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
|
||||
best = Some((dd, at, dir * (1.0 / dir.len())));
|
||||
}
|
||||
};
|
||||
for p in prims.iter().take(2000) {
|
||||
if let Prim::Circle(c) = p {
|
||||
let at = c.closest(cursor);
|
||||
consider(at, (at - c.center).perp());
|
||||
continue;
|
||||
}
|
||||
if let Prim::Infinite { base, dir, ray } = p {
|
||||
let len = dir.len();
|
||||
if len > 1e-12 {
|
||||
let u = *dir * (1.0 / len);
|
||||
// A ray runs one way from its base: behind it, its base is the nearest point.
|
||||
let t = (cursor - *base).dot(u);
|
||||
consider(*base + u * if *ray { t.max(0.0) } else { t }, u);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for seg in prim_segments(p) {
|
||||
let seg = fix_circle(&seg);
|
||||
let at = seg.closest(cursor);
|
||||
match seg {
|
||||
Segment::Line(l) => consider(at, l.b - l.a),
|
||||
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, at, dir)| (at, dir))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
@@ -486,6 +537,7 @@ fn gather_in(
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
frozen: &[String],
|
||||
skip: Option<Handle>,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
let probe = Bounds2::new(cursor, cursor).expand(aperture);
|
||||
let mut cands: Vec<(u32, Vec2)> = Vec::new();
|
||||
@@ -493,13 +545,19 @@ fn gather_in(
|
||||
let mut count = 0usize;
|
||||
let mut budget = MAX_BLOCK_LEAVES;
|
||||
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
|
||||
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
|
||||
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
|
||||
continue;
|
||||
}
|
||||
let inf = crate::select::is_infinite(e);
|
||||
if !inf && !crate::select::bounds_of(d, e, known).expand(aperture).intersects(&probe) {
|
||||
continue;
|
||||
}
|
||||
// A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate
|
||||
// limit nor the intersection slots unless its drawn geometry is in reach, or INS is on and an
|
||||
// insertion point is within the aperture.
|
||||
if !inf && crate::select::blank_frame_only(d, e, &probe, cursor, aperture, osmode & mode::INS != 0) {
|
||||
continue;
|
||||
}
|
||||
count += 1;
|
||||
if count > 2000 {
|
||||
break;
|
||||
@@ -515,6 +573,7 @@ fn gather_in(
|
||||
}
|
||||
EntityKind::AttDef(a) => cands.push((mode::INS, a.text.justify_point())),
|
||||
// A multileader: its text's insertion point, or its block content's.
|
||||
// select.rs blank_snap_points must offer the same points.
|
||||
EntityKind::MLeader(m) => {
|
||||
cands.extend(m.text.iter().map(|t| (mode::INS, t.insert.xy())));
|
||||
cands.extend(m.block.iter().map(|b| (mode::INS, b.insert.xy())));
|
||||
@@ -531,6 +590,15 @@ fn gather_in(
|
||||
if let EntityKind::Dimension(dm) = &e.kind {
|
||||
sink.dimension(d, dm, &mut budget, frozen);
|
||||
}
|
||||
// A dimension kept as read draws its block through a reference in its graphics (#3438),
|
||||
// and snaps to the objects inside it the same way.
|
||||
if let EntityKind::Unknown(u) = &e.kind {
|
||||
for g in &u.graphics {
|
||||
if let EntityKind::Insert(ins) = &g.kind {
|
||||
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
@@ -772,20 +840,7 @@ impl Sink<'_> {
|
||||
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
|
||||
match dm.block.as_ref().and_then(|n| d.block(n)) {
|
||||
Some(blk) => {
|
||||
// The block holds world geometry: a reference at its own base point places it as is.
|
||||
let ins = Insert {
|
||||
block: blk.name.clone(),
|
||||
insert: blk.base,
|
||||
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
block_leaves(d, &ins, &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
|
||||
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
|
||||
}
|
||||
None => {
|
||||
let g = cadcraft_render::dimension_in(d, dm);
|
||||
@@ -862,6 +917,18 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
|
||||
match &be.kind {
|
||||
EntityKind::AttDef(_) => {}
|
||||
EntityKind::Insert(inner) => block_leaves(d, inner, &mm, depth + 1, budget, frozen, f),
|
||||
// A dimension draws its block, as at the top level.
|
||||
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
|
||||
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
|
||||
}
|
||||
k @ EntityKind::Unknown(u) => {
|
||||
f(k, &mm);
|
||||
for g in &u.graphics {
|
||||
if let EntityKind::Insert(inner) = &g.kind {
|
||||
block_leaves(d, inner, &mm, depth + 1, budget, frozen, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
k => f(k, &mm),
|
||||
}
|
||||
}
|
||||
@@ -869,6 +936,24 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference that places a dimension's block as the renderer draws it: the block holds world
|
||||
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
|
||||
/// dimension; #2634).
|
||||
fn dimension_reference(blk: &cadcraft_doc::Block, dm: &cadcraft_doc::Dimension) -> Insert {
|
||||
Insert {
|
||||
block: blk.name.clone(),
|
||||
insert: blk.base + dm.insertion_point,
|
||||
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` comes within `aperture` of the box `probe`.
|
||||
fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool {
|
||||
let b = match p {
|
||||
@@ -1171,6 +1256,27 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alignment_targets_stay_on_a_ray_and_off_frozen_layers() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let ray = |base: (f64, f64)| EntityKind::Ray(cadcraft_doc::RayLine { base: Vec3::new(base.0, base.1, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) });
|
||||
d.add(&Space::Model, Common::default(), ray((0.0, 0.0))).unwrap();
|
||||
// Behind the ray: its base is the nearest point, out of a small aperture.
|
||||
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(-5.0, 0.0), 0.5, &[], Handle(0)), None);
|
||||
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(-0.2, 0.1), 0.5, &[], Handle(0)).unwrap();
|
||||
assert!(at.dist(Vec2::ZERO) < 1e-12, "{at:?}");
|
||||
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 0.1), 0.5, &[], Handle(0)).unwrap();
|
||||
assert!(at.dist(Vec2::new(5.0, 0.0)) < 1e-12, "{at:?}");
|
||||
// A line on a layer frozen in the viewport isn't a target.
|
||||
let mut d = drawing();
|
||||
d.ensure_layer("Hidden");
|
||||
let c = Common { layer: "Hidden".into(), ..Common::default() };
|
||||
let l = EntityKind::Line(Line { a: Vec3::new(0.0, 30.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) });
|
||||
d.add(&Space::Model, c, l).unwrap();
|
||||
assert!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &[], Handle(0)).is_some());
|
||||
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_and_mid() {
|
||||
let d = drawing();
|
||||
@@ -1180,6 +1286,156 @@ mod tests {
|
||||
assert_eq!(m.point, Vec2::new(5.0, 0.0));
|
||||
}
|
||||
|
||||
/// Blank MTEXT frames over the cursor are for picking: thousands of them, with their insertion
|
||||
/// points out of reach, must not crowd a real endpoint out of the snap candidates (#2810).
|
||||
#[test]
|
||||
fn blank_mtext_frames_do_not_crowd_out_snap_candidates() {
|
||||
for line_first in [true, false] {
|
||||
let mut d = Drawing::new_metric();
|
||||
let line = EntityKind::Line(Line { a: Vec3::new(5.2, -1.0, 0.0), b: Vec3::new(30.0, -1.0, 0.0) });
|
||||
if line_first {
|
||||
d.add(&Space::Model, Common::default(), line.clone()).unwrap();
|
||||
}
|
||||
for _ in 0..2100 {
|
||||
let t = cadcraft_doc::MText {
|
||||
insert: Vec3::new(0.0, 0.0, 0.0),
|
||||
height: 2.5,
|
||||
width: 10.0,
|
||||
attach: 1,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: " ".into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
}
|
||||
if !line_first {
|
||||
d.add(&Space::Model, Common::default(), line).unwrap();
|
||||
}
|
||||
// The cursor is inside every box (x 0..10, y -2.5..0), 0.2 from the line's end.
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.5, mode::END, None, false).unwrap();
|
||||
assert_eq!(h.point, Vec2::new(5.2, -1.0), "line first: {line_first}");
|
||||
// A blank MTEXT whose insertion point is in the aperture keeps its INS snap.
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(0.1, -0.1), 0.5, mode::INS, None, false).unwrap();
|
||||
assert_eq!(h.point, Vec2::new(0.0, 0.0), "line first: {line_first}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 2001 blank MTEXT frames covering `cursor` (insertion points at `ins_at`), drawn before a
|
||||
/// LINE whose end is at `cursor`: the END snap found with `osmode`.
|
||||
fn crowded_blank_frames_end_snap(ins_at: Vec2, cursor: Vec2, aperture: f64, osmode: u32) -> Option<Vec2> {
|
||||
let mut d = Drawing::new_metric();
|
||||
for _ in 0..2001 {
|
||||
let t = cadcraft_doc::MText {
|
||||
insert: Vec3::new(ins_at.x, ins_at.y, 0.0),
|
||||
height: 2.5,
|
||||
width: 10.0,
|
||||
attach: 1,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: " ".into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
}
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(cursor.x, cursor.y, 0.0), b: Vec3::new(30.0, cursor.y, 0.0) }))
|
||||
.unwrap();
|
||||
osnap(&d, &Space::Model, cursor, aperture, osmode, None, false).map(|h| h.point)
|
||||
}
|
||||
|
||||
/// An insertion point in a corner of the square probe is farther than the aperture from the
|
||||
/// cursor, so snap would never accept it: its frame must not crowd out an END snap.
|
||||
#[test]
|
||||
fn blank_insertion_points_in_the_probe_corner_do_not_crowd_out_an_end_snap() {
|
||||
let cursor = Vec2::new(5.0, -1.0);
|
||||
let ap = 0.5;
|
||||
let corner = Vec2::new(cursor.x - 0.9 * ap, cursor.y + 0.9 * ap);
|
||||
assert!(corner.dist(cursor) > ap, "outside the circle, inside the square probe");
|
||||
assert_eq!(crowded_blank_frames_end_snap(corner, cursor, ap, mode::END | mode::INS), Some(cursor));
|
||||
}
|
||||
|
||||
/// With INS off a blank MTEXT's insertion point is no snap candidate, even right at the cursor.
|
||||
#[test]
|
||||
fn blank_insertion_points_with_ins_off_do_not_crowd_out_an_end_snap() {
|
||||
let cursor = Vec2::new(5.0, -1.0);
|
||||
assert_eq!(crowded_blank_frames_end_snap(cursor, cursor, 0.5, mode::END), Some(cursor));
|
||||
}
|
||||
|
||||
/// A blank annotative multileader (text 6 right of its landing, 4 x 2, at 1:2) among 2100 blank
|
||||
/// MTEXT frames over the cursor. `block_at` also gives it a block content at that offset from
|
||||
/// the landing. Returns the INS snap at `landing + probe` (aperture 0.5).
|
||||
fn crowded_blank_mleader_ins(block_at: Option<f64>, probe: Vec2) -> Option<Vec2> {
|
||||
let mut s = crate::Session::new();
|
||||
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
|
||||
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let landing = {
|
||||
let d = s.doc_mut().unwrap();
|
||||
if block_at.is_some() {
|
||||
// A block whose geometry (a line 60 long) covers its base point, at the stored insertion
|
||||
// and, drawn at 1:2 about the landing, at the scaled one too.
|
||||
let mut blk = cadcraft_doc::Block::new("BLK");
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(60.0, 0.0, 0.0) });
|
||||
blk.entities.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), line));
|
||||
d.blocks.insert("BLK".into(), std::sync::Arc::new(blk));
|
||||
}
|
||||
d.header.set_str("CANNOSCALE", "1:2");
|
||||
let half = d.anno_scale("1:2").cloned().unwrap();
|
||||
d.modify_entity(h, |e| {
|
||||
e.common.anno_scales = vec![half];
|
||||
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
|
||||
let landing = m.landing;
|
||||
let t = m.text.as_mut().unwrap();
|
||||
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
|
||||
t.width = 4.0;
|
||||
t.height = 2.0;
|
||||
t.attach = 1;
|
||||
t.rotation = 0.0;
|
||||
if let Some(x) = block_at {
|
||||
m.block = Some(cadcraft_doc::Insert {
|
||||
block: "BLK".into(),
|
||||
insert: landing + Vec3::new(x, 0.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
|
||||
m.landing.xy()
|
||||
};
|
||||
let cursor = landing + probe;
|
||||
// Blank frames (10 x 2.5, top-left at the insert) cover the cursor; their inserts do not.
|
||||
let d = s.doc_mut().unwrap();
|
||||
for _ in 0..2100 {
|
||||
let t = cadcraft_doc::MText {
|
||||
insert: Vec3::new(cursor.x - 5.0, cursor.y + 1.0, 0.0),
|
||||
height: 2.5,
|
||||
width: 10.0,
|
||||
attach: 1,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: " ".into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
}
|
||||
osnap(d, &Space::Model, cursor, 0.5, mode::INS, None, false).map(|h| h.point - landing)
|
||||
}
|
||||
|
||||
/// An annotative blank multileader keeps its INS snap (the stored, unscaled insertion point)
|
||||
/// among thousands of blank frames, and so does its block content.
|
||||
#[test]
|
||||
fn annotative_blank_mleader_keeps_its_ins_snaps_among_blank_frames() {
|
||||
assert_eq!(crowded_blank_mleader_ins(None, Vec2::new(6.1, -0.1)), Some(Vec2::new(6.0, 0.0)), "text");
|
||||
assert_eq!(crowded_blank_mleader_ins(Some(30.0), Vec2::new(30.1, -0.1)), Some(Vec2::new(30.0, 0.0)), "block");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intersection() {
|
||||
let d = drawing();
|
||||
|
||||
@@ -53,7 +53,8 @@ impl ChunkIx {
|
||||
if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) {
|
||||
infinite.push(u32::try_from(i).unwrap_or(u32::MAX));
|
||||
}
|
||||
entity_bounds_cached(d, e, 0, &mut cache)
|
||||
let b = entity_bounds_cached(d, e, 0, &mut cache);
|
||||
crate::select::pick_bounds(d, e, b)
|
||||
})
|
||||
.collect();
|
||||
let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@@ -89,8 +89,11 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53,
|
||||
/// On/off session settings: name, read, write.
|
||||
type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool));
|
||||
const SETTINGS: &[Toggle] = &[
|
||||
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
|
||||
// ATTDIA 1 (the default): INSERT typed or from a menu asks for attribute values in the Edit
|
||||
// Attributes dialog; 0: at the command line. ATTREQ 0: INSERT gives every attribute its default.
|
||||
("ATTDIA", |s| s.attdia, |s, v| s.attdia = v),
|
||||
("ATTREQ", |s| s.attreq, |s, v| s.attreq = v),
|
||||
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
|
||||
("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v),
|
||||
];
|
||||
|
||||
|
||||
@@ -746,6 +746,15 @@ fn script_runs_commands() {
|
||||
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_allow_one_leading_utf8_bom() {
|
||||
for text in ["\u{feff}LINE 0,0 10,10\n\n", "\u{feff}; first comment\r\nLINE 0,0 10,10\r\n\r\n"] {
|
||||
let mut s = Session::new();
|
||||
s.script(text).unwrap();
|
||||
assert_eq!(kinds(&s), vec!["Line"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_splits_line_at_keyword_prompt() {
|
||||
let mut s = Session::new();
|
||||
@@ -1552,6 +1561,50 @@ fn setvar_rejects_non_finite_text_for_real_variables() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_is_drawn_but_no_selection_takes_it_in() {
|
||||
// A proxy's graphics are drawn and measured, but saving writes its record unchanged: an edit
|
||||
// could not hold. So a window round a line and a proxy, ALL, SELECTALL and a pick on the
|
||||
// proxy's graphics leave the proxy out, and MOVE moves the line alone.
|
||||
use cadcraft_doc::{Common, Entity, Handle, Line, Space, Unknown, entity_bounds};
|
||||
use cadcraft_geom::Vec3;
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let line = s.doc().unwrap().model.last().unwrap().handle;
|
||||
let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }));
|
||||
let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] };
|
||||
let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap();
|
||||
let bounds = |s: &Session| entity_bounds(s.doc().unwrap(), s.doc().unwrap().entity(proxy).unwrap(), 0);
|
||||
let before = bounds(&s);
|
||||
assert!(!before.is_empty(), "the proxy measures as its graphics");
|
||||
|
||||
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
|
||||
assert_eq!(s.selection(), Vec::<Handle>::new(), "a pick on the proxy's graphics");
|
||||
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
|
||||
s.idle_click(Vec2::new(11.0, 6.0), false).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "a window round both");
|
||||
s.execute("selectall", &json!({})).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "SELECTALL");
|
||||
|
||||
s.execute("move", &json!({"delta": [0, 20]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved");
|
||||
assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it");
|
||||
|
||||
// Handles named outright leave the proxy out too.
|
||||
s.execute("select", &json!({"handles": [proxy.hex(), line.hex()]})).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "SELECT by handles");
|
||||
|
||||
// Last passes over the proxy drawn last: it takes the line.
|
||||
s.set_selection(Vec::new());
|
||||
s.start("erase").unwrap();
|
||||
s.input(Input::Text("L".into())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.entity(line).is_none(), "Last took the line");
|
||||
assert!(d.entity(proxy).is_some(), "the proxy is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_tools_keeps_compatible_command_ids() {
|
||||
assert_eq!(crate::cmd::resolve_alias("-blockreplace"), "blockreplace");
|
||||
|
||||
@@ -323,5 +323,26 @@ fn clipboard_travels_as_text() {
|
||||
t.execute("pasteorig", &json!({})).unwrap();
|
||||
assert_eq!(t.doc().unwrap().model.len(), 2);
|
||||
assert!(t.doc().unwrap().block("DOOR").is_some() && t.doc().unwrap().layer("HINGE").is_some());
|
||||
// A paste asked for from a menu or by name reads the system clipboard first, so text from
|
||||
// another window replaces a copy made here earlier; text that is not a DXF drawing does not.
|
||||
let mut u = Session::empty();
|
||||
u.open_drawing(drawing_b(), "B", None);
|
||||
assert!(u.execute("pasteclip", &json!({})).is_err(), "nothing to paste yet");
|
||||
assert!(clipboard::load_system_text(&mut u, &text));
|
||||
u.execute("pasteclip", &json!({})).unwrap();
|
||||
assert_eq!(u.doc().unwrap().model.len(), 2, "the system clipboard's objects were pasted");
|
||||
|
||||
let mut v = Session::empty();
|
||||
v.open_drawing(drawing_b(), "B", None);
|
||||
let local = line(v.doc_mut().unwrap(), "0", (1.0, 1.0), (2.0, 2.0));
|
||||
let local_handle = local.handle.hex();
|
||||
v.doc_mut().unwrap().model.push(local);
|
||||
v.execute("copyclip", &json!({ "handles": [local_handle] })).unwrap();
|
||||
assert_eq!(v.clipboard.len(), 1);
|
||||
assert!(!clipboard::load_system_text(&mut v, "just some words"), "not a drawing");
|
||||
assert_eq!(v.clipboard.len(), 1, "the copy made here stays");
|
||||
assert!(clipboard::load_system_text(&mut v, &text));
|
||||
assert_eq!(v.clipboard.len(), 2, "newer text from another window replaces it");
|
||||
assert!(v.clipboard_source.as_ref().is_some_and(|c| c.uid.is_none()));
|
||||
let _ = a;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! DIMASSOC 1 creates dimension objects without coupling them to source geometry; 2 couples them.
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Read the single entity handle returned by a dimension command.
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Clone the asserted dimension so later edits can be compared with its previous state.
|
||||
fn dimension(s: &Session, h: Handle) -> Dimension {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Dimension(d) => d.clone(),
|
||||
other => panic!("expected dimension, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a synthetic source line and return its first entity handle.
|
||||
fn line(s: &mut Session, a: [i32; 2], b: [i32; 2]) -> Handle {
|
||||
let v = s.execute("line", &json!({"points": [a, b]})).unwrap();
|
||||
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Set the drawing-wide associativity mode before creating the test dimensions.
|
||||
fn mode(s: &mut Session, n: i32) {
|
||||
s.execute("setvar", &json!({"name": "DIMASSOC", "value": n})).unwrap();
|
||||
}
|
||||
|
||||
/// Typed and JSON dimensions retain their mode through DXF, source edits, undo and redo.
|
||||
#[test]
|
||||
fn linear_dimensions_respect_the_mode_through_edits_and_dxf() {
|
||||
for n in [1, 2] {
|
||||
for typed in [false, true] {
|
||||
let mut s = Session::new();
|
||||
mode(&mut s, n);
|
||||
let source = line(&mut s, [0, 0], [10, 0]);
|
||||
let d = if typed {
|
||||
s.cmdline("dimlinear 0,0 10,0 5,4").unwrap();
|
||||
s.last_dim.unwrap()
|
||||
} else {
|
||||
handle(&s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap())
|
||||
};
|
||||
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, typed{typed}");
|
||||
let saved = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let has_link = saved.lines().any(|l| l.trim() == "DIMASSOC");
|
||||
assert_eq!(has_link, n == 2, "mode{n}: only associative dimensions save a DIMASSOC object");
|
||||
let mut reopened = Session::new();
|
||||
reopened.open_drawing(cadcraft_io::read_dxf(saved.as_bytes()).unwrap(), "roundtrip.dxf", None);
|
||||
for session in [&mut s, &mut reopened] {
|
||||
session.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
|
||||
let edited = dimension(session, d);
|
||||
assert_eq!(edited.p14.x, if n == 2 { 15.0 } else { 10.0 });
|
||||
assert_eq!(cadcraft_engine::render::dimension_in(session.doc().unwrap(), &edited).measurement, if n == 2 { 15.0 } else { 10.0 });
|
||||
session.undo().unwrap();
|
||||
assert_eq!(dimension(session, d).p14.x, 10.0);
|
||||
session.redo().unwrap();
|
||||
assert_eq!(dimension(session, d).p14.x, edited.p14.x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Continue, Baseline and Quick Dimension attach source links only in mode 2.
|
||||
#[test]
|
||||
fn indexed_chains_and_qdim_respect_the_mode() {
|
||||
for n in [1, 2] {
|
||||
for cmd in ["dimcontinue", "dimbaseline", "qdim"] {
|
||||
let mut s = Session::new();
|
||||
mode(&mut s, n);
|
||||
let source = line(&mut s, [0, 0], [10, 0]);
|
||||
s.execute("point", &json!({"at": [20, 0]})).unwrap();
|
||||
s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap();
|
||||
let params = if cmd == "qdim" { json!({"handles": [source.hex()], "at": [5, 6]}) } else { json!({"points": [[20, 0]]}) };
|
||||
let out = s.execute(cmd, ¶ms).unwrap();
|
||||
let hs = out["handles"].as_array().unwrap();
|
||||
assert!(!hs.is_empty());
|
||||
for h in hs {
|
||||
let d = dimension(&s, Handle::parse_hex(h.as_str().unwrap()).unwrap());
|
||||
assert_eq!(d.assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, {cmd}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Even explicitly selected angular source lines produce associations only in mode 2.
|
||||
#[test]
|
||||
fn explicit_angular_links_respect_the_mode() {
|
||||
for n in [1, 2] {
|
||||
let mut s = Session::new();
|
||||
mode(&mut s, n);
|
||||
let a = line(&mut s, [0, 0], [10, 0]);
|
||||
let b = line(&mut s, [0, 0], [0, 10]);
|
||||
let d = handle(&s.execute("dimangular", &json!({"lines": [a.hex(), b.hex()], "at": [4, 4]})).unwrap());
|
||||
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 4 } else { 0 });
|
||||
}
|
||||
}
|
||||
|
||||
/// Changing the creation mode preserves old links and does not disable explicit reassociation.
|
||||
#[test]
|
||||
fn mode_change_keeps_existing_links_and_allows_explicit_reassociation() {
|
||||
let mut s = Session::new();
|
||||
let source = line(&mut s, [0, 0], [10, 0]);
|
||||
let params = json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]});
|
||||
let existing = handle(&s.execute("dimlinear", ¶ms).unwrap());
|
||||
mode(&mut s, 1);
|
||||
let new = handle(&s.execute("dimlinear", ¶ms).unwrap());
|
||||
assert_eq!(dimension(&s, existing).assoc.len(), 2);
|
||||
assert!(dimension(&s, new).assoc.is_empty());
|
||||
s.execute("dimreassociate", &json!({"handles": [new.hex()]})).unwrap();
|
||||
assert_eq!(dimension(&s, new).assoc.len(), 2);
|
||||
s.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
|
||||
assert_eq!(dimension(&s, existing).p14.x, 15.0);
|
||||
assert_eq!(dimension(&s, new).p14.x, 15.0);
|
||||
}
|
||||
@@ -133,6 +133,13 @@ fn bad_input_is_refused_and_changes_nothing() {
|
||||
json!({ "path": "a.png", "data": data, "width": -3 }),
|
||||
json!({ "path": "a.png", "data": data, "width": "wide" }),
|
||||
json!({ "path": "a.png", "data": data, "width": 1e-320 }),
|
||||
// A value of the wrong type is refused, not taken as omitted.
|
||||
json!({ "path": "a.png", "data": data, "scale": "big" }),
|
||||
json!({ "path": "a.png", "data": data, "width": 2, "scale": "big" }),
|
||||
json!({ "path": "a.png", "data": data, "rotation": "right" }),
|
||||
json!({ "path": "a.png", "data": data, "at": "nowhere" }),
|
||||
json!({ "path": "a.png", "data": data, "at": [1] }),
|
||||
json!({ "path": "a.png", "data": data, "name": 7 }),
|
||||
json!({ "path": "x".repeat(5000), "data": data }),
|
||||
] {
|
||||
assert!(s.execute("imageattach", &p).is_err(), "{p}");
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text};
|
||||
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text};
|
||||
use cadcraft_engine::geom::Vec3;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -45,3 +45,66 @@ fn references_take_lock_position_from_the_definition() {
|
||||
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
|
||||
assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true });
|
||||
}
|
||||
|
||||
/// A definition at `x` with `modes`, invisible or not, multiline or not.
|
||||
fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib {
|
||||
let text = Text {
|
||||
insert: Vec3::new(x, 0.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.0,
|
||||
value: tag.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
};
|
||||
let multiline = multiline.then(|| {
|
||||
let mtext = MText {
|
||||
insert: Vec3::new(x, 0.0, 0.0),
|
||||
height: 2.0,
|
||||
width: 0.0,
|
||||
attach: 7,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: format!("{tag}\\PTWO"),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
|
||||
});
|
||||
Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() {
|
||||
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
|
||||
let locked = AttribModes { lock_position: true, ..AttribModes::default() };
|
||||
let mut b = Block::new("TAG");
|
||||
for a in [
|
||||
definition("FREE", 0.0, AttribModes::default(), false, false),
|
||||
definition("LOCKED", 10.0, locked, false, false),
|
||||
definition("HIDDEN", 20.0, AttribModes::default(), true, false),
|
||||
definition("NOTE", 30.0, AttribModes::default(), false, true),
|
||||
] {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("TAG".into(), Arc::new(b));
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "tags", None);
|
||||
let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap();
|
||||
let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
// The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute.
|
||||
let g = s.grips_of(h).unwrap();
|
||||
assert_eq!(g.iter().map(|p| p.x).collect::<Vec<_>>(), [100.0, 100.0, 130.0]);
|
||||
// NOTE's grip (index 2) dragged up 5: its multiline text moves with it.
|
||||
s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap();
|
||||
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
|
||||
let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap();
|
||||
assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0));
|
||||
let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap();
|
||||
assert_eq!(free.text.insert.y, 0.0, "the others stay");
|
||||
}
|
||||
@@ -36,13 +36,16 @@ fn baseline_spacing_follows_overrides_and_dimscale() {
|
||||
assert!(near(dli, 1.0), "SETVAR DIMDLI sets the spacing: {dli}");
|
||||
let zero = baseline_spacing(&[("dimstyle", json!({"name": "Standard", "DIMSCALE": 0}))]);
|
||||
assert!(near(zero, 0.38), "DIMSCALE 0 in model space is scale 1, not a collapsed spacing: {zero}");
|
||||
}
|
||||
|
||||
// DIMSPACE's default spacing (twice DIMDLI) uses the same scale.
|
||||
#[test]
|
||||
fn dimspace_auto_uses_unit_scale_for_zero_dimscale_in_model_space() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimstyle", &json!({"name": "Standard", "DIMSCALE": 0})).unwrap();
|
||||
let text_height = 0.25;
|
||||
s.execute("dimstyle", &json!({"name": "Standard", "DIMTXT": text_height, "DIMSCALE": 0})).unwrap();
|
||||
let a = s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [30, 0], "at": [15, 5]})).unwrap();
|
||||
let b = s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [50, 0], "at": [25, 6]})).unwrap();
|
||||
s.execute("dimspace", &json!({"base": a["handle"], "handles": [b["handle"]]})).unwrap();
|
||||
let gap = dim_line_y(&s, &b["handle"]) - dim_line_y(&s, &a["handle"]);
|
||||
assert!(near(gap, 0.76), "{gap}");
|
||||
assert!((gap - 2.0 * text_height).abs() < 1e-9, "{gap}");
|
||||
}
|
||||
@@ -145,3 +145,56 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() {
|
||||
let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff));
|
||||
assert!(preview[n..].iter().all(|e| e.common.color == blue));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grip_with_a_value_list_marks_its_stops_while_dragged() {
|
||||
let (mut s, h) = session();
|
||||
// Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it.
|
||||
let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End);
|
||||
let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect();
|
||||
assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
|
||||
assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12));
|
||||
// A grip that isn't on a list or increments has none; nor a list grip.
|
||||
assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty());
|
||||
|
||||
// The preview marks each stop with a tick across the travel, a few pixels long.
|
||||
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
|
||||
let half = 6.0 * s.pixel_size();
|
||||
let ticks: Vec<(f64, f64)> = s
|
||||
.preview(Vec2::new(133.0, 0.0))
|
||||
.into_iter()
|
||||
.filter_map(|e| match e.kind {
|
||||
cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => {
|
||||
Some((l.a.x, (l.a.y + l.b.y) / 2.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
|
||||
}
|
||||
|
||||
/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at
|
||||
/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does;
|
||||
/// away from objects it only moves.
|
||||
#[test]
|
||||
fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
|
||||
let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n");
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "params", None);
|
||||
let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap();
|
||||
assert_eq!(g[0]["shape"], "alignment");
|
||||
// A point on the line, a little below it.
|
||||
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c];
|
||||
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap();
|
||||
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
|
||||
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees());
|
||||
assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert);
|
||||
// Far from anything: it only moves.
|
||||
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap();
|
||||
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
|
||||
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
|
||||
}
|
||||
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user