diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 000000000..a1c1f31e8 --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -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----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 000000000..0456c8bfd --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -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" + } + } + } +} diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 000000000..61bb8f2e6 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -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. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 000000000..48e2c8799 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -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"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 1771a35fe..21c844441 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 056365ca5..cb15815b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/.gitignore b/.gitignore index 0c90e0b79..0f5b7e2f0 100644 --- a/.gitignore +++ b/.gitignore @@ -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__/ diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index cf177e6bd..576c3c121 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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 ``, 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 | diff --git a/Cargo.lock b/Cargo.lock index 5ec7f622f..a67e4bdeb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index f7182330a..3c981421f 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -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 { + 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"); diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index 46283753e..02f2a7341 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -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); } diff --git a/apps/cadcraft-cli/src/roundtrip.rs b/apps/cadcraft-cli/src/roundtrip.rs index dba9c8d04..71c5deec3 100644 --- a/apps/cadcraft-cli/src/roundtrip.rs +++ b/apps/cadcraft-cli/src/roundtrip.rs @@ -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 = f .routes diff --git a/apps/cadcraft-cli/src/run.rs b/apps/cadcraft-cli/src/run.rs index 56b4626e2..642cab033 100644 --- a/apps/cadcraft-cli/src/run.rs +++ b/apps/cadcraft-cli/src/run.rs @@ -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(()) diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index 59762d283..bbe4bc2fd 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -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] diff --git a/apps/cadcraft-cli/tests/it/usage.rs b/apps/cadcraft-cli/tests/it/usage.rs index bf3d6797d..6cb4ab831 100644 --- a/apps/cadcraft-cli/tests/it/usage.rs +++ b/apps/cadcraft-cli/tests/it/usage.rs @@ -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 = 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, 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"))], + ); +} diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 1e5594c73..03c041a93 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -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 "); return; diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index 55aec2547..970cb9081 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -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"] } diff --git a/apps/cadcraft/build.rs b/apps/cadcraft/build.rs index 1349ebe36..4a6d27017 100644 --- a/apps/cadcraft/build.rs +++ b/apps/cadcraft/build.rs @@ -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}"); diff --git a/apps/cadcraft/src/apple_events.rs b/apps/cadcraft/src/apple_events.rs new file mode 100644 index 000000000..7a9df457e --- /dev/null +++ b/apps/cadcraft/src/apple_events.rs @@ -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), + 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) -> Vec { + let mut out: Vec = 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, 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()); + } +} diff --git a/apps/cadcraft/src/build_channel.rs b/apps/cadcraft/src/build_channel.rs new file mode 100644 index 000000000..19f4330b3 --- /dev/null +++ b/apps/cadcraft/src/build_channel.rs @@ -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)); + } + } +} diff --git a/apps/cadcraft/src/build_flavor.rs b/apps/cadcraft/src/build_flavor.rs new file mode 100644 index 000000000..b63ede7c5 --- /dev/null +++ b/apps/cadcraft/src/build_flavor.rs @@ -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(&[])); + } +} diff --git a/apps/cadcraft/src/env.rs b/apps/cadcraft/src/env.rs index 24b69bcc8..6af615a4a 100644 --- a/apps/cadcraft/src/env.rs +++ b/apps/cadcraft/src/env.rs @@ -71,6 +71,10 @@ impl Env { fn from_vars_and_exe(var: impl Fn(&str) -> Option, 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) -> 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())); diff --git a/apps/cadcraft/src/launch_profile.rs b/apps/cadcraft/src/launch_profile.rs new file mode 100644 index 000000000..09f4e40c1 --- /dev/null +++ b/apps/cadcraft/src/launch_profile.rs @@ -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, +} + +static PROFILE: OnceLock = 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) -> Result { + 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) -> Result { + 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, exe: Option<&Path>) -> Result { + 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 { + 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 { + 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()); + } +} diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 2206161ed..9e812536c 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -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, + /// 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 { 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 `. fn version_string() -> String { format!("cadcraft {}", cadcraft_engine::build_version()) } +/// The Nightly identity line every nightly script checks: ` (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> { + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --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::>()) { + 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 `/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 `/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 ` (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] diff --git a/apps/cadcraft/src/native_menu.rs b/apps/cadcraft/src/native_menu.rs index 8649ed8e4..50aa49535 100644 --- a/apps/cadcraft/src/native_menu.rs +++ b/apps/cadcraft/src/native_menu.rs @@ -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); } } diff --git a/apps/cadcraft/src/nightly_session.rs b/apps/cadcraft/src/nightly_session.rs new file mode 100644 index 000000000..cb889ef04 --- /dev/null +++ b/apps/cadcraft/src/nightly_session.rs @@ -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, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + 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>>; + +/// 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, 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> { + 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::>(); + 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(); + } + } +} diff --git a/apps/cadcraft/src/portable.rs b/apps/cadcraft/src/portable.rs index 8b1ed0fba..d3d915384 100644 --- a/apps/cadcraft/src/portable.rs +++ b/apps/cadcraft/src/portable.rs @@ -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> { - 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 { + 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> { + if portable_marker(exe_dir).is_none() { + return Ok(None); + } + let data = exe_dir.join(PORTABLE_DATA_DIR); + probe(&data)?; Ok(Some(data)) } diff --git a/apps/cadcraft/src/process_identity.rs b/apps/cadcraft/src/process_identity.rs new file mode 100644 index 000000000..9d2e1c179 --- /dev/null +++ b/apps/cadcraft/src/process_identity.rs @@ -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> = 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()); + } +} diff --git a/apps/cadcraft/src/profile_root.rs b/apps/cadcraft/src/profile_root.rs new file mode 100644 index 000000000..45a5acb2e --- /dev/null +++ b/apps/cadcraft/src/profile_root.rs @@ -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 { + 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 { + 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, key: &str) -> Result { + 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, key: &str, fallback: &str) -> Result { + 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 { + 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::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + 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, exe: &Path) -> Result, 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::, _>>()?; + // 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::, _>>()?; + 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, label: &str) -> Result { + 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, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + 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`], `/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, + 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 { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + 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); + } +} diff --git a/apps/cadcraft/src/single_instance.rs b/apps/cadcraft/src/single_instance.rs index fef17ef53..9ab46229a 100644 --- a/apps/cadcraft/src/single_instance.rs +++ b/apps/cadcraft/src/single_instance.rs @@ -100,25 +100,30 @@ pub fn absolute(paths: &[PathBuf]) -> Option> { /// 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 `\single-instance` for a Nightly launch. #[cfg(windows)] -fn socket_path() -> Option { +fn socket_path(profile: Option<&std::path::Path>) -> Option { 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)) } diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md new file mode 100644 index 000000000..7ab893251 --- /dev/null +++ b/assets/app-icon/README.md @@ -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//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. diff --git a/assets/app-icon/cadcraft-nightly-1024.png b/assets/app-icon/cadcraft-nightly-1024.png new file mode 100644 index 000000000..08a3994f3 Binary files /dev/null and b/assets/app-icon/cadcraft-nightly-1024.png differ diff --git a/assets/app-icon/cadcraft-nightly.icns b/assets/app-icon/cadcraft-nightly.icns new file mode 100644 index 000000000..1098ee974 Binary files /dev/null and b/assets/app-icon/cadcraft-nightly.icns differ diff --git a/assets/app-icon/cadcraft-nightly.ico b/assets/app-icon/cadcraft-nightly.ico new file mode 100644 index 000000000..98a0be421 Binary files /dev/null and b/assets/app-icon/cadcraft-nightly.ico differ diff --git a/assets/app-icon/cadcraft-nightly.png b/assets/app-icon/cadcraft-nightly.png new file mode 100644 index 000000000..15fc5e4be Binary files /dev/null and b/assets/app-icon/cadcraft-nightly.png differ diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 000000000..56e92ed81 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -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." +} diff --git a/contributors/people.toml b/contributors/people.toml index d63a1ea02..f38661d01 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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 diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 409d403dd..5d0a1d456 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -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, - rows: Vec>, - }, + Lookup { columns: Vec, rows: Vec> }, /// 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, + #[serde(serialize_with = "hex_vertices")] + vertices: Vec<(Handle, Vec)>, + #[serde(serialize_with = "hexes")] + rotate_only: Vec, 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 { 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 { 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 = (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::().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::().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}"); } } diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ded8271c5..239a27acb 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -8,9 +8,9 @@ //! `AcDbBlockRepresentation` data holds its values (created when it had none) and its history //! says what was done to it (AutoCAD replays the history when the dynamic block is redefined). //! -//! What can change so far: a visibility state, a lookup value, a distance and a position, with -//! the stretch and move actions they drive and the lookups that follow. The other parameters' -//! actions come later. +//! What can change: a visibility state, a lookup value, a distance (linear, polar or XY), an angle, +//! a position and a flip state, with the stretch, move, rotate, flip, scale and array actions they +//! drive and the lookups that follow. use std::collections::{BTreeMap, HashMap, HashSet}; @@ -18,7 +18,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3}; use super::{ActionKind, DynamicBlock, ParameterKind, Value, dynamic_block, reference}; use crate::foreign::{ForeignExtra, ForeignObject}; -use crate::{Block, Drawing, Entity, EntityKind, Handle, RawTag}; +use crate::{Block, Drawing, Entity, EntityKind, HAlign, Handle, RawTag, Text, VAlign}; /// Xdata application naming a copied object's object in the dynamic block (its element tag). const ETAG: &str = "AcDbBlockRepETag"; @@ -100,6 +100,72 @@ enum Val { Point(Vec3), /// A two-point parameter's base and end points. Points(Vec3, Vec3), + /// A flip parameter's reflection line (base, end) and whether it is flipped. + Flip(Vec3, Vec3, bool), + /// A flip grip's state: its value record's last group 70. + State(bool), +} + +/// A rotation parameter's angle (radians, 0 to 2π): its end's direction from its base, from the +/// direction `home` the dynamic block has (base to end). +fn rotation_angle(b: Vec3, e: Vec3, home: (Vec3, Vec3)) -> f64 { + let (now, zero) = ((e - b).xy(), (home.1 - home.0).xy()); + (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU) +} + +/// The end point that gives a rotation parameter with base `b` and end `e` the angle `a` from the +/// direction `home` the dynamic block has. +fn rotation_end(b: Vec3, e: Vec3, home: (Vec3, Vec3), a: f64) -> Vec3 { + let r = (e - b).len(); + let zero = (home.1 - home.0).xy(); + let dir = Vec2::new(zero.y.atan2(zero.x).cos(), zero.y.atan2(zero.x).sin()).rotate(a); + b + (dir * r).to3(0.0) +} + +/// Text `t` carried by `m`, kept readable as AutoCAD keeps it (MIRRTEXT 0). A transform that +/// mirrors keeps the text's mirrored footprint: the text reads in whichever mirrored direction is +/// nearer its own, and a footprint reversed along the text swaps left and right justification +/// (AutoCAD moves the start back by the text's width instead, which draws the same), one reversed +/// across it swaps top and bottom. +fn carry_text(t: &mut Text, m: &Mat3) { + let u = Vec2::new(t.rotation.cos(), t.rotation.sin()); + let mut k = EntityKind::Text(t.clone()); + k.transform(m); + let EntityKind::Text(mut after) = k else { return }; + let o = m.apply(Vec2::ZERO); + let (ex, ey, mu) = (m.apply(Vec2::new(1.0, 0.0)) - o, m.apply(Vec2::new(0.0, 1.0)) - o, m.apply(u) - o); + if ex.x * ey.y - ex.y * ey.x < 0.0 && mu.len() > 1e-12 { + // The point the text is placed by, before its justification changes. + let at = after.justify_point(); + if mu.dot(u) >= 0.0 { + after.rotation = cadcraft_geom::norm_angle(mu.angle()); + after.valign = match after.valign { + VAlign::Top => VAlign::Bottom, + VAlign::Bottom | VAlign::Baseline => VAlign::Top, + v => v, + }; + } else { + after.rotation = cadcraft_geom::norm_angle((mu * -1.0).angle()); + match after.halign { + HAlign::Left => after.halign = HAlign::Right, + HAlign::Right => after.halign = HAlign::Left, + // Placed by both points: they swap ends. + HAlign::Aligned | HAlign::Fit => { + if let Some(a) = after.align_pt { + after.align_pt = Some(after.insert); + after.insert = a; + } + } + _ => {} + } + } + if !matches!(after.halign, HAlign::Aligned | HAlign::Fit) { + let at = at.to3(after.insert.z); + after.insert = at; + after.align_pt = (!matches!((after.halign, after.valign), (HAlign::Left, VAlign::Baseline))).then_some(at); + } + } + *t = after; } /// A parameter's current value on the reference: the value it was given, else the block's own. @@ -110,15 +176,18 @@ fn current(m: &DynamicBlock, values: &BTreeMap, node: i32) -> Option (_, Some(Value::Text { value })) => Val::Text(value.clone()), (_, Some(Value::Point { at })) => Val::Point(*at), (_, Some(Value::Points { base, end })) => Val::Points(*base, *end), + (_, Some(Value::Flip { base, end, flipped })) => Val::Flip(*base, *end, *flipped), + (ParameterKind::Flip { base, end, .. }, None) => Val::Flip(*base, *end, false), (ParameterKind::Visibility { states, .. }, None) => Val::Text(states.first().map(|s| s.name.clone()).unwrap_or_default()), (ParameterKind::Point { at, .. }, None) => Val::Point(*at), + // The block has it at its base point. + (ParameterKind::BasePoint { .. }, None) => Val::Point(m.base), ( ParameterKind::Linear { base, end, .. } - | ParameterKind::Polar { base, end } - | ParameterKind::Xy { base, end } - | ParameterKind::Rotation { base, end } - | ParameterKind::Alignment { base, end } - | ParameterKind::Flip { base, end }, + | ParameterKind::Polar { base, end, .. } + | ParameterKind::Xy { base, end, .. } + | ParameterKind::Rotation { base, end, .. } + | ParameterKind::Alignment { base, end, .. }, None, ) => Val::Points(*base, *end), _ => return None, @@ -146,11 +215,10 @@ fn allowed(set: &super::ValueSet, v: f64) -> f64 { } /// A linear parameter's points for distance `dist`: the end point moves along the parameter, or -/// both points move apart from the midpoint. -fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool) -> (Vec3, Vec3) { - let dir = end - base; - let len = dir.len(); - let u = if len > 1e-12 { dir * (1.0 / len) } else { Vec3::new(1.0, 0.0, 0.0) }; +/// both points move apart from the midpoint. At a distance of 0 the parameter goes the way `home` +/// (its base to its end in the dynamic block) does. +fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool, home: Vec3) -> (Vec3, Vec3) { + let u = unit_along(end - base, home); if from_midpoint { let mid = (base + end) * 0.5; (mid - u * (dist / 2.0), mid + u * (dist / 2.0)) @@ -159,6 +227,17 @@ fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool) -> (Vec3 } } +/// `dir` as a unit vector, else `home`'s (a distance of 0 has no direction of its own), else X. +fn unit_along(dir: Vec3, home: Vec3) -> Vec3 { + if dir.len() > 1e-12 { + dir * (1.0 / dir.len()) + } else if home.len() > 1e-12 { + home * (1.0 / home.len()) + } else { + Vec3::new(1.0, 0.0, 0.0) + } +} + /// The changes one property change makes, before actions run: parameter values by graph id. #[derive(Default)] struct Plan { @@ -166,26 +245,49 @@ struct Plan { } impl Plan { - /// Set the value a lookup table cell gives property `property` of parameter `node`. + /// Set the value a lookup table cell gives property `property` of parameter `node` (block + /// units; angles in radians, as AutoCAD writes them). fn cell(&mut self, m: &DynamicBlock, values: &BTreeMap, node: i32, property: &str, cell: &str) -> Result<(), String> { let p = m.parameters.iter().find(|p| p.node == node).ok_or("A lookup table refers to a missing parameter.")?; - match (&p.kind, property.to_ascii_lowercase().as_str()) { - (_, "lookupstring") | (ParameterKind::Visibility { .. }, "visibilitystate") => { - self.set.insert(node, Val::Text(cell.to_string())); - } - (ParameterKind::Linear { from_midpoint, .. }, "updateddistance" | "distance") => { - let dist = cell - .trim() - .parse::() - .ok() - .filter(|v| v.is_finite()) - .ok_or_else(|| format!("A lookup table gives \"{cell}\" for a distance."))?; - let Some(Val::Points(b, e)) = self.set.get(&node).cloned().or_else(|| current(m, values, node)) else { return Ok(()) }; - let (b2, e2) = linear_points(b, e, dist, *from_midpoint); - self.set.insert(node, Val::Points(b2, e2)); - } - (_, other) => return Err(format!("A lookup table sets {other}, which CADCraft can't change yet.")), + let col = column(&p.kind, property).ok_or_else(|| format!("A lookup table sets {property}, which CADCraft can't change yet."))?; + if col == Column::Text { + self.set.insert(node, Val::Text(cell.to_string())); + return Ok(()); } + let v = + cell.trim().parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("A lookup table gives \"{cell}\" for {property}."))?; + let Some(cur) = self.set.get(&node).cloned().or_else(|| current(m, values, node)) else { return Ok(()) }; + // A polar parameter's direction (along X when it has none). + let along = |b: Vec3, e: Vec3| { + let d = (e - b).xy(); + if d.len() > 1e-12 { d * (1.0 / d.len()) } else { Vec2::new(1.0, 0.0) } + }; + let now = match (col, &p.kind, cur) { + (Column::Distance, ParameterKind::Linear { from_midpoint, base: hb, end: he, .. }, Val::Points(b, e)) => { + let (b2, e2) = linear_points(b, e, v, *from_midpoint, *he - *hb); + Val::Points(b2, e2) + } + (Column::Distance, ParameterKind::Polar { .. }, Val::Points(b, e)) => Val::Points(b, b + (along(b, e) * v).to3(0.0)), + (Column::Angle, ParameterKind::Rotation { base: hb, end: he, .. }, Val::Points(b, e)) => { + Val::Points(b, rotation_end(b, e, (*hb, *he), v)) + } + (Column::Angle, ParameterKind::Polar { .. }, Val::Points(b, e)) => { + Val::Points(b, b + (Vec2::new(v.cos(), v.sin()) * (e - b).xy().len()).to3(0.0)) + } + (Column::DistanceX, ParameterKind::Xy { .. }, Val::Points(b, e)) => Val::Points(b, Vec3::new(b.x + v, e.y, e.z)), + (Column::DistanceY, ParameterKind::Xy { .. }, Val::Points(b, e)) => Val::Points(b, Vec3::new(e.x, b.y + v, e.z)), + (Column::X, ParameterKind::Point { .. }, Val::Point(at)) => Val::Point(Vec3::new(m.base.x + v, at.y, at.z)), + (Column::Y, ParameterKind::Point { .. }, Val::Point(at)) => Val::Point(Vec3::new(at.x, m.base.y + v, at.z)), + // Its flip grip's record follows. + (Column::Flip, ParameterKind::Flip { .. }, Val::Flip(b, e, _)) => { + if let Some(g) = p.grips.first().filter(|g| **g != 0) { + self.set.insert(*g, Val::State(v != 0.0)); + } + Val::Flip(b, e, v != 0.0) + } + _ => return Ok(()), + }; + self.set.insert(node, now); Ok(()) } @@ -208,21 +310,17 @@ impl Plan { Ok(found) } - /// After input property `property` of parameter `node` changed: a lookup table with that input - /// whose inputs (with the new value) match a row gives its lookup value, and the lookup's - /// other tables then set their inputs for that value (as AutoCAD does). - fn chain(&mut self, m: &DynamicBlock, values: &BTreeMap, node: i32, property: &str) -> Result<(), String> { + /// After parameter `node` changed: a lookup table with it as an input whose inputs (with the + /// new values) match a row gives its lookup value, and the lookup's other tables then set + /// their inputs for that value (as AutoCAD does). + fn chain(&mut self, m: &DynamicBlock, values: &BTreeMap, node: i32) -> Result<(), String> { let read = |plan: &Plan, n: i32, prop: &str| -> Option { let v = plan.set.get(&n).cloned().or_else(|| current(m, values, n))?; - match (v, prop.to_ascii_lowercase().as_str()) { - (Val::Text(t), "visibilitystate" | "lookupstring") => Some(t), - (Val::Points(b, e), "updateddistance" | "distance") => Some(format!("{}", (e - b).len())), - _ => None, - } + column_text(m, n, prop, &v) }; for (i, a) in m.actions.iter().enumerate() { let ActionKind::Lookup { columns, rows } = &a.kind else { continue }; - if !columns.iter().any(|c| !c.lookup && c.node == node && c.property.eq_ignore_ascii_case(property)) { + if !columns.iter().any(|c| !c.lookup && c.node == node) { continue; } let Some(out) = columns.iter().position(|c| c.lookup) else { continue }; @@ -242,6 +340,68 @@ impl Plan { } } +/// What a lookup table column stands for: a text (visibility state, lookup value), a distance, an +/// angle (radians), an XY parameter's horizontal or vertical distance, a position's X or Y (from +/// the block's base point) or a flip state (0 or 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Column { + Text, + Distance, + Angle, + DistanceX, + DistanceY, + X, + Y, + Flip, +} + +/// The column a lookup table property (as AutoCAD names them) is for a parameter of `kind`, when +/// CADCraft can set and read it. +pub(super) fn column(kind: &ParameterKind, property: &str) -> Option { + Some(match (kind, property.to_ascii_lowercase().as_str()) { + (ParameterKind::Lookup { .. }, "lookupstring") | (ParameterKind::Visibility { .. }, "visibilitystate") => Column::Text, + (ParameterKind::Linear { .. } | ParameterKind::Polar { .. }, "updateddistance" | "distance") => Column::Distance, + (ParameterKind::Rotation { .. } | ParameterKind::Polar { .. }, "updatedangle") => Column::Angle, + (ParameterKind::Xy { .. }, "updateddistancex") => Column::DistanceX, + (ParameterKind::Xy { .. }, "updateddistancey") => Column::DistanceY, + (ParameterKind::Point { .. }, "updatedx") => Column::X, + (ParameterKind::Point { .. }, "updatedy") => Column::Y, + (ParameterKind::Flip { .. }, "updatedflip") => Column::Flip, + _ => return None, + }) +} + +/// Property `property` of parameter `node` with value `v`, as a lookup table cell writes it. +fn column_text(m: &DynamicBlock, node: i32, property: &str, v: &Val) -> Option { + let p = m.parameters.iter().find(|p| p.node == node)?; + // From 0 to 2π, a full turn being none. + let angle = |a: f64| { + let a = a.rem_euclid(std::f64::consts::TAU); + if std::f64::consts::TAU - a < 1e-9 { 0.0 } else { a } + }; + let out = match (column(&p.kind, property)?, &p.kind, v) { + (Column::Text, _, Val::Text(t)) => t.clone(), + (Column::Distance, _, Val::Points(b, e)) => (*e - *b).len().to_string(), + (Column::Angle, ParameterKind::Rotation { base: hb, end: he, .. }, Val::Points(b, e)) => { + angle(rotation_angle(*b, *e, (*hb, *he))).to_string() + } + (Column::Angle, _, Val::Points(b, e)) => angle((*e - *b).xy().angle()).to_string(), + (Column::DistanceX, _, Val::Points(b, e)) => (e.x - b.x).to_string(), + (Column::DistanceY, _, Val::Points(b, e)) => (e.y - b.y).to_string(), + (Column::X, _, Val::Point(at)) => (at.x - m.base.x).to_string(), + (Column::Y, _, Val::Point(at)) => (at.y - m.base.y).to_string(), + (Column::Flip, _, Val::Flip(_, _, f)) => i32::from(*f).to_string(), + _ => return None, + }; + Some(out) +} + +/// Property `property` of parameter `node` on a reference with values `values`, as a lookup table +/// cell writes it. +pub(super) fn property_text(m: &DynamicBlock, values: &BTreeMap, node: i32, property: &str) -> Option { + column_text(m, node, property, ¤t(m, values, node)?) +} + /// Whether table cell `cell` reads as `value` (numbers compare as numbers). fn same(cell: &str, value: &str) -> bool { match (cell.trim().parse::(), value.trim().parse::()) { @@ -273,17 +433,58 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> .parameters .iter() .find(|p| { - p.show_properties && p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(want) || (axis.is_some() && l.eq_ignore_ascii_case(label))) + p.show_properties && p.kind.labels().iter().any(|l| l.eq_ignore_ascii_case(want) || (axis.is_some() && l.eq_ignore_ascii_case(label))) }) .ok_or_else(|| format!("The reference has no property \"{name}\"."))?; + // Which of a two-property parameter's properties it is: a polar parameter's distance or + // angle, an XY parameter's horizontal or vertical distance. + let second = p.kind.labels().iter().position(|l| l.eq_ignore_ascii_case(want)) == Some(1); let mut plan = Plan::default(); match (&p.kind, axis) { + (ParameterKind::Polar { values, angle_values, label, angle_label, .. }, _) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; + let (len, a) = ((e - b).len(), (e - b).xy().angle()); + let (len, a) = if second { + // Typed as the drawing shows angles (from ANGBASE, clockwise when ANGDIR is 1). + let a = allowed(angle_values, super::reference::angle_from_shown(d, number(value)?.to_radians())); + if !a.is_finite() { + return Err(format!("\"{value}\" is not an angle for {angle_label}.")); + } + (len, a) + } else { + let dist = allowed(values, number(value)? / sx); + if !(dist > 0.0 && dist.is_finite()) { + return Err(format!("{label} must be more than 0.")); + } + (dist, a) + }; + plan.set.insert(p.node, Val::Points(b, b + Vec2::new(a.cos(), a.sin()).to3(0.0) * len)); + plan.chain(&m, &r.values, p.node)?; + } + (ParameterKind::Xy { x_values, y_values, x_label, y_label, .. }, _) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; + let (set, scale, label) = if second { (y_values, sy, y_label) } else { (x_values, sx, x_label) }; + let v = number(value)? / scale; + // AutoCAD refuses a distance below the minimum rather than taking the minimum. + if set.has_minimum() && v < set.minimum - 1e-9 { + return Err(format!("{label} must be at least {}.", set.minimum * scale)); + } + let v = allowed(set, v); + let e2 = if second { Vec3::new(e.x, b.y + v, e.z) } else { Vec3::new(b.x + v, e.y, e.z) }; + // A tiny reference scale can take a finite number past the range: such an end point + // would be saved but not read back as the parameter's points. + if !(v.is_finite() && e2.is_finite()) { + return Err(format!("\"{value}\" is too large for {label}.")); + } + plan.set.insert(p.node, Val::Points(b, e2)); + plan.chain(&m, &r.values, p.node)?; + } (ParameterKind::Visibility { states, label, .. }, _) => { let s = states.iter().find(|s| s.name.eq_ignore_ascii_case(value.trim())).ok_or_else(|| { format!("\"{value}\" is not a state of {label}: {}.", states.iter().map(|s| s.name.as_str()).collect::>().join(", ")) })?; plan.set.insert(p.node, Val::Text(s.name.clone())); - plan.chain(&m, &r.values, p.node, "VisibilityState")?; + plan.chain(&m, &r.values, p.node)?; } (ParameterKind::Lookup { label, .. }, _) => { plan.set.insert(p.node, Val::Text(value.trim().to_string())); @@ -291,25 +492,56 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> return Err(format!("\"{value}\" is not a value of {label}.")); } } - (ParameterKind::Linear { values, from_midpoint, .. }, None) => { + // AutoCAD takes a distance of 0 (a value list can offer it), not one below. + (ParameterKind::Linear { values, from_midpoint, base: hb, end: he, .. }, None) => { let typed = number(value)? / sx; - if typed <= 0.0 { - return Err(format!("{name} must be more than 0.")); + if typed < 0.0 { + return Err(format!("{name} can't be less than 0.")); } let dist = allowed(values, typed); - if dist <= 0.0 { - return Err(format!("{name} must be more than 0.")); + if !(dist >= 0.0 && dist.is_finite()) { + return Err(format!("{name} can't be less than 0.")); } let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; - let (b2, e2) = linear_points(b, e, dist, *from_midpoint); + let (b2, e2) = linear_points(b, e, dist, *from_midpoint, *he - *hb); plan.set.insert(p.node, Val::Points(b2, e2)); - plan.chain(&m, &r.values, p.node, "UpdatedDistance")?; + plan.chain(&m, &r.values, p.node)?; } (ParameterKind::Point { .. }, Some(is_x)) => { let Some(Val::Point(at)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no position.")) }; let v = number(value)?; let at = if is_x { Vec3::new(block_base.x + v / sx, at.y, at.z) } else { Vec3::new(at.x, block_base.y + v / sy, at.z) }; plan.set.insert(p.node, Val::Point(at)); + plan.chain(&m, &r.values, p.node)?; + } + // An angle in degrees, as Properties shows it, snapped to the parameter's values. + (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, None) => { + // Typed as the drawing shows angles (from ANGBASE, clockwise when ANGDIR is 1). + let typed = super::reference::angle_from_shown(d, number(value)?.to_radians()); + let a = allowed(values, typed); + if !a.is_finite() { + return Err(format!("\"{value}\" is not an angle for {label}.")); + } + let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; + plan.set.insert(p.node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); + plan.chain(&m, &r.values, p.node)?; + } + // A state by name (or 0 / 1); its flip grip's record follows. + (ParameterKind::Flip { states, label, .. }, None) => { + let v = value.trim(); + let flipped = if v.eq_ignore_ascii_case(&states[1]) || v == "1" { + true + } else if v.eq_ignore_ascii_case(&states[0]) || v == "0" { + false + } else { + return Err(format!("\"{value}\" is not a state of {label}: {}, {}.", states[0], states[1])); + }; + let Some(Val::Flip(b, e, _)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no reflection line.")) }; + plan.set.insert(p.node, Val::Flip(b, e, flipped)); + if let Some(g) = p.grips.first().filter(|g| **g != 0) { + plan.set.insert(*g, Val::State(flipped)); + } + plan.chain(&m, &r.values, p.node)?; } _ => return Err(format!("CADCraft can't change {name} yet.")), } @@ -332,15 +564,14 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); let q = ins.transform(base).inverse().ok_or("The reference has a zero scale.")?.apply(to); let p = m.parameters.iter().find(|p| p.node == node).ok_or("The reference has no such parameter.")?; + if matches!(p.kind, ParameterKind::Alignment { .. }) { + return align_grip(d, insert, node, to, None); + } let mut plan = Plan::default(); match (&p.kind, part) { - (ParameterKind::Linear { values, from_midpoint, label, .. }, GripPart::Base | GripPart::End) => { + (ParameterKind::Linear { values, from_midpoint, label, base: hb, end: he, .. }, GripPart::Base | GripPart::End) => { let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; - let len = (e - b).len(); - if len < 1e-12 { - return Err(format!("{label} has no direction.")); - } - let u = (e - b) * (1.0 / len); + let u = unit_along(e - b, *he - *hb); let q = Vec3::new(q.x, q.y, b.z); let raw = if *from_midpoint { 2.0 * (q - (b + e) * 0.5).dot(u).abs() @@ -354,22 +585,222 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa return Err(format!("{label} must be more than 0.")); } let (b2, e2) = match (from_midpoint, part) { - (true, _) => linear_points(b, e, dist, true), + (true, _) => linear_points(b, e, dist, true, u), (false, GripPart::Base) => (e - u * dist, e), (false, _) => (b, b + u * dist), }; plan.set.insert(node, Val::Points(b2, e2)); - plan.chain(&m, &r.values, node, "UpdatedDistance")?; } (ParameterKind::Point { label, .. }, GripPart::At) => { let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) }; plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z))); } + // The end grip goes where it is dragged (its distance snapped to the value set); the base + // grip moves the base, keeping the end. + (ParameterKind::Polar { values, angle_values, label, .. }, GripPart::Base | GripPart::End) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; + let q3 = Vec3::new(q.x, q.y, b.z); + let (b2, e2) = if part == GripPart::Base { + (q3, e) + } else { + let raw = (q3 - b).len(); + let dist = allowed(values, raw); + if !(raw > 1e-12 && dist > 0.0 && dist.is_finite()) { + return Err(format!("{label} must be more than 0.")); + } + // The angle snaps to its own value set too, as typing it does (in a full turn from + // the block's +X); without one, the end goes where it is dragged. + let a = allowed(angle_values, (q3 - b).xy().angle().rem_euclid(std::f64::consts::TAU)); + if !a.is_finite() { + return Err(format!("{label} has no direction there.")); + } + (b, b + Vec2::new(a.cos(), a.sin()).to3(0.0) * dist) + }; + plan.set.insert(node, Val::Points(b2, e2)); + } + // Each grip sets the coordinates it stands for: the base's or the end's, or the base's X + // with the end's Y (and the other way round) at the two other corners. A distance below a + // value set's minimum is refused, as AutoCAD refuses it. + (ParameterKind::Xy { x_values, y_values, x_label, y_label, .. }, _) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{x_label} has no points.")) }; + let (mut b2, mut e2) = (b, e); + match part { + GripPart::Base => (b2.x, b2.y) = (q.x, q.y), + GripPart::End => (e2.x, e2.y) = (q.x, q.y), + GripPart::BaseXEndY => (b2.x, e2.y) = (q.x, q.y), + GripPart::BaseYEndX => (e2.x, b2.y) = (q.x, q.y), + GripPart::At => return Err("That grip can't be dragged.".into()), + } + let fit = |set: &super::ValueSet, v: f64, label: &str| { + if set.has_minimum() && v < set.minimum - 1e-9 { + Err(format!("{label} must be at least {}.", set.minimum)) + } else { + Ok(allowed(set, v)) + } + }; + let (dx, dy) = (fit(x_values, e2.x - b2.x, x_label)?, fit(y_values, e2.y - b2.y, y_label)?); + // The moved point keeps the snapped distances from the one that stays. + if matches!(part, GripPart::Base) { + (b2.x, b2.y) = (e2.x - dx, e2.y - dy); + } else if matches!(part, GripPart::End) { + (e2.x, e2.y) = (b2.x + dx, b2.y + dy); + } else if part == GripPart::BaseXEndY { + (b2.x, e2.y) = (e2.x - dx, b2.y + dy); + } else { + (e2.x, b2.y) = (b2.x + dx, e2.y - dy); + } + plan.set.insert(node, Val::Points(b2, e2)); + } + // The angle from the base to the point, snapped to the parameter's values. + (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, GripPart::End) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; + let q3 = Vec3::new(q.x, q.y, b.z); + if (q3 - b).len() < 1e-12 { + return Err(format!("{label} needs a point away from its base.")); + } + // The grip is where its grip object is, which can be off the radius' end: the + // cursor turns the grip, so the angle is the cursor's less that offset. + let offset = p + .grips + .get(1) + .and_then(|id| m.grip_points.iter().find(|(g, _)| g == id)) + .map(|(_, g)| rotation_angle(*hb, *g, (*hb, *he))) + .filter(|_| (*he - *hb).len() > 1e-12) + .unwrap_or(0.0); + let a = allowed(values, (rotation_angle(b, q3, (*hb, *he)) - offset).rem_euclid(std::f64::consts::TAU)); + plan.set.insert(node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); + } _ => return Err("That grip can't be dragged.".into()), } + plan.chain(&m, &r.values, node)?; apply(d, insert, &r.definition, &r.values, &plan.set, node) } +/// Drag the grip of alignment parameter `node` of dynamic block reference `insert` to `to` +/// (drawing coordinates), as AutoCAD does: with `near`, the nearest point of an object at the +/// cursor and the object's direction there, the reference moves so the parameter's base point is +/// on that point and turns so the parameter's direction (base to end) runs along the object, its +/// right-hand side toward the cursor (toward where the grip was when the cursor is on the object); +/// without, the base point just follows the cursor. Only the reference's position and rotation +/// change (AutoCAD records no value for it). +pub fn align_grip(d: &mut Drawing, insert: Handle, node: i32, to: Vec2, near: Option<(Vec2, Vec2)>) -> Result<(), String> { + if !to.is_finite() || near.is_some_and(|(at, along)| !(at.is_finite() && along.is_finite())) { + return Err("Invalid point.".into()); + } + let r = reference(d, insert).ok_or("Not a dynamic block reference.")?; + let m = dynamic_block(d, &r.definition).ok_or("Not a dynamic block reference.")?; + let EntityKind::Insert(ins) = &d.entity(insert).ok_or("No such object.")?.kind else { return Err("Not a block reference.".into()) }; + let p = m.parameters.iter().find(|p| p.node == node).ok_or("The reference has no such parameter.")?; + if !matches!(p.kind, ParameterKind::Alignment { .. }) { + return Err("That isn't an alignment grip.".into()); + } + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err("The alignment has no points.".into()) }; + let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); + let xf = ins.transform(base); + let (wb, way) = (xf.apply(b.xy()), xf.apply(e.xy()) - xf.apply(b.xy())); + let (at, turn) = match near { + Some((at, along)) if along.len() > 1e-12 && way.len() > 1e-12 => { + let u = along * (1.0 / along.len()); + let side = if (to - at).len() > 1e-9 { to - at } else { wb - at }; + let dir = if Vec2::new(u.y, -u.x).dot(side) < 0.0 { u * -1.0 } else { u }; + (at, dir.angle() - way.angle()) + } + Some((at, _)) => (at, 0.0), + None => (to, 0.0), + }; + let t = Mat3::rotate_about(wb, turn).then(Mat3::translate(at - wb)); + if !(turn.is_finite() && t.apply(Vec2::ZERO).is_finite()) { + return Err("Invalid point.".into()); + } + d.modify_entity(insert, |e| e.kind.transform(&t)).map_err(|e| e.to_string()) +} + +/// Most stops one grip shows. +const MAX_STOPS: usize = 200; + +/// The values a value set stops at, for tick marks: its list, or each increment from its minimum +/// to its maximum (to `open_to` without a maximum). None for a value set that takes any value. +fn stops(set: &super::ValueSet, open_to: f64) -> Vec { + let within = |v: f64| { + v.is_finite() && (!set.has_minimum() || v >= set.minimum - 1e-9) && (!set.has_maximum() || set.maximum <= 0.0 || v <= set.maximum + 1e-9) + }; + if set.is_list() { + return set.list.iter().copied().filter(|v| within(*v)).take(MAX_STOPS).collect(); + } + if !(set.has_increment() && set.increment > 0.0 && set.increment.is_finite()) { + return Vec::new(); + } + let from = if set.has_minimum() { set.minimum } else { 0.0 }; + let to = if set.has_maximum() && set.maximum > 0.0 { set.maximum } else { open_to }; + (0..MAX_STOPS).map(|k| from + k as f64 * set.increment).take_while(|v| *v <= to + 1e-9).filter(|v| within(*v)).collect() +} + +/// Where grip `part` of parameter `node` of dynamic block reference `insert` can stop when its +/// parameter's values are a list or go by an increment, as AutoCAD marks them while the grip is +/// dragged: each stop's point and the way the grip travels there (unit vectors, drawing +/// coordinates). Empty when the grip goes anywhere. +pub fn grip_stops(d: &Drawing, insert: Handle, node: i32, part: super::GripPart) -> Vec<(Vec2, Vec2)> { + use super::GripPart; + let Some(r) = reference(d, insert) else { return Vec::new() }; + let Some(m) = dynamic_block(d, &r.definition) else { return Vec::new() }; + let Some(EntityKind::Insert(ins)) = d.entity(insert).map(|e| &e.kind) else { return Vec::new() }; + let Some(p) = m.parameters.iter().find(|p| p.node == node) else { return Vec::new() }; + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Vec::new() }; + let len = (e - b).len(); + if len < 1e-12 { + return Vec::new(); + } + let u = (e - b) * (1.0 / len); + // In the block: (point, travel direction). + let local: Vec<(Vec3, Vec3)> = match (&p.kind, part) { + (ParameterKind::Linear { values, from_midpoint, .. }, GripPart::Base | GripPart::End) => { + let mid = (b + e) * 0.5; + stops(values, 2.0 * len) + .into_iter() + .filter(|v| *v > 0.0) + .map(|v| match (from_midpoint, part) { + (true, GripPart::Base) => (mid - u * (v / 2.0), u * -1.0), + (true, _) => (mid + u * (v / 2.0), u), + (false, GripPart::Base) => (e - u * v, u * -1.0), + (false, _) => (b + u * v, u), + }) + .collect() + } + // A full turn is where no turn is. + // Where the grip is at each angle: its grip object can be off the radius' end, by an + // angle and at a distance of its own. + (ParameterKind::Rotation { base: hb, end: he, values, .. }, GripPart::End) => { + let g = p.grips.get(1).and_then(|id| m.grip_points.iter().find(|(gi, _)| gi == id)).map(|(_, g)| *g); + let home = (*he - *hb).len(); + let (offset, reach) = match g { + Some(g) if home > 1e-12 && (g - *hb).len() > 1e-12 => (rotation_angle(*hb, g, (*hb, *he)), (g - *hb).len() * len / home), + _ => (0.0, len), + }; + let reach_end = b + u * reach; + stops(values, std::f64::consts::TAU) + .into_iter() + .filter(|a| *a < std::f64::consts::TAU - 1e-9) + .map(|a| { + let at = rotation_end(b, reach_end, (*hb, *he), a + offset); + let radial = (at - b).xy(); + (at, radial.perp().to3(0.0)) + }) + .collect() + } + _ => Vec::new(), + }; + let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); + let xf = ins.transform(base); + local + .into_iter() + .filter_map(|(at, way)| { + let (p, ahead) = (xf.apply(at.xy()), xf.apply(at.xy() + way.xy())); + let dir = ahead - p; + (dir.len() > 1e-12 && p.is_finite()).then(|| (p, dir * (1.0 / dir.len()))) + }) + .collect() +} + /// The change of each parameter value an action can follow, by parameter graph id and the /// connection's name ("EndXDelta", "XDelta"…), from `old` and `new` values. fn delta(old: &Val, new: &Val, connection: &str) -> f64 { @@ -458,6 +889,296 @@ fn in_frame(frame: &[Vec2], p: Vec2) -> bool { } } +/// What the actions of one change read (the dynamic block, the parameters' values and the change) +/// and what they write: the values they carry along (`new`, starting from the change) and what +/// happens to each copied object (`moves`). +struct ActionRun<'a> { + m: &'a DynamicBlock, + /// The dynamic block's own objects: a stretch moves the points of each that lie in its frame + /// where the block has them. + def: &'a Block, + values: &'a BTreeMap, + set: &'a BTreeMap, + param_of: HashMap, + /// The reference's copy of each of the dynamic block's objects. + copy_map: &'a HashMap, + new: BTreeMap, + moves: HashMap>, +} + +impl ActionRun<'_> { + fn copy_of(&self, dh: &Handle) -> Option { + self.copy_map.get(dh).copied() + } + + /// The value of parameter `node` so far: carried along by an action already, else the + /// reference's. + fn value_of(&self, node: i32) -> Option { + self.new.get(&node).cloned().or_else(|| current(self.m, self.values, node)) + } + + /// Action `a`, when one of its connections follows a parameter the change sets. + fn action(&mut self, a: &super::Action) -> Result<(), String> { + if !a.connections.iter().any(|(n, _)| self.set.contains_key(n)) { + return Ok(()); + } + match (transform_of(self.m, self.values, self.set, a)?, &a.kind) { + (Some(t), _) => self.transform(a, t), + (None, ActionKind::PolarStretch { .. }) => self.polar_stretch(a), + (None, _) => self.stretch(a), + } + Ok(()) + } + + /// Arrays, made again from the first copy of each arrayed object for the parameter's value now + /// (whatever changed): the copy follows the parameter's base point, the others repeat it. The + /// offsets of each arrayed object's other copies, by the object's copy in the reference. + fn arrays(&mut self) -> Result>, String> { + let mut arrays: HashMap> = HashMap::new(); + // Copies the arrays make so far: the budget is taken before each copy's offsets are kept, + // so many objects in a large array are refused before their offsets are held. + let mut total = 0usize; + for a in &self.m.actions { + let ActionKind::Array { column, row } = a.kind else { continue }; + let Some((node, _)) = a.connections.first() else { continue }; + let Some(p) = self.m.parameters.iter().find(|p| p.node == *node) else { continue }; + let (Some(Val::Points(was, _)), Some(Val::Points(b, e))) = (current(self.m, self.values, *node), self.value_of(*node)) else { + continue; + }; + let offsets = array_offsets(&p.kind, b, e, column, row)?; + let shift = (b - was).xy(); + for h in a.selection.iter().filter(|h| !self.param_of.contains_key(h)) { + let Some(c) = self.copy_of(h) else { continue }; + if shift.x != 0.0 || shift.y != 0.0 { + self.moves.entry(c).or_default().push(Op::Move(None, shift)); + } + keep_array(&mut arrays, &mut total, c, &offsets)?; + } + } + Ok(arrays) + } + + /// A base point parameter the actions moved: AutoCAD keeps it at the block's base point, so the + /// block's objects and parameters move back by its move, and the reference's insertion point + /// moves forward by it (the returned move: the reference stays where it was, but for what the + /// actions changed). (A fixed base point of a rotate or scale action stays where the dynamic + /// block has it.) + fn rebase(&mut self, src: &Block) -> Vec2 { + let mut rebase = Vec2::ZERO; + if let Some(p) = self.m.parameters.iter().find(|p| matches!(p.kind, ParameterKind::BasePoint { .. })) + && let (Some(Val::Point(was)), Some(Val::Point(now))) = (current(self.m, self.values, p.node), self.new.get(&p.node).cloned()) + { + let v = (now - was).xy(); + if v.len() > 1e-12 && v.is_finite() { + rebase = v; + self.new.insert(p.node, Val::Point(was)); + } + } + if rebase == Vec2::ZERO { + return rebase; + } + for e in src.entities.iter() { + self.moves.entry(e.handle).or_default().push(Op::Move(None, rebase * -1.0)); + } + let back = |q: Vec3| q - rebase.to3(0.0); + for p in self.m.parameters.iter().filter(|p| !matches!(p.kind, ParameterKind::BasePoint { .. })) { + let moved = match self.value_of(p.node) { + Some(Val::Point(q)) => Val::Point(back(q)), + Some(Val::Points(b, e)) => Val::Points(back(b), back(e)), + Some(Val::Flip(b, e, f)) => Val::Flip(back(b), back(e), f), + _ => continue, + }; + self.new.insert(p.node, moved); + } + rebase + } + + /// A rotate, flip or scale action turns, mirrors or scales its objects, and carries the + /// parameters in its selection the same way. A handle the selection repeats is handled once + /// (twice would turn or scale it twice, or mirror it back). + fn transform(&mut self, a: &super::Action, t: Mat3) { + let mut handled: HashSet = HashSet::new(); + for h in &a.selection { + if !handled.insert(*h) { + continue; + } + if let Some(node) = self.param_of.get(h).copied() { + if self.set.contains_key(&node) { + continue; + } + let Some(cur) = self.value_of(node) else { continue }; + let p = |q: Vec3| t.apply(q.xy()).to3(q.z); + let moved = match cur { + Val::Point(q) => Val::Point(p(q)), + Val::Points(b, e) => Val::Points(p(b), p(e)), + Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f), + other => other, + }; + self.new.insert(node, moved); + } else if let Some(c) = self.copy_of(h) { + self.moves.entry(c).or_default().push(Op::Transform(t)); + } + } + } + + /// A polar stretch action turns its objects about its parameter's base point and moves the + /// ones in its frame after the turn, and carries the parameters in its selection. The objects it + /// only turns (`rotate_only`) are not also stretched. + fn polar_stretch(&mut self, a: &super::Action) { + let ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset } = &a.kind else { return }; + let Some((turn, v)) = polar_stretch(self.m, self.values, self.set, a, *multiplier, *angle_offset) else { return }; + // As for stretch actions: vertex lists indexed once, a repeated handle handled once. + let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); + let mut handled: HashSet = HashSet::new(); + for h in &a.selection { + if !handled.insert(*h) { + continue; + } + if let Some(node) = self.param_of.get(h).copied() { + // Its points turn, and the ones in the frame (where the dynamic block has them) + // follow the distance. + if self.set.contains_key(&node) { + continue; + } + let Some(cur) = self.value_of(node) else { continue }; + let home = current(self.m, &BTreeMap::new(), node); + self.new.insert(node, turned_and_shifted(cur, home, frame, (turn, v))); + continue; + } + let Some(c) = self.copy_of(h) else { continue }; + let idx = vtx_by_handle.get(h).map(|i| (*i).clone()); + let ops = self.moves.entry(c).or_default(); + ops.push(Op::Transform(turn)); + ops.push(Op::Move(idx, v)); + } + // Objects only turned (an object also in the selection is stretched, as AutoCAD does). + for h in rotate_only.iter().filter(|h| !handled.contains(h) && !self.param_of.contains_key(h)).collect::>() { + if let Some(c) = self.copy_of(h) { + self.moves.entry(c).or_default().push(Op::Transform(turn)); + } + } + } + + /// A stretch or move action moves its objects (the vertices of a stretch's frame) by the change + /// of its two connections, and carries the parameters in its selection. + fn stretch(&mut self, a: &super::Action) { + let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec)]) = match &a.kind { + ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices), + ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]), + _ => return, + }; + // The two connections give the change in x and y. + let comp = |i: usize| { + a.connections.get(i).map_or(0.0, |(n, conn)| match (self.set.get(n), current(self.m, self.values, *n)) { + (Some(nv), Some(ov)) => delta(&ov, nv, conn), + _ => 0.0, + }) + }; + // A zero multiplier would move nothing. AutoCAD 2024 moves such an action by the + // parameter's change and leaves its angle offset out (measured on a stretch action written + // with multiplier 0, angle offset 1 and group 280 = 1). + let (mult, angle) = if mult == 0.0 { (1.0, 0.0) } else { (mult, angle) }; + let v = Vec2::new(comp(0), comp(1)).rotate(angle) * mult; + if !(v.x.is_finite() && v.y.is_finite()) || (v.x == 0.0 && v.y == 0.0) { + return; + } + // Index this action's vertex lists by handle once, and skip handles already handled in + // this action's selection, so a selection that repeats a handle does not re-scan the + // vertex list and re-clone its index vector per occurrence (CWE-400). + let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); + // Whether the frame (two corners or a polygon) is tested point by point. + let framed = (2..=MAX_FRAME_POINTS).contains(&frame.len()); + let mut handled: HashSet = HashSet::new(); + for h in &a.selection { + if !handled.insert(*h) { + continue; + } + if let Some(node) = self.param_of.get(h).copied() { + // A parameter in the selection is carried along: its points in the frame. Which + // points are in it is decided where the dynamic block has them (AutoCAD evaluates + // the actions from the block itself, so a point another action has moved out of + // the frame still follows). + if self.set.contains_key(&node) { + continue; + } + let Some(cur) = self.value_of(node) else { continue }; + let home = current(self.m, &BTreeMap::new(), node); + self.new.insert(node, shifted(cur, home, frame, v)); + continue; + } + let Some(c) = self.copy_of(h) else { continue }; + // The points of a line or polyline that move are those inside the frame where the + // dynamic block has them, all of them when none is, as AutoCAD 2024 moves them. It + // doesn't go by the vertex lists the action stores, which a block from another program + // can get wrong. A polyline's vertices are in its own plane: in the block's when its + // extrusion is exactly along z (a mirrored one is read flipped into it). Any tilt, however + // small, moves them by as much as the elevation times the tilt, so a tilted one keeps the + // stored list. + let idx = match self.def.entities.get(*h).map(|e| (&e.kind, e.common.extrusion)) { + Some((EntityKind::Line(l), _)) if framed => inside(frame, [l.a.xy(), l.b.xy()].into_iter()), + Some((EntityKind::LwPolyline(pl), n)) if framed && n.x == 0.0 && n.y == 0.0 => inside(frame, pl.vertices.iter().map(|v| v.p)), + _ => vtx_by_handle.get(h).map(|i| (*i).clone()), + }; + self.moves.entry(c).or_default().push(Op::Move(idx, v)); + } + } +} + +/// The reference's copies by element tag: each copy's tag, and the first copy of each tag (an +/// arrayed object's copies all carry its tag; the first is the one the array starts from). +fn tags_of_copies(d: &Drawing, src: &Block) -> (HashMap, HashMap) { + let tags = by_tag(d, src); + let of_copy = tags.iter().map(|(t, h)| (*h, *t)).collect(); + let mut first: HashMap = HashMap::new(); + for (t, h) in tags { + first.entry(t).or_insert(h); + } + (of_copy, first) +} + +/// The earlier copies of arrayed objects (the arrays replace them). +fn earlier_copies(src: &Block, src_tag: &HashMap, arrays: &HashMap>) -> HashSet { + let arrayed_tags: HashSet = arrays.keys().filter_map(|h| src_tag.get(h)).copied().collect(); + src.entities + .iter() + .filter(|e| !arrays.contains_key(&e.handle) && src_tag.get(&e.handle).is_some_and(|t| arrayed_tags.contains(t))) + .map(|e| e.handle) + .collect() +} + +/// A parameter value `cur` turned by `turn`, and carried by `v` where its points are in `frame` +/// (judged where the dynamic block has them, `home`), after a polar stretch. +fn turned_and_shifted(cur: Val, home: Option, frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val { + let carry = |p: Vec3, at: Vec3| { + let q = turn.apply(p.xy()).to3(p.z); + if in_frame(frame, at.xy()) { q + v.to3(0.0) } else { q } + }; + match (cur, home) { + (Val::Point(p), Some(Val::Point(h))) => Val::Point(carry(p, h)), + (Val::Point(p), _) => Val::Point(carry(p, p)), + (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(carry(b, hb), carry(e, he)), + (Val::Points(b, e), _) => Val::Points(carry(b, b), carry(e, e)), + (Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(carry(b, hb), carry(e, he), f), + (Val::Flip(b, e, f), _) => Val::Flip(carry(b, b), carry(e, e), f), + (t, _) => t, + } +} + +/// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where +/// the dynamic block has them (`home`), move. +fn shifted(cur: Val, home: Option, frame: &[Vec2], v: Vec2) -> Val { + let shift = |p: Vec3, at: Option| if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p }; + match (cur, home) { + (Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))), + (Val::Point(p), _) => Val::Point(shift(p, None)), + (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))), + (Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)), + (Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f), + (Val::Flip(b, e, f), _) => Val::Flip(shift(b, None), shift(e, None), f), + (t, _) => t, + } +} + /// Give `insert` a new anonymous block with the plan's values applied (visibility states, and /// the stretch and move actions of the changed parameters, with the parameters in their selections /// carried along), and record the new values on it. @@ -476,87 +1197,27 @@ fn apply( let src = d.block(&ins.block).cloned().ok_or("The reference's block is missing.")?; // The dynamic block's objects and the reference's copies of them, by element tag. let def_tags: HashMap = by_tag(d, &def).into_iter().map(|(t, h)| (h, t)).collect(); - let src_by_tag: HashMap = by_tag(d, &src).into_iter().collect(); - let copy_of = |dh: &Handle| def_tags.get(dh).and_then(|t| src_by_tag.get(t)).copied(); + let (src_tag, src_by_tag) = tags_of_copies(d, &src); + let copy_map: HashMap = def_tags.iter().filter_map(|(dh, tag)| Some((*dh, *src_by_tag.get(tag)?))).collect(); + let copy_of = |dh: &Handle| copy_map.get(dh).copied(); // New values, starting from the change; actions add the parameters they carry along. - let mut new: BTreeMap = set.clone(); - let mut moves: HashMap>, Vec2)>> = HashMap::new(); - let param_of: HashMap = m.parameters.iter().map(|p| (p.handle, p.node)).collect(); + let mut run = ActionRun { + m: &m, + def: &def, + values, + set, + param_of: m.parameters.iter().map(|p| (p.handle, p.node)).collect(), + copy_map: ©_map, + new: set.clone(), + moves: HashMap::new(), + }; for a in &m.actions { - let changed: Vec<&(i32, String)> = a.connections.iter().filter(|(n, _)| set.contains_key(n)).collect(); - if changed.is_empty() { - continue; - } - let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec)]) = match &a.kind { - ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices), - ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]), - _ => continue, - }; - // The two connections give the change in x and y. - let comp = |i: usize| { - a.connections.get(i).map_or(0.0, |(n, conn)| match (set.get(n), current(&m, values, *n)) { - (Some(nv), Some(ov)) => delta(&ov, nv, conn), - _ => 0.0, - }) - }; - // A zero multiplier would move nothing. AutoCAD 2024 moves such an action by the - // parameter's change and leaves its angle offset out (measured on a stretch action written - // with multiplier 0, angle offset 1 and group 280 = 1). - let (mult, angle) = if mult == 0.0 { (1.0, 0.0) } else { (mult, angle) }; - let v = Vec2::new(comp(0), comp(1)).rotate(angle) * mult; - if !(v.x.is_finite() && v.y.is_finite()) || (v.x == 0.0 && v.y == 0.0) { - continue; - } - // Index this action's vertex lists by handle once, and skip handles already handled in - // this action's selection, so a selection that repeats a handle does not re-scan the - // vertex list and re-clone its index vector per occurrence (CWE-400). - let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); - // Whether the frame (two corners or a polygon) is tested point by point. - let framed = (2..=MAX_FRAME_POINTS).contains(&frame.len()); - let mut handled: HashSet = HashSet::new(); - for h in &a.selection { - if !handled.insert(*h) { - continue; - } - if let Some(node) = param_of.get(h) { - // A parameter in the selection is carried along: its points in the frame. Which - // points are in it is decided where the dynamic block has them (AutoCAD evaluates - // the actions from the block itself, so a point another action has moved out of - // the frame still follows). - if set.contains_key(node) { - continue; - } - let Some(cur) = new.get(node).cloned().or_else(|| current(&m, values, *node)) else { continue }; - let home = current(&m, &BTreeMap::new(), *node); - let shift = |p: Vec3, at: Option| { - if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p } - }; - let moved = match (cur, home) { - (Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))), - (Val::Point(p), _) => Val::Point(shift(p, None)), - (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))), - (Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)), - (t, _) => t, - }; - new.insert(*node, moved); - continue; - } - let Some(c) = copy_of(h) else { continue }; - // The points of a line or polyline that move are those inside the frame where the - // dynamic block has them, all of them when none is, as AutoCAD 2024 moves them. It - // doesn't go by the vertex lists the action stores, which a block from another program - // can get wrong. A polyline's vertices are in its own plane: in the block's when its - // extrusion is exactly along z (a mirrored one is read flipped into it). Any tilt, however - // small, moves them by as much as the elevation times the tilt, so a tilted one keeps the - // stored list. - let idx = match def.entities.get(*h).map(|e| (&e.kind, e.common.extrusion)) { - Some((EntityKind::Line(l), _)) if framed => inside(frame, [l.a.xy(), l.b.xy()].into_iter()), - Some((EntityKind::LwPolyline(pl), n)) if framed && n.x == 0.0 && n.y == 0.0 => inside(frame, pl.vertices.iter().map(|v| v.p)), - _ => vtx_by_handle.get(h).map(|i| (*i).clone()), - }; - moves.entry(c).or_default().push((idx, v)); - } + run.action(a)?; } + let arrays = run.arrays()?; + let rebase = run.rebase(&src); + let earlier = earlier_copies(&src, &src_tag, &arrays); + let ActionRun { new, moves, .. } = run; // Visibility states. let mut shown: HashMap = HashMap::new(); for (node, v) in &new { @@ -578,18 +1239,35 @@ fn apply( let mut b = Block { name: name.clone(), anonymous: true, xref_path: None, array: None, units: 0, entities: crate::EntityStore::new(), ..(*src).clone() }; let mut copies: HashMap = HashMap::new(); - for e in src.entities.iter() { + for e in src.entities.iter().filter(|e| !earlier.contains(&e.handle)) { copies.insert(e.handle, d.new_handle()); } - // How far each attribute definition moves (block coordinates): the reference's attribute of - // that tag moves with it, as AutoCAD moves it. - let attrib_moves: HashMap = src + // The array copies made of each object: (its copy in the reference, the new copy). + let mut repeats: Vec<(Handle, Handle)> = Vec::new(); + // Each arrayed object's copies' handles, by place in its array, made before any copy is (in + // the order the copies are made, so the handles are those they would get anyway): a repeated + // associative hatch's loops name the copy of their outline at the same place. + let mut repeat_handles: HashMap<(Handle, usize), Handle> = HashMap::new(); + for e in src.entities.iter().filter(|e| copies.contains_key(&e.handle) && !matches!(e.kind, EntityKind::AttDef(_))) { + for k in 0..arrays.get(&e.handle).map_or(0, Vec::len) { + repeat_handles.insert((e.handle, k), d.new_handle()); + } + } + // How each attribute definition moves, turns or mirrors (block coordinates): the reference's + // attribute of that tag follows it, as AutoCAD moves it. + let attrib_moves: HashMap = src .entities .iter() .filter_map(|e| match &e.kind { EntityKind::AttDef(ad) => { - let v = moves.get(&e.handle).into_iter().flatten().fold(Vec2::ZERO, |acc, (_, v)| acc + *v); - (v != Vec2::ZERO).then(|| (ad.tag.to_ascii_uppercase(), v)) + let ops = moves.get(&e.handle)?; + let t = ops.iter().fold(Mat3::IDENTITY, |acc, op| { + acc.then(match op { + Op::Move(_, v) => Mat3::translate(*v), + Op::Transform(t) => *t, + }) + }); + Some((ad.tag.to_ascii_uppercase(), t)) } _ => None, }) @@ -607,15 +1285,61 @@ fn apply( if let Some(v) = shown_copy.get(&e.handle) { c.common.visible = *v; } - for (idx, v) in moves.get(&e.handle).into_iter().flatten() { - move_entity(&mut c, idx.as_deref(), *v); + for op in moves.get(&e.handle).into_iter().flatten() { + match op { + Op::Move(idx, v) => move_entity(&mut c, idx.as_deref(), *v), + // Text and attribute definitions keep reading as AutoCAD keeps them. + Op::Transform(t) => match &mut c.kind { + EntityKind::Text(x) => carry_text(x, t), + EntityKind::AttDef(a) if a.multiline.is_none() => carry_text(&mut a.text, t), + k => k.transform(t), + }, + } } if let EntityKind::Hatch(h) = &mut c.kind { for l in &mut h.loops { l.sources = l.sources.iter().map(|s| copies.get(s).copied().unwrap_or(*s)).collect(); } } + // An arrayed object's other copies (attribute definitions aren't repeated: the + // reference has one attribute per tag), marked as AutoCAD marks them; the first isn't. + let offsets = arrays.get(&e.handle).filter(|_| !matches!(c.kind, EntityKind::AttDef(_))); + if offsets.is_some() { + mark_repeat(&mut c.common.xdata, false); + } + let again: Vec = offsets + .into_iter() + .flatten() + .enumerate() + .map(|(k, v)| { + let mut r = c.clone(); + r.handle = repeat_handles.get(&(e.handle, k)).copied().unwrap_or_else(|| d.new_handle()); + // A loop whose outline is repeated at this place follows that copy of it. + if let (EntityKind::Hatch(h), EntityKind::Hatch(src_h)) = (&mut r.kind, &e.kind) { + for (l, sl) in h.loops.iter_mut().zip(&src_h.loops) { + for (s, orig) in l.sources.iter_mut().zip(&sl.sources) { + let same_place = arrays.get(orig).and_then(|o| o.get(k)) == Some(v); + if let Some(rh) = repeat_handles.get(&(*orig, k)).filter(|_| same_place) { + *s = *rh; + } + } + } + } + for t in &mut r.common.xdata { + if t.code == 1005 && Handle::parse_hex(&t.value) == Some(nh) { + t.value = r.handle.hex(); + } + } + mark_repeat(&mut r.common.xdata, true); + r.kind.transform(&Mat3::translate(*v)); + repeats.push((e.handle, r.handle)); + r + }) + .collect(); b.entities.push(c); + for r in again { + b.entities.push(r); + } } refill_hatches(&mut b); let def_record = Some(record_handle(d, definition).unwrap_or_else(|| { @@ -627,13 +1351,16 @@ fn apply( let old = ins.block.clone(); d.blocks.insert(name.clone(), std::sync::Arc::new(b)); let f = std::sync::Arc::make_mut(&mut d.foreign); - for (old_h, new_h) in &copies { + for (i, (old_h, new_h)) in copies.iter().chain(repeats.iter().map(|(a, b)| (a, b))).enumerate() { if let Some(mut x) = f.entities.get(old_h).cloned() { for t in &mut x.xdata { if t.code == 1005 && Handle::parse_hex(&t.value) == Some(*old_h) { t.value = new_h.hex(); } } + if arrays.contains_key(old_h) && etag_in(&x.xdata).is_some() { + mark_repeat(&mut x.xdata, i >= copies.len()); + } x.xdict = None; // Reactors within the block (an associative hatch's outline) follow to the copies; // ones outside it are not ours. @@ -645,21 +1372,21 @@ fn apply( let xdata = vec![tag(1001, BTAG), tag(1070, "1"), tag(1005, rec.hex())]; f.records.insert(("BLOCK_RECORD".into(), name.to_ascii_uppercase()), ForeignExtra { xdata, ..Default::default() }); } - // The block-to-drawing transform's linear part turns a block-coordinate move into the move of - // the reference's attribute. + // A block-coordinate change of an attribute definition, seen in the drawing (through the + // block-to-drawing transform), is the change of the reference's attribute. let to_world = ins.transform(src.base.xy()); - let origin = to_world.apply(Vec2::ZERO); + let to_block = to_world.inverse().unwrap_or(Mat3::IDENTITY); + // The insertion point's move for a moved base point (the block's objects moved back by it). + let shift = to_world.apply(rebase) - to_world.apply(Vec2::ZERO); d.modify_entity(insert, |e| { if let EntityKind::Insert(i) = &mut e.kind { i.block = name.clone(); + i.insert = i.insert + shift.to3(0.0); for a in &mut i.attribs { - if let Some(v) = attrib_moves.get(&a.tag.to_ascii_uppercase()) { - let w = to_world.apply(*v) - origin; - let mut k = EntityKind::Text(a.text.clone()); - k.transform(&Mat3::translate(w)); - if let EntityKind::Text(t) = k { - a.text = t; - } + if let Some(t) = attrib_moves.get(&a.tag.to_ascii_uppercase()) { + let w = to_block.then(*t).then(Mat3::translate(rebase)).then(to_world); + carry_text(&mut a.text, &w); + a.transform_multiline(&w); } } } @@ -671,6 +1398,79 @@ fn apply( Ok(()) } +/// Xdata application AutoCAD marks an array's copies with (all but the first). +const ARRAY_TAG: &str = "AcDbBlockArrayActionTag"; + +/// Mark xdata `x` as an array's copy (`on`) or not: without the mark AutoCAD can't change the +/// reference again ("Invalid input"). +fn mark_repeat(x: &mut Vec, on: bool) { + if let Some(at) = x.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ARRAY_TAG)) { + let end = x.iter().skip(at + 1).position(|t| t.code == 1001).map_or(x.len(), |n| at + 1 + n); + x.drain(at..end); + } + if on { + x.push(tag(1001, ARRAY_TAG)); + x.push(tag(1070, "1")); + } +} + +/// Most copies one change's arrays make. +const MAX_ARRAY: usize = 100_000; + +/// Keep `offsets` as copy `c`'s array (in place of one an earlier action gave it), within the +/// budget of `MAX_ARRAY` copies in all (`total`, updated). Over it, nothing is kept or cloned. +fn keep_array(arrays: &mut HashMap>, total: &mut usize, c: Handle, offsets: &[Vec2]) -> Result<(), String> { + let next = total.saturating_sub(arrays.get(&c).map_or(0, Vec::len)).saturating_add(offsets.len()); + if next > MAX_ARRAY { + return Err(format!("The arrays would make more than {MAX_ARRAY} copies.")); + } + *total = next; + arrays.insert(c, offsets.to_vec()); + Ok(()) +} + +/// Where an array action repeats its objects (offsets from the first copy, which isn't listed) +/// for parameter `kind` with points `b` and `e`, as AutoCAD repeats them: along a linear or polar +/// parameter, one copy for each whole `column` in its distance; across an XY parameter, a whole +/// number of `column`s along X by `row`s along Y, toward the end. Fewer than one of either leaves +/// the object alone. +fn array_offsets(kind: &ParameterKind, b: Vec3, e: Vec3, column: f64, row: f64) -> Result, String> { + // How many whole steps of `step` fit in `span` (a little short still counts as whole). + let fits = |span: f64, step: f64| -> Result { + if !(step > 0.0 && step.is_finite() && span.is_finite()) { + return Ok(0); + } + let n = (span.abs() / step + 1e-9).floor(); + if n > MAX_ARRAY as f64 { + return Err(format!("The array would make more than {MAX_ARRAY} copies.")); + } + Ok(n as usize) + }; + let d = (e - b).xy(); + match kind { + ParameterKind::Linear { .. } | ParameterKind::Polar { .. } => { + let n = fits(d.len(), column)?; + if n < 2 { + return Ok(Vec::new()); + } + let u = d * (1.0 / d.len()); + Ok((1..n).map(|k| u * (k as f64 * column)).collect()) + } + ParameterKind::Xy { .. } => { + let (cols, rows) = (fits(d.x, column)?, fits(d.y, row)?); + if cols < 1 || rows < 1 || cols.saturating_mul(rows) < 2 { + return Ok(Vec::new()); + } + if cols.saturating_mul(rows) > MAX_ARRAY { + return Err(format!("The array would make more than {MAX_ARRAY} copies.")); + } + let (sx, sy) = (if d.x < 0.0 { -column } else { column }, if d.y < 0.0 { -row } else { row }); + Ok((0..rows).flat_map(|j| (0..cols).map(move |i| Vec2::new(i as f64 * sx, j as f64 * sy))).skip(1).collect()) + } + _ => Ok(Vec::new()), + } +} + /// Associative hatches of block `b` whose loop is one closed polyline of the block take its /// outline again (it may have been stretched). fn refill_hatches(b: &mut Block) { @@ -881,9 +1681,13 @@ fn record_values( } None => { let h = d.new_handle(); - let mut tags = templates.get(&key).cloned().unwrap_or_else(|| { - let p = at(*node); - vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())] + let mut tags = templates.get(&key).cloned().unwrap_or_else(|| match v { + // A flip grip's record: its header's groups and two states, the last one its own. + Val::State(_) => vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(70, "25"), tag(70, "104"), tag(70, "0"), tag(70, "0")], + _ => { + let p = at(*node); + vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())] + } }); write_value(&mut tags, v); objects.push(ForeignObject { handle: h, kind: "XRECORD".into(), tags: own(tags, h, data) }); @@ -962,12 +1766,32 @@ fn write_history(tags: &mut Vec, p: &super::Parameter, old: Option<&Val> (ParameterKind::Visibility { label, .. } | ParameterKind::Lookup { label, .. }, Val::Text(t)) => { vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(1, t.clone())])] } + (ParameterKind::Rotation { label, base: hb, end: he, .. }, Val::Points(b, e)) => { + let a = rotation_angle(*b, *e, (*hb, *he)); + vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, a.to_string())])] + } + (ParameterKind::Flip { label, .. }, Val::Flip(_, _, f)) => { + vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(70, i32::from(*f).to_string())])] + } (ParameterKind::Linear { label, .. }, Val::Points(b, e)) => { let mut c: Vec<(i32, Vec)> = p.grips.iter().filter(|g| **g != 0).map(|g| (*g, Vec::new())).collect(); c.push((p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, (*e - *b).len().to_string())])); c } (ParameterKind::Point { at, .. }, Val::Point(q)) => grips(&[(was.unwrap_or(*at), *q, *at)]), + // As drags of the base and end grips from where the dynamic block has them: the entries + // of all its grips (an XY parameter's corners too) give way to these two. + (ParameterKind::Polar { base: hb, end: he, .. } | ParameterKind::Xy { base: hb, end: he, .. }, Val::Points(b, e)) => p + .grips + .iter() + .enumerate() + .filter(|(_, g)| **g != 0) + .map(|(i, g)| match i { + 0 => grip(*g, *b - *hb), + 1 => grip(*g, *e - *he), + _ => (*g, Vec::new()), + }) + .collect(), _ => return, }; // The header, then the entries (each from its 1071). @@ -999,10 +1823,14 @@ fn write_value(tags: &mut Vec, v: &Val) { return; } Val::Point(p) => vec![*p], - Val::Points(b, e) => vec![*b, *e], + Val::Points(b, e) | Val::Flip(b, e, _) => vec![*b, *e], + Val::State(f) => { + set_state(tags, *f); + return; + } }; for (i, p) in points.iter().enumerate() { - // The i-th point's groups, else new ones before any text. + // The i-th point's groups, else new ones before any text or a state after the points. let find = |tags: &[RawTag], code: i32, n: usize| tags.iter().enumerate().filter(|(_, t)| t.code == code).nth(n).map(|(j, _)| j); match (find(tags, 10, i), find(tags, 20, i)) { (Some(jx), Some(jy)) => { @@ -1017,11 +1845,134 @@ fn write_value(tags: &mut Vec, v: &Val) { } } _ => { - let at = tags.iter().position(|t| t.code == 1).unwrap_or(tags.len()); + let first = tags.iter().position(|t| t.code == 10); + let at = + tags.iter().enumerate().position(|(j, t)| t.code == 1 || (t.code == 70 && first.is_some_and(|f| j > f))).unwrap_or(tags.len()); tags.splice(at..at, [tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())]); } } } + // A flip value's state follows both its points. + if let Val::Flip(_, _, f) = v { + set_state(tags, *f); + } +} + +/// Set a record's state: a flip value's group 70 after its points, a flip grip's last group 70 +/// after the header's two (`70 25`, `70 104`); added at the end when the record has none. +fn set_state(tags: &mut Vec, on: bool) { + let first_point = tags.iter().position(|t| t.code == 10); + let at: Vec = tags.iter().enumerate().filter(|(_, t)| t.code == 70).map(|(i, _)| i).collect(); + let last = match first_point { + Some(p) => at.iter().rev().find(|i| **i > p), + None => at.get(2..).and_then(|rest| rest.last()), + }; + match last { + Some(&i) => { + if let Some(t) = tags.get_mut(i) { + t.value = i32::from(on).to_string(); + } + } + None => tags.push(tag(70, i32::from(on).to_string())), + } +} + +/// The transform action `a` makes with the changes `set`, if it is one and they change it: a +/// rotate action turns about its base point by the change of its rotation parameter's angle; a flip +/// action mirrors across its flip parameter's reflection line when the state changes; a scale +/// action scales about its base point by how much its distances grew. +fn transform_of(m: &DynamicBlock, values: &BTreeMap, set: &BTreeMap, a: &super::Action) -> Result, String> { + Ok(match &a.kind { + ActionKind::Rotate { base } => { + let Some((node, _)) = a.connections.iter().find(|(_, c)| c.eq_ignore_ascii_case("AngleDelta")) else { return Ok(None) }; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; + let turn = (*ne - *nb).xy().angle() - (oe - ob).xy().angle(); + let pivot = if base.dependent { *nb + base.offset } else { base.at }; + (turn.abs() > 1e-12 && turn.is_finite()).then(|| Mat3::rotate_about(pivot.xy(), turn)) + } + ActionKind::Flip => { + let Some((node, _)) = a.connections.first() else { return Ok(None) }; + let (Some(Val::Flip(b, e, now)), Some(Val::Flip(_, _, was))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; + (now != &was && (*e - *b).len() > 1e-12).then(|| Mat3::mirror(b.xy(), e.xy())) + } + ActionKind::Scale { base } => scale_of(m, values, set, a, base)?, + _ => None, + }) +} + +/// What polar stretch action `a` does with the changes `set`: the turn about its parameter's base +/// point by the change of its angle, and how far the points in its frame move after it (the end +/// point's move less the turn's, times the multiplier, turned by the angle offset). `None` when its +/// parameter didn't change. +fn polar_stretch( + m: &DynamicBlock, + values: &BTreeMap, + set: &BTreeMap, + a: &super::Action, + multiplier: f64, + angle_offset: f64, +) -> Option<(Mat3, Vec2)> { + let (node, _) = a.connections.iter().find(|(n, _)| set.contains_key(n))?; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return None }; + let (was, now) = ((oe - ob).xy(), (*ne - *nb).xy()); + // A distance of 0 has no direction: nothing turns. + let delta = if was.len() > 1e-12 && now.len() > 1e-12 { now.angle() - was.angle() } else { 0.0 }; + let turn = Mat3::rotate_about(ob.xy(), delta); + let mult = if multiplier == 0.0 { 1.0 } else { multiplier }; + let v = (ne.xy() - turn.apply(oe.xy())).rotate(angle_offset) * mult; + let still = delta.abs() < 1e-12 && v.len() < 1e-12; + (delta.is_finite() && v.is_finite() && !still).then_some((turn, v)) +} + +/// The scale factors one change of a scale action may make: past them the objects would vanish +/// or their sizes overflow. +const MIN_SCALE: f64 = 1e-9; +const MAX_SCALE: f64 = 1e9; + +/// A scale action's transform for the changes `set`: it scales uniformly by the ratio of the new +/// distance from its parameter's base to its end to the old one (an XY parameter's diagonal, as +/// AutoCAD scales by it), about the base point, which follows the parameter's base point when the +/// action says so. (AutoCAD can scale by an XY parameter's X or Y distance alone, but keeps that +/// choice only in DWG data that isn't read.) +fn scale_of( + m: &DynamicBlock, + values: &BTreeMap, + set: &BTreeMap, + a: &super::Action, + base: &super::ActionBase, +) -> Result, String> { + let names = ["Scale", "XScale", "YScale"]; + let Some((node, _)) = a.connections.iter().find(|(n, c)| set.contains_key(n) && names.iter().any(|x| c.eq_ignore_ascii_case(x))) else { + return Ok(None); + }; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; + let (now, was) = ((*ne - *nb).xy().len(), (oe - ob).xy().len()); + if was < 1e-12 { + // From nothing no ratio is known. + return Err(format!("{} can't scale objects from a distance of 0.", a.name)); + } + let s = now / was; + if (s - 1.0).abs() < 1e-12 { + return Ok(None); + } + if s.is_nan() || s < MIN_SCALE { + return Err(format!("{} would scale objects to nothing.", a.name)); + } + if s > MAX_SCALE { + return Err(format!("{} would scale objects more than {MAX_SCALE} times.", a.name)); + } + let pivot = match a.connections.first().and_then(|(n, _)| set.get(n).cloned().or_else(|| current(m, values, *n))) { + Some(Val::Points(b, _)) if base.dependent => b + base.offset, + _ => base.at, + }; + Ok(Some(Mat3::scale_about(pivot.xy(), s))) +} + +/// One change to a copied object: a move (of the listed vertices, else all of it) or a turn or +/// mirror. +enum Op { + Move(Option>, Vec2), + Transform(Mat3), } /// Remove anonymous block `name` when nothing refers to it any more (the block a changed @@ -1051,6 +2002,22 @@ fn drop_if_unused(d: &mut Drawing, name: &str) { mod tests { use super::*; + #[test] + fn the_array_budget_is_taken_before_offsets_are_kept() { + let mut arrays: HashMap> = HashMap::new(); + let mut total = 0; + let big = vec![Vec2::ZERO; MAX_ARRAY - 10]; + keep_array(&mut arrays, &mut total, Handle(1), &big).unwrap(); + // The next object's array would pass the budget: refused, nothing more kept. + assert!(keep_array(&mut arrays, &mut total, Handle(2), &[Vec2::ZERO; 20]).is_err()); + assert_eq!((arrays.len(), total), (1, MAX_ARRAY - 10)); + // A copy whose array another action replaces counts once. + keep_array(&mut arrays, &mut total, Handle(1), &[Vec2::ZERO; 3]).unwrap(); + assert_eq!(total, 3); + keep_array(&mut arrays, &mut total, Handle(2), &[Vec2::ZERO; 20]).unwrap(); + assert_eq!(total, 23); + } + fn tagged(h: u64, tag_value: Option<&str>) -> Entity { let mut e = Entity::new(Handle(h), EntityKind::Line(crate::Line { a: Vec3::ZERO, b: Vec3::ZERO })); if let Some(v) = tag_value { @@ -1073,6 +2040,19 @@ mod tests { assert_eq!(by_tag(&d, &anon), vec![(20, Handle(5)), (1_000_001, Handle(6))]); } + #[test] + fn a_flip_value_s_state_follows_both_its_points() { + // A one-point record, with and without its state: the end point goes in before the state. + let one = || vec![tag(10, "0"), tag(20, "0"), tag(30, "0")]; + let flip = Val::Flip(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), true); + for mut tags in [one(), [one(), vec![tag(70, "0")]].concat()] { + write_value(&mut tags, &flip); + let codes: Vec = tags.iter().map(|t| t.code).collect(); + assert_eq!(codes, [10, 20, 30, 10, 20, 30, 70]); + assert_eq!(tags.last().map(|t| t.value.as_str()), Some("1")); + } + } + #[test] fn a_value_record_listed_under_many_keys_is_copied_once() { // One large XRECORD named by many keys of a reference's value dictionary: the templates diff --git a/crates/doc/src/dynblock/grips.rs b/crates/doc/src/dynblock/grips.rs index 301d9ecad..cbc04775e 100644 --- a/crates/doc/src/dynblock/grips.rs +++ b/crates/doc/src/dynblock/grips.rs @@ -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 { @@ -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(p: &Vec2, s: S) -> Result { [p.x, p.y].serialize(s) } @@ -120,6 +166,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { }; // The grips the current visibility state shows (all of them without visibility states). let objects: HashMap = m.grip_objects.iter().copied().collect(); + let points: HashMap = m.grip_points.iter().copied().collect(); let mut shown_in_state: Option> = None; let mut visibility_node = None; for p in &m.parameters { @@ -171,6 +218,87 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { } } } + 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 { }); } } + // 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)) { diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 3465a9f94..8ab0a1420 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -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, - /// 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, 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 { 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 { o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::().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 { 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::(), 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 { - 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 { + 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 { + 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 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"); + } +} diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 832e0925f..c074ae289 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -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, + /// 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, } 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(), diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index a3f2e76b4..982f2f9bb 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -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 { + 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()) diff --git a/crates/doc/src/entity/fill.rs b/crates/doc/src/entity/fill.rs index cff172a71..7a7799a55 100644 --- a/crates/doc/src/entity/fill.rs +++ b/crates/doc/src/entity/fill.rs @@ -7,6 +7,11 @@ pub struct HatchLoop { pub vertices: Vec, #[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, /// 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")] diff --git a/crates/doc/src/entity/proxy.rs b/crates/doc/src/entity/proxy.rs new file mode 100644 index 000000000..e0b1eb1cf --- /dev/null +++ b/crates/doc/src/entity/proxy.rs @@ -0,0 +1,1411 @@ +//! The proxy graphics an ACAD_PROXY_ENTITY carries (DXF groups 92/160 and 310): the picture +//! the owning application left for programs that don't have it, drawn as AutoCAD draws it with +//! PROXYSHOW 1. The layout follows the Open Design Alliance's public DWG specification +//! ("Proxy Entity Graphics"): a header (total size, chunk count), then chunks of (size, type, +//! data), sizes in bytes including the 8-byte chunk header, all little-endian. +//! +//! The picture becomes ordinary, read-only entities: drawn and measured like the contents of a +//! block, with layer 0, ByBlock colour, linetype and lineweight standing for the proxy's own +//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight +//! polylines, materials) are skipped. + +use super::{Arc, Circle, Common, Ellipse, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown}; +use crate::RawTag; +use cadcraft_color::{Color, Rgb}; +use cadcraft_geom::{PolyVertex, Vec2, Vec3}; + +/// Bytes of proxy graphics read at most from one entity. +const MAX_BYTES: usize = 16 << 20; +/// Entities made at most from one entity's proxy graphics. +const MAX_ENTITIES: usize = 100_000; +/// Vertices read at most from one polyline or polygon chunk. +const MAX_VERTICES: usize = 1_000_000; +/// Matrices pushed at most. +const MAX_MATRICES: usize = 64; + +/// The table names proxy graphics refer to by index, in the order of the file's tables. +#[derive(Clone, Debug, Default)] +pub struct ProxyTables { + /// LAYER records in file order. + pub layers: Vec, + /// LTYPE records in file order, without ByBlock and ByLayer (indices count only the others). + pub linetypes: Vec, + /// Text styles (name, font file) in file order: a text chunk names its font, and the first + /// style with that font draws it. + pub styles: Vec<(String, String)>, +} + +impl Unknown { + /// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in + /// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size + /// group is the first after the `AcDbProxyEntity` subclass marker (from the start in a record + /// without one), so a 92 or 160 among the entity's own groups before it isn't taken for it. + /// An entity of another type CADCraft keeps as read holds them in its `AcDbEntity` part when + /// it was saved with a picture of itself (a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION, or an + /// object of another application; #3438). Empty for an entity without graphics and for one + /// whose data isn't hex. + pub fn proxy_graphics_bytes(&self) -> Vec { + let Some((at, size)) = self.graphics_size_group() else { return Vec::new() }; + // Reserve what the 310 groups hold, not what the size claims: a size far past the data + // would otherwise reserve up to MAX_BYTES for nothing. + let held: usize = self.tags.iter().skip(at + 1).take_while(|t| t.code == 310).map(|t| t.value.trim().len() / 2).sum(); + let mut out = Vec::with_capacity(size.min(held)); + for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) { + // Damaged data draws nothing rather than a picture cut at a guess. + if !push_hex(&mut out, &t.value) { + return Vec::new(); + } + if out.len() >= size { + break; + } + } + out.truncate(size); + out + } +} + +impl Unknown { + /// The `*D` block a dimension CADCraft keeps as read names (group 2 of its `AcDbDimension` + /// part): a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION. AutoCAD draws a dimension from that + /// block, so CADCraft draws it from there too, and saving keeps it (#3438, #1161). `None` + /// for other records. + pub fn dimension_block(&self) -> Option<&str> { + let m = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbDimension")?; + self.tags[m + 1..].iter().take_while(|t| t.code != 100).find(|t| t.code == 2).map(|t| t.value.trim()).filter(|n| !n.is_empty()) + } + + /// Where the proxy graphics size group (92, or 160 in newer files) is, and the size it gives + /// (at most [`MAX_BYTES`]): in an ACAD_PROXY_ENTITY the first after the `AcDbProxyEntity` + /// marker, in another kept entity the one in its `AcDbEntity` part. + fn graphics_size_group(&self) -> Option<(usize, usize)> { + let at = if self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") { + let from = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbProxyEntity").map_or(0, |m| m + 1); + self.tags.iter().skip(from).position(|t| t.code == 92 || t.code == 160).map(|i| from + i) + } else { + // The groups of the AcDbEntity subclass, up to the entity's own subclass marker. + self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbEntity").and_then(|m| { + let own = &self.tags[m + 1..]; + own.iter().take_while(|t| t.code != 100).position(|t| t.code == 92 || t.code == 160).map(|i| m + 1 + i) + }) + }?; + let size = self.tags.get(at).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(0).min(MAX_BYTES); + Some((at, size)) + } + + /// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned + /// into the written LAYER table `written`, by name; everything else as read. The name of an + /// index is the one the record's own decoded graphics draw on after it (so a proxy copied from + /// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no + /// drawn entity follows takes the name from the file's table `read` (see + /// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own + /// layer, as in a block); an index past the table, or one of a record without a name, stays + /// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups + /// that hold the declared size are read and rewritten. `None` when no index changes, or the + /// graphics aren't readable. + pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option> { + // Only a proxy entity's own graphics: a kept dimension draws from its block instead. + if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") { + return None; + } + let (at, size) = self.graphics_size_group()?; + let (mut bytes, mut groups) = (Vec::new(), Vec::new()); + for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) { + if bytes.len() >= size { + break; + } + let before = bytes.len(); + if !push_hex(&mut bytes, &self.tags[i].value) { + return None; + } + groups.push((i, bytes.len() - before)); + } + let end = size.min(bytes.len()); + // The ATTRIBUTE_LAYER chunks: where each index sits. + let mut refs: Vec<(usize, u32)> = Vec::new(); + let mut chunk = 8usize; + while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) { + let len = len as usize; + if len < 8 || chunk.saturating_add(len) > end { + break; + } + if kind == 16 + && let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8) + { + refs.push((chunk + 8, i)); + } + chunk += len; + } + if refs.is_empty() { + return None; + } + let indices: Vec = refs.iter().map(|r| r.1).collect(); + let learned = self.layers_by_index(&bytes[..end], &indices); + if read.is_empty() && learned.is_empty() { + return None; + } + // Each written name's first place, found once. + let mut place: std::collections::HashMap = std::collections::HashMap::new(); + for (p, n) in written.iter().enumerate() { + place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX)); + } + let zero = place.get("0").copied(); + let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX)); + let mut resolved: std::collections::HashMap = std::collections::HashMap::new(); + let mut changed = false; + for (offset, i) in refs { + let j = *resolved.entry(i).or_insert_with(|| { + let name = match learned.get(&i) { + Some(name) => name.as_deref(), + None => read.get(i as usize).map(String::as_str), + }; + match name.filter(|n| !n.is_empty()) { + Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i), + None if i >= past => i, + None => past, + } + }); + if j != i { + bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes()); + changed = true; + } + } + if !changed { + return None; + } + let mut tags = self.tags.clone(); + let mut from = 0; + for (g, n) in groups { + tags[g].value = bytes[from..from + n].iter().map(|b| format!("{b:02X}")).collect(); + from += n; + } + Some(tags) + } + + /// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in + /// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the + /// same entities in the same order, so each one's marker meets its real layer. `None` for an + /// index after which the graphics stay on the layer before (one past the table it was read + /// with). An index above 65,535 isn't named here (it resolves through the file's table, like + /// one no entity follows). Empty when the graphics don't match + /// (not decoded from these bytes); an index whose entities disagree is left out. + fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap> { + /// What the entities after an index say about it. + enum Seen { + /// They are on this layer, and the ones before them weren't. + Named(String), + /// They are on the same layer as the ones before them: the index keeps that layer, + /// or names it. + Kept(String), + /// It keeps the layer before (two kept observations on different layers). + Keeps, + } + const MAX: u32 = 65_535; + let mut out: std::collections::HashMap> = std::collections::HashMap::new(); + if self.graphics.is_empty() { + return out; + } + let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0); + let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() }; + let marked = proxy_entities(bytes, &markers, Handle(0)); + if marked.len() != self.graphics.len() { + return out; + } + let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b); + let mut seen: std::collections::HashMap = std::collections::HashMap::new(); + let mut conflict = std::collections::HashSet::new(); + let mut before: Option<(&str, &str)> = None; + for (m, g) in marked.iter().zip(&self.graphics) { + let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str()); + let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark); + let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real)); + before = Some((mark, real)); + let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::().ok()) else { continue }; + if !changed_here { + // The same marker on another real layer: an index in between (one past the table + // the marker decoding doesn't see as such) changed it, so this one can't be named. + if !kept { + conflict.insert(i); + } + continue; + } + let real = real.to_string(); + let merged = match (seen.remove(&i), kept) { + (None, false) => Some(Seen::Named(real)), + (None, true) => Some(Seen::Kept(real)), + (Some(Seen::Named(a) | Seen::Kept(a)), false) | (Some(Seen::Named(a)), true) if same(&a, &real) => Some(Seen::Named(a)), + (Some(Seen::Kept(a)), true) => Some(if same(&a, &real) { Seen::Kept(a) } else { Seen::Keeps }), + (Some(Seen::Keeps), true) => Some(Seen::Keeps), + _ => None, + }; + match merged { + Some(s) => { + seen.insert(i, s); + } + None => { + conflict.insert(i); + } + } + } + for (i, s) in seen { + if !conflict.contains(&i) { + out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None }); + } + } + out + } +} + +impl crate::Drawing { + /// Rename layer `old` to `new` where proxy graphics use it: in [`crate::Drawing::proxy_layers`], + /// so saving finds the layer under its new name, and in the decoded graphics, which draw on + /// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the + /// target, as its objects do) and LAYDEL with layer 0. + pub fn rename_proxy_layer(&mut self, old: &str, new: &str) { + for n in &mut self.proxy_layers { + if n.eq_ignore_ascii_case(old) { + *n = new.to_string(); + } + } + let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old))); + let fix = |e: &mut Entity| { + if let EntityKind::Unknown(u) = &mut e.kind { + for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) { + g.common.layer = new.to_string(); + } + } + }; + let mut stores: Vec<&mut crate::EntityStore> = vec![&mut self.model]; + stores.extend(self.layouts.iter_mut().map(|l| &mut l.entities)); + for b in self.blocks.values_mut() { + if b.entities.iter().any(|e| uses(e)) { + stores.push(&mut std::sync::Arc::make_mut(b).entities); + } + } + for store in stores { + let hs: Vec = store.iter().filter(|e| uses(e)).map(|e| e.handle).collect(); + for h in hs { + store.modify(h, fix); + } + } + } +} + +/// Append the bytes of hex string `s`. False on a character that isn't a hex digit. +fn push_hex(out: &mut Vec, s: &str) -> bool { + let digits: Vec = s.trim().bytes().collect(); + for pair in digits.chunks(2) { + let (Some(&hi), Some(&lo)) = (pair.first(), pair.get(1)) else { return false }; + let (Some(hi), Some(lo)) = ((hi as char).to_digit(16), (lo as char).to_digit(16)) else { return false }; + out.push((hi * 16 + lo) as u8); + } + true +} + +/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one +/// selects the proxy. +pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec { + let mut r = Decoder { + tables, + handle, + pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() }, + fill: false, + matrices: Vec::new(), + out: Vec::new(), + }; + let mut at = 8; + while let (Some(size), Some(kind)) = (u32_at(bytes, at), u32_at(bytes, at + 4)) { + let size = size as usize; + if size < 8 || r.out.len() >= MAX_ENTITIES { + break; + } + let Some(data) = bytes.get(at + 8..at.saturating_add(size)) else { break }; + r.chunk(kind, data); + at += size; + } + r.out +} + +struct Decoder<'a> { + tables: &'a ProxyTables, + handle: Handle, + /// Layer, colour, linetype and lineweight for the entities that follow. + pen: Common, + /// Whether polygons and circles that follow are filled (ATTRIBUTE_FILL). + fill: bool, + /// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4). + matrices: Vec<[f64; 12]>, + out: Vec, +} + +impl Decoder<'_> { + /// Decode one chunk of type `kind`: draw it, or change the pen for what follows. + fn chunk(&mut self, kind: u32, data: &[u8]) { + let mut b = Bytes { data, at: 0 }; + match kind { + // CIRCLE: centre, radius, normal. + 2 => { + if let (Some(c), Some(r)) = (b.point(), b.f64()) { + self.circle(c, r); + } + } + // CIRCLE_3P: three points on it. + 3 => { + if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) + && let Some(fit) = Fit3::through(p1, p2, p3) + { + self.circle_in(fit.center, fit.radius, fit.e1, fit.e2); + } + } + // CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal). + 4 => { + if let (Some(c), Some(r), Some(n), Some(v), Some(sweep)) = (b.point(), b.f64(), b.point(), b.point(), b.f64()) { + self.arc(c, r, n, v, sweep); + } + } + // CIRCULAR_ARC_3P: start, a point on the arc, end. + 5 => { + if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) { + self.arc_3p_local(p1, p2, p3); + } + } + // POLYLINE and POLYGON: a count, then the points; POLYLINE_WITH_NORMAL: a count, the + // points and a normal (the dimension lines of a LARGE_RADIAL_DIMENSION's picture). + 6 | 7 | 32 => { + let Some(n) = b.u32() else { return }; + let n = (n as usize).min(MAX_VERTICES); + let pts: Vec = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect(); + self.polyline(pts, kind == 7); + } + // TEXT: position, normal, direction, height, width factor, oblique, string. + 10 => { + if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) { + let s = b.string(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() }); + } + } + // TEXT2: position, normal, direction, string, length (the characters drawn), raw + // flag, height, width factor, oblique, tracking, five style flags, font, big font. + 11 => { + if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) { + let s = b.string(); + let s = first_chars(s, b.u32()); + b.skip(4); + if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) { + b.skip(8 + 20); + let font = b.string(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font }); + } + } + } + // UNICODE_TEXT: as TEXT with a UTF-16 string. + 36 => { + if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) { + let s = b.unicode(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() }); + } + } + // UNICODE_TEXT2: as TEXT2 with UTF-16 strings, and bold, italic, charset, pitch and + // the typeface before the font file. + 38 => { + if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) { + let s = b.unicode(); + let s = first_chars(s, b.u32()); + b.skip(4); + if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) { + b.skip(8 + 20 + 16); + let _typeface = b.unicode(); + let font = b.unicode(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font }); + } + } + } + // ATTRIBUTE_COLOR: ACI, 0 ByBlock, 256 ByLayer. + 14 => { + if let Some(c) = b.u32() { + self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256)); + } + } + // ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record + // without a name, leaves the layer. + 16 => { + if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) { + self.pen.layer = name.clone(); + } + } + // ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer; + // 32766 is ByBlock, 32767 and anything past the table ByLayer. + 18 => { + if let Some(i) = b.u32() { + self.pen.linetype = match i { + 32766 => "ByBlock".into(), + _ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()), + }; + } + } + // ATTRIBUTE_FILL: a trait like the colour, in force until the next one: 1 fills the + // polygons and circles that follow, 2 (and anything else) doesn't (AcGiFillType + // kAcGiFillAlways, kAcGiFillNever). + 20 => { + if let Some(f) = b.u32() { + self.fill = f == 1; + } + } + // ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte. + 22 => { + if let Some(v) = b.u32() { + self.pen.color = match v >> 24 { + 0xC0 => Color::ByLayer, + 0xC1 => Color::ByBlock, + 0xC2 => Color::True(Rgb::from_u32(v & 0x00FF_FFFF)), + 0xC3 => Color::from_aci((v & 0xFF) as i16), + _ => self.pen.color, + }; + } + } + // ATTRIBUTE_LINEWEIGHT: hundredths of a millimetre, or -1 ByLayer, -2 ByBlock, + // -3 the default. + 23 => { + if let Some(v) = b.u32() { + self.pen.lineweight = Lineweight::from_dxf(i16::try_from(v as i32).unwrap_or(-1)); + } + } + // ATTRIBUTE_LTSCALE. + 24 => { + if let Some(s) = b.f64().filter(|s| s.is_finite() && *s > 0.0) { + self.pen.ltscale = s; + } + } + // PUSH_MATRIX, PUSH_MATRIX2: a 4x4 model transform for what follows; POP_MATRIX. + 29 | 30 => { + let m: Vec = (0..16).map_while(|_| b.f64()).collect(); + if let Some(m) = m.get(..12).and_then(|m| <[f64; 12]>::try_from(m).ok()) + && m.iter().all(|x| x.is_finite()) + && self.matrices.len() < MAX_MATRICES + { + self.matrices.push(m); + } + } + 31 => { + self.matrices.pop(); + } + _ => {} + } + } + + /// Add an entity drawn with the current pen (up to [`MAX_ENTITIES`]). + fn push(&mut self, kind: EntityKind) { + if self.out.len() < MAX_ENTITIES { + self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind }); + } + } + + /// `p` through the pushed matrices, innermost first, in the XY plane. + fn xy(&self, p: Vec3) -> Vec2 { + let mut p = p; + for m in self.matrices.iter().rev() { + p = Vec3::new( + m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3], + m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7], + m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11], + ); + } + p.xy() + } + + /// How much the pushed matrices scale lengths (1 without any). + fn scale(&self) -> f64 { + self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product() + } + + /// Where the pushed matrices take `c` and the unit vectors `e1`, `e2` of a circle's plane: the + /// circle of radius 1 around `c` is drawn as `c' + u·cos a + v·sin a`. The vectors go through + /// the matrices' linear parts only, so a small scale isn't lost against a large translation. + fn axes(&self, c: Vec3, e1: Vec3, e2: Vec3) -> (Vec2, Vec2, Vec2) { + (self.xy(c), self.linear(e1), self.linear(e2)) + } + + /// Direction `v` through the pushed matrices' linear parts, innermost first, in the XY plane. + fn linear(&self, v: Vec3) -> Vec2 { + let mut v = v; + for m in self.matrices.iter().rev() { + v = Vec3::new(m[0] * v.x + m[1] * v.y + m[2] * v.z, m[4] * v.x + m[5] * v.y + m[6] * v.z, m[8] * v.x + m[9] * v.y + m[10] * v.z); + } + v.xy() + } + + /// A full circle around `c`, through the pushed matrices: an ellipse when they scale its + /// plane unevenly or shear it. While ATTRIBUTE_FILL is on, a solid hatch under it: AutoCAD + /// draws a filled shape's outline too, with its lineweight. + fn circle(&mut self, c: Vec3, r: f64) { + self.circle_in(c, r, X, Y); + } + + /// The circle of radius `r` around `c` in the plane of the unit vectors `e1` and `e2`, as + /// `circle` draws one in the chunk's XY plane. + fn circle_in(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3) { + let (at, u, v) = self.axes(c, e1, e2); + if !(r.is_finite() && r > 0.0 && at.is_finite()) { + return; + } + match round(u * r, v * r) { + Some(r) => { + if self.fill { + // Two half-circle arcs (bulge 1). + let side = |p: Vec2| PolyVertex { p, bulge: 1.0, start_width: 0.0, end_width: 0.0 }; + self.solid(vec![side(at + Vec2::new(r, 0.0)), side(at - Vec2::new(r, 0.0))]); + } + self.push(EntityKind::Circle(Circle { center: at.to3(0.0), radius: r })); + } + None => { + let Some(e) = ellipse(at, u * r, v * r, 0.0, std::f64::consts::TAU) else { + return self.edge_on(at, u * r, v * r, 0.0, std::f64::consts::TAU); + }; + if self.fill { + // Bulges draw circular arcs only: the fill follows the ellipse in 72 + // straight sides, finer than a plotted pixel at the sizes proxies use. + let side = |i: u32| { + let a = std::f64::consts::TAU * f64::from(i) / 72.0; + PolyVertex { p: at + u * (r * a.cos()) + v * (r * a.sin()), bulge: 0.0, start_width: 0.0, end_width: 0.0 } + }; + self.solid((0..72).map(side).collect()); + } + self.push(EntityKind::Ellipse(e)); + } + } + } + + /// An arc around `c` from the direction `start`, turned by `sweep` around `normal`. + fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) { + if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 { + return; + } + // The start point and the end point (the start vector turned by the sweep around the + // normal: clockwise in plan for a normal pointing down), through the matrices. + let dir = if normal.z < 0.0 { -1.0 } else { 1.0 }; + let a0 = start.y.atan2(start.x); + let a1 = a0 + dir * sweep; + if sweep.abs() >= std::f64::consts::TAU - 1e-9 { + return self.circle(c, r); + } + self.arc_between(c, r, X, Y, a0, a1); + } + + /// The arc of radius `r` around `c` from angle `a0` to `a1` (from `e1` towards `e2`, the unit + /// vectors of its plane), either way round, through the pushed matrices: an elliptical arc + /// when they don't keep it round. + fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) { + let (at, u, v) = self.axes(c, e1, e2); + let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin()); + if round(u * r, v * r).is_some() { + return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1)); + } + match ellipse(at, u * r, v * r, a0.min(a1), a0.max(a1)) { + Some(e) => self.push(EntityKind::Ellipse(e)), + None => self.edge_on(at, u * r, v * r, a0.min(a1), a0.max(a1)), + } + } + + /// A circle or arc `c + u·cos a + v·sin a` (`a` from `a0` to `a1`) seen edge-on: `u` and `v` + /// on one line, so it draws as the line between its two farthest points along it. + fn edge_on(&mut self, c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) { + use std::f64::consts::{PI, TAU}; + let d = if u.len() >= v.len() { u } else { v }; + if !(c.is_finite() && d.is_finite() && v.is_finite() && u.is_finite() && d.len() > 0.0) { + return; + } + let d = d * (1.0 / d.len()); + // Along d the point is at R·cos(a − φ): farthest out at φ and φ + π, where the sweep has them. + let phi = v.dot(d).atan2(u.dot(d)); + let inside = |a: f64| (a - a0).rem_euclid(TAU) <= a1 - a0; + let on = |a: f64| c + u * a.cos() + v * a.sin(); + let mut ends = [a0, a1, phi, phi + PI].into_iter().filter(|&a| a == a0 || a == a1 || inside(a)).map(on).map(|p| (p - c).dot(d)); + let first = ends.next().unwrap_or(0.0); + let (lo, hi) = ends.fold((first, first), |(lo, hi), t| (lo.min(t), hi.max(t))); + if hi > lo { + self.push(EntityKind::Line(Line { a: (c + d * lo).to3(0.0), b: (c + d * hi).to3(0.0) })); + } + } + + /// The arc from `p1` through `p2` to `p3`, chunk coordinates: fitted in the plane of the + /// three points and drawn through the pushed matrices, which may make it elliptical. + fn arc_3p_local(&mut self, p1: Vec3, p2: Vec3, p3: Vec3) { + if self.matrices.is_empty() && p1.z == p2.z && p2.z == p3.z { + return self.arc_3p(p1.xy(), p2.xy(), p3.xy()); + } + let Some(fit) = Fit3::through(p1, p2, p3) else { + return self.polyline(vec![self.xy(p1), self.xy(p3)], false); + }; + let (a1, a2, a3) = (fit.angle(p1), fit.angle(p2), fit.angle(p3)); + let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU); + // Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1. + let (from, sweep) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, ccw(a1, a3)) } else { (a3, ccw(a3, a1)) }; + self.arc_between(fit.center, fit.radius, fit.e1, fit.e2, from, from + sweep); + } + + /// The arc from `p1` through `p2` to `p3`. + fn arc_3p(&mut self, p1: Vec2, p2: Vec2, p3: Vec2) { + let Some((c, r)) = circle_through(p1, p2, p3) else { + return self.polyline(vec![p1, p3], false); + }; + let ang = |p: Vec2| (p.y - c.y).atan2(p.x - c.x); + let (a1, a2, a3) = (ang(p1), ang(p2), ang(p3)); + let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU); + // Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1. + let (start, end) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, a3) } else { (a3, a1) }; + self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end })); + } + + /// A polyline, or a closed polygon: on a solid hatch while ATTRIBUTE_FILL is on (the outline + /// is drawn too, as for a circle). + fn polyline(&mut self, pts: Vec, polygon: bool) { + if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() { + return; + } + if polygon && self.fill && pts.len() >= 3 { + let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect(); + self.solid(vertices); + } + match pts.as_slice() { + [a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })), + _ => { + let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect(); + self.push(EntityKind::LwPolyline(LwPolyline { vertices, closed: polygon, const_width: 0.0, elevation: 0.0, plinegen: false })); + } + } + } + + /// A solid hatch with the one boundary `vertices`. + fn solid(&mut self, vertices: Vec) { + // At the cap the fill gives way to the outline that follows it: a shape left with only + // its fill couldn't be picked or snapped to. + if self.out.len() + 1 >= MAX_ENTITIES { + return; + } + self.push(EntityKind::Hatch(Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + })); + } + + /// A single-line text, its style the first one whose font file the chunk names. + fn text(&mut self, t: TextChunk) { + let TextChunk { p, dir, height, width, oblique, value, font } = t; + let font = font.as_str(); + let height = height * self.scale(); + if !(height.is_finite() && height > 0.0) || value.is_empty() { + return; + } + let at = self.xy(p); + if !at.is_finite() { + return; + } + let towards = self.xy(p + dir) - at; + let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 }; + let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase(); + let style = self + .tables + .styles + .iter() + .find(|(_, f)| !font.is_empty() && stem(f) == stem(font)) + .map(|(n, _)| n.clone()) + .unwrap_or_else(|| "Standard".into()); + self.push(EntityKind::Text(Text { + insert: at.to3(0.0), + align_pt: None, + height, + value, + rotation, + width_factor: if width.is_finite() && width > 0.0 { width } else { 1.0 }, + oblique: if oblique.is_finite() { oblique } else { 0.0 }, + style, + halign: Default::default(), + valign: Default::default(), + })); + } +} + +/// The first `length` characters of `s`: a text chunk may carry more text than it draws (the +/// rest of a note, drawn by the chunks after it). No length, or one past the end, keeps it all. +fn first_chars(s: String, length: Option) -> String { + match length.map(|n| n as usize) { + Some(n) if n > 0 && n < s.chars().count() => s.chars().take(n).collect(), + _ => s, + } +} + +/// A text chunk: position, direction, height, width factor, oblique, string and font file. +struct TextChunk { + p: Vec3, + dir: Vec3, + height: f64, + width: f64, + oblique: f64, + value: String, + font: String, +} + +/// The radius of the circle with conjugate radii `u` and `v` when they are one: as long as each +/// other and at right angles (a matrix that turns, mirrors and scales evenly). +fn round(u: Vec2, v: Vec2) -> Option { + let (lu, lv) = (u.len(), v.len()); + let tol = 1e-9 * lu.max(lv); + ((lu - lv).abs() <= tol && u.dot(v).abs() <= tol * lu.max(lv) && lu.is_finite() && lu > 0.0).then_some(lu) +} + +/// The ellipse `c + u·cos a + v·sin a` for `a` from `a0` to `a1` (counter-clockwise in the +/// parameter): its axes from the conjugate radii `u` and `v`, the arc carried over to the +/// ellipse's own parameter (counter-clockwise from its major axis). +fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option { + use std::f64::consts::{FRAC_PI_2, TAU}; + // c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles. + let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2()); + let p = u * t.cos() + v * t.sin(); + let q = v * t.cos() - u * t.sin(); + // The ellipse turns counter-clockwise with its parameter only when q is p turned left; + // a mirroring matrix reverses it. + let mirrored = p.cross(q) < 0.0; + let q = if mirrored { -q } else { q }; + let (mut s0, mut s1) = if mirrored { (t - a1, t - a0) } else { (a0 - t, a1 - t) }; + // The major axis is the longer of p and q. + let (major, minor) = if q.len() > p.len() { + s0 -= FRAC_PI_2; + s1 -= FRAC_PI_2; + (q, p.len()) + } else { + (p, q.len()) + }; + let ratio = minor / major.len(); + if !(c.is_finite() && major.is_finite() && major.len() > 0.0 && ratio.is_finite() && ratio > 0.0) { + return None; + } + let full = (a1 - a0) >= TAU - 1e-9; + let (start, end) = if full { (0.0, TAU) } else { (s0.rem_euclid(TAU), s1.rem_euclid(TAU)) }; + Some(Ellipse { center: c.to3(0.0), major: major.to3(0.0), ratio, start, end }) +} + +/// The circle through three points (centre, radius), if they aren't on one line. +fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> { + cadcraft_geom::Circle::from_3_points(a, b, c).filter(|f| f.radius > 0.0).map(|f| (f.center, f.radius)) +} + +const X: Vec3 = Vec3 { x: 1.0, y: 0.0, z: 0.0 }; +const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 }; + +/// The circle through three points in space: its centre, radius and the unit vectors `e1`, `e2` +/// of its plane. For points of equal `z` they are X and Y, so angles are the chunk's. +struct Fit3 { + center: Vec3, + radius: f64, + e1: Vec3, + e2: Vec3, +} + +impl Fit3 { + /// The fit, if the points aren't on one line (relative to the triangle's size, so it holds at + /// any scale). + fn through(p1: Vec3, p2: Vec3, p3: Vec3) -> Option { + let (u, v) = (p2 - p1, p3 - p1); + let w = u.cross(v); + let w2 = w.dot(w); + if !(w2.is_finite() && w.len() > 1e-12 * (u.len() * v.len()) && w2 > 0.0) { + return None; + } + // The centre in point-relative coordinates: ((|u|² v − |v|² u) × w) / (2 |w|²). + let center = p1 + (v * u.dot(u) - u * v.dot(v)).cross(w) * (0.5 / w2); + let radius = (p1 - center).len(); + // The plane's normal towards +Z (which way the arc turns comes from the middle point), and + // X (or Y) laid into the plane. + let up = if w.z < 0.0 { -1.0 } else { 1.0 }; + let n = w * (up / w.len()); + let along = |a: Vec3| a - n * a.dot(n); + let e1 = if along(X).len() > 1e-6 { along(X).normalized() } else { along(Y).normalized() }; + let e2 = n.cross(e1); + (center.is_finite() && radius.is_finite() && radius > 0.0 && e2.is_finite()).then_some(Fit3 { center, radius, e1, e2 }) + } + + /// The angle of `p` around the centre, from `e1` towards `e2`. + fn angle(&self, p: Vec3) -> f64 { + let d = p - self.center; + d.dot(self.e2).atan2(d.dot(self.e1)) + } +} + +/// The little-endian u32 at `at`, if `bytes` holds one there. +fn u32_at(bytes: &[u8], at: usize) -> Option { + bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) +} + +/// A reader over one chunk's data. Strings are padded to four bytes. +struct Bytes<'a> { + data: &'a [u8], + at: usize, +} + +impl Bytes<'_> { + /// The next `n` bytes, if there are that many. + fn take(&mut self, n: usize) -> Option<&[u8]> { + let s = self.data.get(self.at..self.at.checked_add(n)?)?; + self.at += n; + Some(s) + } + /// Pass over `n` bytes (reads after the end then find nothing). + fn skip(&mut self, n: usize) { + self.at = self.at.saturating_add(n); + } + /// A little-endian u32. + fn u32(&mut self) -> Option { + self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) + } + /// A little-endian double. + fn f64(&mut self) -> Option { + self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes) + } + /// Three doubles, if all are finite. + fn point(&mut self) -> Option { + let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?); + (p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p) + } + /// Move on to the next multiple of four bytes, where padded strings end. + fn align(&mut self) { + self.at = self.at.saturating_add((4 - self.at % 4) % 4); + } + /// A zero-terminated string in the drawing's code page; bytes above 0x7F as Latin-1. + fn string(&mut self) -> String { + let rest = self.data.get(self.at..).unwrap_or_default(); + let end = rest.iter().position(|&c| c == 0).unwrap_or(rest.len()); + let s: String = rest.iter().take(end).map(|&c| c as char).collect(); + self.at += end + 1; + self.align(); + s + } + /// A UTF-16 string ended by a zero code unit. + fn unicode(&mut self) -> String { + let rest = self.data.get(self.at..).unwrap_or_default(); + let (pairs, _) = rest.as_chunks::<2>(); + let units: Vec = pairs.iter().map(|&p| u16::from_le_bytes(p)).take_while(|&u| u != 0).collect(); + self.at += units.len() * 2 + 2; + self.align(); + String::from_utf16_lossy(&units) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::RawTag; + + /// A chunk of type `kind`, its data padded to four bytes. + fn chunk(kind: u32, data: &[u8]) -> Vec { + let mut d = data.to_vec(); + d.resize(d.len().div_ceil(4) * 4, 0); + let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec(); + out.extend(kind.to_le_bytes()); + out.extend(d); + out + } + /// Proxy graphics: the header (total size, chunk count), then the chunks. + fn graphics(chunks: &[Vec]) -> Vec { + let body: Vec = chunks.concat(); + let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + out.extend((chunks.len() as u32).to_le_bytes()); + out.extend(body); + out + } + /// A point in the XY plane as three doubles. + fn pt(x: f64, y: f64) -> Vec { + [x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect() + } + /// Two layers, two linetypes and two text styles. + fn tables() -> ProxyTables { + ProxyTables { + layers: vec!["0".into(), "BALLOONS".into()], + linetypes: vec!["Continuous".into(), "DASHED".into()], + styles: vec![("Standard".into(), "txt".into()), ("ISO".into(), "isocp.shx".into())], + } + } + + /// A balloon as AutoCAD Mechanical stores one: layer, colour, a circle, the leader and the + /// number as TEXT2. + #[test] + fn a_balloon_becomes_circle_line_and_text() { + let mut text2 = pt(173.0, 112.0); + text2.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter())); + text2.extend(pt(1.0, 0.0)); + text2.extend(b"12\0\0"); + text2.extend(2i32.to_le_bytes()); + text2.extend(0i32.to_le_bytes()); + for v in [6.0f64, 1.0, 0.0, 0.0] { + text2.extend(v.to_le_bytes()); + } + text2.extend([0u8; 20]); + text2.extend(b"ISOCP.SHX\0\0\0\0\0"); + let mut circle = pt(175.0, 115.0); + circle.extend(6.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter())); + let mut leader = 2u32.to_le_bytes().to_vec(); + leader.extend(pt(170.0, 111.0)); + leader.extend(pt(150.0, 90.0)); + let g = graphics(&[chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text2)]); + let es = proxy_entities(&g, &tables(), Handle(0x35)); + assert_eq!(es.len(), 3); + assert!(es.iter().all(|e| e.handle == Handle(0x35) && e.common.layer == "BALLOONS" && e.common.color == Color::Index(1))); + assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(175.0, 115.0, 0.0) && c.radius == 6.0)); + assert!(matches!(&es[1].kind, EntityKind::Line(l) if l.b == Vec3::new(150.0, 90.0, 0.0))); + assert!(matches!(&es[2].kind, EntityKind::Text(t) if t.value == "12" && t.height == 6.0 && t.style == "ISO" && t.rotation == 0.0)); + } + + /// A TEXT2 chunk draws only as many characters as its length says. + #[test] + fn text2_draws_its_length() { + let text2 = |value: &[u8], length: i32| { + let mut t = pt(0.0, 0.0); + t.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + t.extend(pt(1.0, 0.0)); + t.extend(value); + t.extend(vec![0u8; 4 - value.len() % 4]); + t.extend(length.to_le_bytes()); + t.extend(1i32.to_le_bytes()); + for v in [2.5f64, 1.0, 0.0, 0.0] { + t.extend(v.to_le_bytes()); + } + t.extend([0u8; 20]); + t.extend(b"txt\0"); + let es = proxy_entities(&graphics(&[chunk(11, &t)]), &tables(), Handle(1)); + match es.first().map(|e| &e.kind) { + Some(EntityKind::Text(t)) => t.value.clone(), + other => panic!("{other:?}"), + } + }; + assert_eq!(text2(b"two lines\\Pof text", 9), "two lines"); + assert_eq!(text2(b"whole", 0), "whole"); + assert_eq!(text2(b"whole", 99), "whole"); + } + + /// Without layer and colour chunks the picture takes the proxy's own (layer 0, ByBlock). + #[test] + fn unset_traits_are_the_proxys() { + let mut leader = 3u32.to_le_bytes().to_vec(); + for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0)] { + leader.extend(pt(x, y)); + } + let es = proxy_entities( + &graphics(&[chunk(6, &leader), chunk(16, &u32::MAX.to_le_bytes()), chunk(18, &32766u32.to_le_bytes())]), + &tables(), + Handle(1), + ); + let e = es.first().expect("polyline"); + assert_eq!( + (e.common.layer.as_str(), e.common.color, e.common.linetype.as_str(), e.common.lineweight), + ("0", Color::ByBlock, "ByBlock", Lineweight::ByBlock) + ); + assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed)); + } + + /// ATTRIBUTE_FILL is a trait like the colour: 1 (kAcGiFillAlways) fills every polygon and + /// circle until a 2 (kAcGiFillNever) ends it, whatever is drawn in between. AutoCAD + /// Mechanical writes 2 before its balloons' circles and 1 before their arrowheads and dots. + #[test] + fn fill_is_a_trait_until_turned_off() { + let mut tri = 3u32.to_le_bytes().to_vec(); + for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] { + tri.extend(pt(x, y)); + } + let mut line = 2u32.to_le_bytes().to_vec(); + line.extend(pt(0.0, 0.0)); + line.extend(pt(1.0, 0.0)); + let mut dot = pt(5.0, 5.0); + dot.extend(0.5f64.to_le_bytes()); + dot.extend(pt(0.0, 0.0)); + let (on, off) = (chunk(20, &1u32.to_le_bytes()), chunk(20, &2u32.to_le_bytes())); + let es = proxy_entities( + &graphics(&[on, chunk(6, &line), chunk(7, &tri), chunk(2, &dot), chunk(7, &tri), off, chunk(7, &tri), chunk(2, &dot)]), + &tables(), + Handle(1), + ); + let kinds: Vec<&str> = es.iter().map(|e| e.kind.type_name()).collect(); + // A filled shape is a solid hatch with its outline on top. + assert_eq!(kinds, ["Line", "Hatch", "Polyline", "Hatch", "Circle", "Hatch", "Polyline", "Polyline", "Circle"]); + assert!(matches!(&es[1].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3)); + assert!(matches!(&es[2].kind, EntityKind::LwPolyline(p) if p.closed)); + // The filled circle: two half-circle arcs around its centre. + let disc: Vec<(Vec2, f64)> = match &es[3].kind { + EntityKind::Hatch(h) => h.loops[0].vertices.iter().map(|v| (v.p, v.bulge)).collect(), + other => panic!("{other:?}"), + }; + assert_eq!(disc, [(Vec2::new(5.5, 5.0), 1.0), (Vec2::new(4.5, 5.0), 1.0)]); + assert!(matches!(&es[6].kind, EntityKind::LwPolyline(p) if p.closed)); + } + + /// A circle or arc under a matrix that scales its plane unevenly is an ellipse, measured + /// and snapped as one; one that scales evenly stays a circle or arc. + #[test] + fn circles_and_arcs_under_an_uneven_matrix_are_ellipses() { + use std::f64::consts::{FRAC_PI_2, PI, TAU}; + let push = |sx: f64, sy: f64| { + let mut m = [0.0f64; 16]; + (m[0], m[5], m[10], m[15], m[3]) = (sx, sy, 1.0, 1.0, 10.0); + chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::>()) + }; + let mut circle = pt(0.0, 0.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let quarter = { + let mut a = pt(0.0, 0.0); + a.extend(1.0f64.to_le_bytes()); + a.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + a.extend(pt(1.0, 0.0)); + a.extend(FRAC_PI_2.to_le_bytes()); + a.extend(0u32.to_le_bytes()); + a + }; + // Three points of the same quarter arc, as CIRCULAR_ARC_3P gives them. + let h = std::f64::consts::FRAC_1_SQRT_2; + let quarter_3p: Vec = [pt(1.0, 0.0), pt(h, h), pt(0.0, 1.0)].concat(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + let ell = |e: &Entity| match &e.kind { + EntityKind::Ellipse(e) => (e.center, e.major, e.ratio, e.start, e.end), + other => panic!("{other:?}"), + }; + let es = proxy_entities(&graphics(&[push(2.0, 1.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1)); + let (c, major, ratio, start, end) = ell(&es[0]); + assert!(c == Vec3::new(10.0, 0.0, 0.0) && near(major.x.abs(), 2.0) && near(major.y, 0.0) && near(ratio, 0.5) && (start, end) == (0.0, TAU)); + for e in &es[1..] { + let (_, major, ratio, start, end) = ell(e); + // The major axis may point either way along x; the arc runs from (12, 0) to (10, 1). + let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin()); + assert!((at(start) - Vec2::new(12.0, 0.0)).len() < 1e-9 && (at(end) - Vec2::new(10.0, 1.0)).len() < 1e-9, "{start} {end}"); + assert!(near((end - start).rem_euclid(TAU), FRAC_PI_2)); + } + // Mirrored along x and stretched: the quarter arc runs from (10, 1) to (8, 0). + let es = proxy_entities(&graphics(&[push(-2.0, 1.0), chunk(4, &quarter)]), &tables(), Handle(1)); + let (_, major, ratio, start, end) = ell(&es[0]); + let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin()); + assert!((at(start) - Vec2::new(10.0, 1.0)).len() < 1e-9 && (at(end) - Vec2::new(8.0, 0.0)).len() < 1e-9, "{start} {end}"); + // A filled circle under it: a solid hatch along the ellipse, under the ellipse. + let fill = chunk(20, &1u32.to_le_bytes()); + let es = proxy_entities(&graphics(&[push(2.0, 1.0), fill, chunk(2, &circle)]), &tables(), Handle(1)); + match (&es[0].kind, &es[1].kind) { + (EntityKind::Hatch(h), EntityKind::Ellipse(_)) => { + let xs = h.loops[0].vertices.iter().map(|v| v.p.x); + let (lo, hi) = xs.fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x))); + assert!(near(lo, 8.0) && near(hi, 12.0), "{lo} {hi}"); + } + other => panic!("{other:?}"), + } + // Picked and snapped by the ellipse only, not the hatch's sides. + let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: es }; + let prims = EntityKind::Unknown(u).prims(); + assert!(matches!(prims.as_slice(), [crate::entity::Prim::Ellipse(_)]), "{prims:?}"); + // A tiny scale under a far translation keeps the circle: radius 1e8 at scale 1e-8 is 1. + let mut far = [0.0f64; 16]; + (far[0], far[5], far[10], far[15], far[3], far[7]) = (1e-8, 1e-8, 1.0, 1.0, 1e9, 1e9); + let far = chunk(29, &far.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let mut big = pt(0.0, 0.0); + big.extend(1e8f64.to_le_bytes()); + big.extend(pt(0.0, 0.0)); + let es = proxy_entities(&graphics(&[far, chunk(2, &big)]), &tables(), Handle(1)); + assert!(matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Circle(c) if (c.radius - 1.0).abs() < 1e-6)), "{es:?}"); + // Even scaling, mirrored or not, keeps circles and arcs. + let es = proxy_entities(&graphics(&[push(-3.0, 3.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1)); + assert!(matches!(&es[0].kind, EntityKind::Circle(c) if near(c.radius, 3.0))); + for e in &es[1..] { + let angle = |a: f64, b: f64| near((a - b).rem_euclid(TAU).min((b - a).rem_euclid(TAU)), 0.0); + assert!(matches!(&e.kind, EntityKind::Arc(a) if near(a.radius, 3.0) && angle(a.start, FRAC_PI_2) && angle(a.end, PI)), "{e:?}"); + } + } + + /// Three-point chunks are fitted in the plane of their points, then mapped: a circle across XY + /// turned into it, points far smaller than the scale that enlarges them, and circles and arcs + /// seen edge-on. + #[test] + fn three_point_chunks_fit_in_their_own_plane() { + use std::f64::consts::TAU; + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + let p3 = |p: [f64; 3]| p.iter().flat_map(|v| v.to_le_bytes()).collect::>(); + let mat = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let turn = mat([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + let across = [p3([0.0, 1.0, 0.0]), p3([0.0, 0.0, 1.0]), p3([0.0, -1.0, 0.0])].concat(); + let tiny = mat([1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1.0]); + let small = [p3([1e-7, 0.0, 0.0]), p3([0.0, 1e-7, 0.0]), p3([-1e-7, 0.0, 0.0])].concat(); + // The arc's half is the one through the middle point. + for (m, pts, mid) in [(turn, across.clone(), Vec2::new(1.0, 0.0)), (tiny, small, Vec2::new(0.0, 1.0))] { + let es = proxy_entities(&graphics(&[m, chunk(3, &pts), chunk(5, &pts)]), &tables(), Handle(1)); + assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center.xy().len() < 1e-9 && near(c.radius, 1.0)), "{es:?}"); + match &es[1].kind { + EntityKind::Arc(a) => { + let m = a.start + (a.end - a.start).rem_euclid(TAU) / 2.0; + assert!(near(a.radius, 1.0) && (Vec2::new(m.cos(), m.sin()) - mid).len() < 1e-9, "{a:?}"); + } + other => panic!("{other:?}"), + } + } + // Seen edge-on (in a vertical plane, no matrix) a circle or arc is a line over all it + // covers in plan: for the arc through (0, 1) from (0, 0.6) to (0, 0.6), beyond its ends. + let edge = |pts: Vec, kind: u32| match proxy_entities(&graphics(&[chunk(kind, &pts)]), &tables(), Handle(1)).as_slice() { + [Entity { kind: EntityKind::Line(l), .. }] => { + let (lo, hi) = (l.a.y.min(l.b.y), l.a.y.max(l.b.y)); + assert!(near(l.a.x, 0.0) && near(l.b.x, 0.0), "{l:?}"); + (lo, hi) + } + other => panic!("{other:?}"), + }; + let (lo, hi) = edge(across.clone(), 3); + assert!(near(lo, -1.0) && near(hi, 1.0)); + let (lo, hi) = edge(across, 5); + assert!(near(lo, -1.0) && near(hi, 1.0)); + let (lo, hi) = edge([p3([0.0, 0.6, 0.8]), p3([0.0, 1.0, 0.0]), p3([0.0, 0.6, -0.8])].concat(), 5); + assert!(near(lo, 0.6) && near(hi, 1.0), "{lo} {hi}"); + } + + /// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal, + /// which runs clockwise in plan (from 0° to -90°). + #[test] + fn arcs_follow_their_normal() { + let arc = |nz: f64| { + let mut a = pt(0.0, 0.0); + a.extend(2.0f64.to_le_bytes()); + a.extend([0.0f64, 0.0, nz].iter().flat_map(|v| v.to_le_bytes())); + a.extend(pt(1.0, 0.0)); + a.extend(std::f64::consts::FRAC_PI_2.to_le_bytes()); + a.extend(0u32.to_le_bytes()); + match proxy_entities(&graphics(&[chunk(4, &a)]), &tables(), Handle(1)).first().map(|e| e.kind.clone()) { + Some(EntityKind::Arc(a)) => (a.start, a.end, a.radius), + other => panic!("{other:?}"), + } + }; + let (s, e, r) = arc(1.0); + assert!(s.abs() < 1e-9 && (e - std::f64::consts::FRAC_PI_2).abs() < 1e-9 && (r - 2.0).abs() < 1e-9); + let (s, e, _) = arc(-1.0); + assert!((s + std::f64::consts::FRAC_PI_2).abs() < 1e-9 && e.abs() < 1e-9, "{s} {e}"); + } + + #[test] + fn a_pushed_matrix_moves_what_follows_until_popped() { + let mut m = [0.0f64; 16]; + (m[0], m[5], m[10], m[15], m[3], m[7]) = (2.0, 2.0, 1.0, 1.0, 100.0, 50.0); + let mut circle = pt(1.0, 1.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let push: Vec = m.iter().flat_map(|v| v.to_le_bytes()).collect(); + let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(31, &[]), chunk(2, &circle)]), &tables(), Handle(1)); + assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(102.0, 52.0, 0.0) && c.radius == 2.0)); + assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0)); + } + + /// A finite matrix can still move a point past the largest float: a circle or a text that + /// would land there is left out, as a polyline is, so no infinity reaches the extents. + #[test] + fn what_a_matrix_moves_out_of_range_is_left_out() { + let mut m = [0.0f64; 16]; + (m[0], m[5], m[10], m[15], m[3]) = (1.0, 1.0, 1.0, 1.0, 1.7e308); + let push: Vec = m.iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut circle = pt(1e308, 0.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let mut text = pt(1e308, 0.0); + text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + text.extend(pt(1.0, 0.0)); + text.extend(b"far\0"); + text.extend(0i32.to_le_bytes()); + text.extend(1i32.to_le_bytes()); + for v in [2.5f64, 1.0, 0.0, 0.0] { + text.extend(v.to_le_bytes()); + } + text.extend([0u8; 20]); + text.extend(b"txt\0"); + let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(11, &text)]), &tables(), Handle(1)); + assert!(es.is_empty(), "{es:?}"); + // The same text without the matrix is drawn: the chunk itself is sound. + assert_eq!(proxy_entities(&graphics(&[chunk(11, &text)]), &tables(), Handle(1)).len(), 1); + } + + #[test] + fn the_bytes_come_from_the_310_groups_after_the_size() { + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let u = Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: vec![tag(90, "498"), tag(92, "5"), tag(310, "0102"), tag(310, "030405FF"), tag(93, "0")], + graphics: Vec::new(), + }; + assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]); + let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() }; + assert!(other.proxy_graphics_bytes().is_empty()); + let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u.clone() }; + assert!(bad.proxy_graphics_bytes().is_empty()); + // The size group is the first after the AcDbProxyEntity marker: a 160 or 92 before it + // belongs to the entity's common data. + let marked = Unknown { + tags: vec![ + tag(100, "AcDbEntity"), + tag(160, "2"), + tag(310, "EEEE"), + tag(100, "AcDbProxyEntity"), + tag(90, "498"), + tag(92, "3"), + tag(310, "010203"), + ], + ..u.clone() + }; + assert_eq!(marked.proxy_graphics_bytes(), [1, 2, 3]); + // A size far past the data gives the data there is. + let short = Unknown { tags: vec![tag(92, "16000000"), tag(310, "0102")], ..u }; + assert_eq!(short.proxy_graphics_bytes(), [1, 2]); + } + + /// Another entity saved with a picture of itself (a LARGE_RADIAL_DIMENSION) holds it in its + /// AcDbEntity part; a 92 among its own groups after that isn't taken for it. Its dimension + /// lines are POLYLINE_WITH_NORMAL chunks (type 32). + #[test] + fn a_kept_entity_draws_the_picture_in_its_acdbentity_part() { + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let mut line = 2u32.to_le_bytes().to_vec(); + line.extend(pt(250.0, 150.0)); + line.extend(pt(290.0, 190.0)); + line.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + let g = graphics(&[chunk(32, &line)]); + let hex: String = g.iter().map(|b| format!("{b:02X}")).collect(); + let size = g.len().to_string(); + let u = Unknown { + dxf_type: "LARGE_RADIAL_DIMENSION".into(), + tags: vec![ + tag(100, "AcDbEntity"), + tag(8, "0"), + tag(92, &size), + tag(310, &hex), + tag(100, "AcDbDimension"), + tag(2, "*D1"), + tag(100, "AcDbRadialDimensionLarge"), + tag(40, "0.785398"), + ], + graphics: Vec::new(), + }; + assert_eq!(u.proxy_graphics_bytes(), g); + let es = proxy_entities(&u.proxy_graphics_bytes(), &tables(), Handle(1)); + assert!( + matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Line(l) if l.a == Vec3::new(250.0, 150.0, 0.0) && l.b == Vec3::new(290.0, 190.0, 0.0))) + ); + // Without graphics in the AcDbEntity part, a 92 in the entity's own data is not one. + let own = Unknown { tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbSomething"), tag(92, "4"), tag(310, "01020304")], ..u }; + assert!(own.proxy_graphics_bytes().is_empty()); + } + + /// Saving renames the layer indices by name into the written table, reading only the 310 + /// groups the declared size needs: a damaged group after them doesn't stop it. + #[test] + fn layer_indices_follow_the_written_table() { + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let mut circle = pt(0.0, 0.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]); + let hex: String = g.iter().map(|b| format!("{b:02X}")).collect(); + let read: Vec = ["0", "A", "B", "C"].map(String::from).to_vec(); + let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() }; + let u = Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex), tag(310, "GG")], + graphics: proxy_entities(&g, &tables, Handle(1)), + }; + assert_eq!(u.graphics[0].common.layer, "B"); + let written: Vec = ["0", "B", "C"].map(String::from).to_vec(); + let tags = u.with_proxy_layers(&read, &written).expect("remapped"); + let again = Unknown { tags, ..u.clone() }; + assert_eq!( + proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer, + "B" + ); + assert_eq!(again.tags[3].value, "GG", "the group after the graphics is kept as read"); + } + + /// An index whose graphics stay on the layer before (99 here, past the table) doesn't make + /// the index before it (3) look contradictory when that one comes again; an index above + /// 65,535 isn't named (it resolves through the file's table), and the others still are. + #[test] + fn indices_are_named_around_kept_layers_and_huge_indices() { + let mut circle = pt(0.0, 0.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let read: Vec = ["0", "A", "C", "B"].map(String::from).to_vec(); + let tables = ProxyTables { layers: read, ..ProxyTables::default() }; + let named = |indices: &[u32]| { + let mut chunks = Vec::new(); + for &i in indices { + chunks.push(chunk(16, &i.to_le_bytes())); + chunks.push(chunk(2, &circle)); + } + let g = graphics(&chunks); + let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) }; + let mut learned: Vec<(u32, Option)> = u.layers_by_index(&g, indices).into_iter().collect(); + learned.sort(); + learned + }; + assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]); + assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]); + // Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4 + // keeps A): both circles follow index 4 in the marker decoding, on different layers. + let g = graphics(&[ + chunk(16, &4u32.to_le_bytes()), + chunk(2, &circle), + chunk(16, &1u32.to_le_bytes()), + chunk(16, &4u32.to_le_bytes()), + chunk(2, &circle), + ]); + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let hex: String = g.iter().map(|b| format!("{b:02X}")).collect(); + let u = Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)], + graphics: proxy_entities(&g, &tables, Handle(1)), + }; + assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::>(), ["0", "A"]); + assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named"); + // Saved with the same table, nothing changes, so both circles stay where they are. + assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none()); + } + + /// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and + /// never panic. + #[test] + fn hostile_graphics_do_not_panic() { + let mut huge = u32::MAX.to_le_bytes().to_vec(); + huge.extend(pt(1.0, 1.0)); + let mut nan = pt(f64::NAN, 0.0); + nan.extend(1.0f64.to_le_bytes()); + let cases: Vec> = vec![ + Vec::new(), + vec![0; 7], + graphics(&[chunk(6, &huge)]), + graphics(&[chunk(2, &nan)]), + graphics(&[chunk(11, &[0xFF; 30])]), + graphics(&[chunk(38, &[0x41; 77])]), + graphics(&[chunk(29, &[1; 40])]), + graphics(&[chunk(31, &[]), chunk(31, &[])]), + [graphics(&[chunk(2, &pt(0.0, 0.0))]), vec![0xFF; 9]].concat(), + { + let mut g = graphics(&[]); + g.extend(4u32.to_le_bytes()); + g.extend(2u32.to_le_bytes()); + g + }, + { + let mut g = graphics(&[]); + g.extend(1_000u32.to_le_bytes()); + g.extend(2u32.to_le_bytes()); + g + }, + ]; + for g in cases { + let _ = proxy_entities(&g, &tables(), Handle(1)); + } + } +} diff --git a/crates/doc/src/entity/region.rs b/crates/doc/src/entity/region.rs index 8c63b43bf..18dedef11 100644 --- a/crates/doc/src/entity/region.rs +++ b/crates/doc/src/entity/region.rs @@ -37,7 +37,7 @@ pub struct RegionProps { impl Region { /// A region bounded by one closed loop. pub fn from_loop(vertices: Vec) -> 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 { @@ -170,7 +170,7 @@ mod tests { let mut vertices: Vec = (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] diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 9f29c07b6..a17b8ebd6 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -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| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let frame = |tags: Vec| 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 diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 6feb9eeb8..07ecbf724 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -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>, + /// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types. pub classes: Vec>, /// Classes retain every source position, including duplicate names. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ee17f1fca..386fca347 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -111,6 +111,8 @@ pub struct Drawing { pub mline_styles: Vec, pub blocks: BTreeMap>, pub model: EntityStore, + /// Model layout's page setup, or the default extents-to-fit setup for a new drawing. + pub model_page: Option, pub layouts: Vec, /// 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, } 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(), } } diff --git a/crates/doc/src/store.rs b/crates/doc/src/store.rs index 00b04970e..1b26a0514 100644 --- a/crates/doc/src/store.rs +++ b/crates/doc/src/store.rs @@ -57,6 +57,10 @@ impl EntityStore { pub fn iter(&self) -> impl Iterator> + '_ { 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> + '_ { + self.chunks.iter().rev().flat_map(|c| c.items.iter().rev()) + } pub fn handles(&self) -> Vec { 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::>(), [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)); diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index 8ae080f59..b6b192ee9 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -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>, 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, + /// 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 { diff --git a/crates/engine/src/cmd/annotate/common.rs b/crates/engine/src/cmd/annotate/common.rs index 37f943f7c..a7cac71dc 100644 --- a/crates/engine/src/cmd/annotate/common.rs +++ b/crates/engine/src/cmd/annotate/common.rs @@ -46,7 +46,7 @@ pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, 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 { let mut k = k; @@ -74,8 +74,10 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result { 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) -> EntityKind { diff --git a/crates/engine/src/cmd/annotate/edit.rs b/crates/engine/src/cmd/annotate/edit.rs index 38f02005f..bfb1a5502 100644 --- a/crates/engine/src/cmd/annotate/edit.rs +++ b/crates/engine/src/cmd/annotate/edit.rs @@ -161,17 +161,22 @@ pub(super) fn run_dimtedit(s: &mut Session, p: &Value) -> Result { } /// 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 { let base = hex_param(p, "base").ok_or_else(|| bad("dimspace", "`base` dimension is required"))?; let hs: Vec = 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 { } /// 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, diff --git a/crates/engine/src/cmd/annotate/tests.rs b/crates/engine/src/cmd/annotate/tests.rs index 98e064958..ee6f9e814 100644 --- a/crates/engine/src/cmd/annotate/tests.rs +++ b/crates/engine/src/cmd/annotate/tests.rs @@ -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(); diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 4a0ba3ae6..79d9b3ece 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -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 { .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 { 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 { .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, + /// Base point picked (mode "base") — `None` for an "objects" pick. + pub base: Option, +} + +fn run_wblockpick(_s: &mut Session, _p: &Value) -> Result { + 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 { + 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, /// 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, /// 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 { + // 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; diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index dbc92b7fb..29a953aee 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -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 { .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 { _ => 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 { 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 { - 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 { + let half = TICK_PX * s.pixel_size(); + let mut out: Vec = 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 { + 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 { 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(()) } } diff --git a/crates/engine/src/cmd/blocks/purge.rs b/crates/engine/src/cmd/blocks/purge.rs index 4ef6946c7..5a86c9b79 100644 --- a/crates/engine/src/cmd/blocks/purge.rs +++ b/crates/engine/src/cmd/blocks/purge.rs @@ -171,6 +171,8 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet { 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 { 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)), _ => {} } } diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 1b480185c..22ff1dcb6 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -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 { 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)))?, }; diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 364258dcf..121db217c 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -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}; diff --git a/crates/engine/src/cmd/draw/line_pline.rs b/crates/engine/src/cmd/draw/line_pline.rs index 9f6df5fa6..1a0ecc377 100644 --- a/crates/engine/src/cmd/draw/line_pline.rs +++ b/crates/engine/src/cmd/draw/line_pline.rs @@ -39,6 +39,10 @@ fn vertex_value(v: &Value) -> Option { 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 { + Ok(s.doc()?.header.f64("ELEVATION", 0.0)) +} + pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result { 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 { 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, + 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 { + 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" }; diff --git a/crates/engine/src/cmd/draw/spline.rs b/crates/engine/src/cmd/draw/spline.rs index 498f1a9f2..5b45b4d23 100644 --- a/crates/engine/src/cmd/draw/spline.rs +++ b/crates/engine/src/cmd/draw/spline.rs @@ -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 { if p.get("object").is_some() { @@ -26,11 +26,11 @@ pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result { } #[derive(Default)] -pub(super) struct SplineM { +pub(in crate::cmd) struct SplineM { pts: Vec, asking_method: bool, - /// `Method` > `CV` hands over to the control-vertex machine (`spline.cv`). - delegate: Option>, + /// Both entry points share Method and Object; CV handles its own points and degree. + cv: Option, /// 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 { 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 { - 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 { - 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(); diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 24007bc91..84842c5cb 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -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), } diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 003edf2a8..9a494d701 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -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::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)") diff --git a/crates/engine/src/cmd/draw2/curves3d.rs b/crates/engine/src/cmd/draw2/curves3d.rs index faad5442c..86b061053 100644 --- a/crates/engine/src/cmd/draw2/curves3d.rs +++ b/crates/engine/src/cmd/draw2/curves3d.rs @@ -284,7 +284,7 @@ pub(super) fn run_spline_cv(s: &mut Session, p: &Value) -> Result { } #[derive(Default)] -pub(super) struct SplineCvM { +pub(in crate::cmd) struct SplineCvM { pts: Vec, degree: Option, asking_degree: bool, @@ -312,7 +312,9 @@ impl Interactive for SplineCvM { fn input(&mut self, s: &mut Session, i: Input) -> Result { 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) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c5084eccb..9c4dc4c41 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -593,7 +593,9 @@ fn run_select(s: &mut Session, p: &Value) -> Result { } 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() diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index dd8512386..690d0be5e 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -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())) } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 25914fd4d..8b0922f2b 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -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; + +static DWG_COMPAT_LOST: OnceLock = 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 { @@ -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 } diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 7a1771374..38e659165 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -232,7 +232,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { 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> { 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> { && 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 { 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 => {} diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index 2daca7d22..7a3e90e77 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -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> { // 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 { - 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>> = paths.iter().map(|_| None).collect(); @@ -224,6 +225,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec, + /// 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> { + 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 { 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 { - 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> { + 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"); + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 6077e8ef6..b3bd61e0c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -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 { Ok(json!({ "layers": layers, "states": d.layer_states.iter().map(|st| st.name.clone()).collect::>() })) } -/// 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 { 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 Result { } } 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 { 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(); diff --git a/crates/engine/src/cmd/layer/merge.rs b/crates/engine/src/cmd/layer/merge.rs index de8c31800..16d2ce276 100644 --- a/crates/engine/src/cmd/layer/merge.rs +++ b/crates/engine/src/cmd/layer/merge.rs @@ -175,6 +175,10 @@ pub(super) fn run_laymrg(s: &mut Session, p: &Value) -> Result { 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 { 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")); diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index e1931a66c..157e2a36c 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -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 { diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 009a95281..65060770d 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -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) -> Option { @@ -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 { 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 { 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 { 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); } } diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index df43f782c..6225517da 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -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> { + 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> { @@ -151,6 +175,7 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } +/// Validate MIRROR parameters and apply the reflection, optionally replacing the source entities. pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result { 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 { 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::>() })) } diff --git a/crates/engine/src/cmd/qselect.rs b/crates/engine/src/cmd/qselect.rs index 236fb89c2..d3aeb35d8 100644 --- a/crates/engine/src/cmd/qselect.rs +++ b/crates/engine/src/cmd/qselect.rs @@ -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> { 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 { diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index acbe0f36f..19651b2fa 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -238,6 +238,7 @@ pub const NO_FILES: &[&str] = &[ "hatchedit", "hatchgenerateboundary", "hatchpick", + "wblockpick", "overkill", "block", "-block", diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index b0c1a1bca..77e1fc8bd 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -170,13 +170,16 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option { match index { diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 978683441..2d8cd628d 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -92,6 +92,15 @@ impl Interactive for Guarded { Vec::new() }) } + fn live_value(&self, s: &Session, cursor: Vec2) -> Option { + 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 { if self.broken.get().is_some() { return None; @@ -128,6 +137,15 @@ impl Interactive for Guarded { None }) } + fn attribute_entry(&self) -> Option { + 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)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b136a898b..9d166db09 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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, @@ -90,11 +103,20 @@ pub struct Session { pub running: Option, /// 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, @@ -158,6 +180,8 @@ pub struct Session { lisp_last: Option>, /// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks). pub hatch_picks: Option, + /// What the last WBLOCKPICK kept (the Write Block dialog's picks). + pub wblock_picks: Option, /// 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, diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index d4f5d10d5..2743341e6 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -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, diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 61a537729..69ee83466 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -70,7 +70,9 @@ fn items(p: &PickSet) -> Vec { /// 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) -> Result { if a.is_empty() { if ctx.s.running.is_some() { @@ -91,7 +93,7 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec) -> Result { } 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) -> Result 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 { 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 { + 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 { 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 { + 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, + /// 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) -> 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 { + 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 = (0..self.rows.len()).map(value).collect(); + let verify: Vec = 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 { diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 4e615a4f2..bd6772f26 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -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, diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 56403f8fa..fef9443b2 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -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> { + 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> { } } +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 { + 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 { - 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)> + 'a>; -pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> 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 { + 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 { + // 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 { + 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, 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| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let frame = + |tags: Vec| 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) -> 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}"); + } + } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f465b7a55..c140e6646 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -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; diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index 68a5e532b..c0455b731 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -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 != ' '); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 74a09aa27..c242971a3 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -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 { + 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 { 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 { + 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. diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 2e25131bf..094944138 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -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, } } } diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index e9d6f1914..f913dcee4 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -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, ) -> Option<(Vec, Vec)> { - 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)> { - 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, ) -> Option<(Vec<(u32, Vec2)>, Vec)> { 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 { + 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, probe: Vec2) -> Option { + 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(); diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 10888f5cf..f4607bed5 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -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); diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index c171f4b8f..01950ae5b 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -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), ]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 205faa273..d7113abfe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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::::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"); diff --git a/crates/engine/tests/clipboard.rs b/crates/engine/tests/clipboard.rs index b9eeff317..6fc1ca808 100644 --- a/crates/engine/tests/clipboard.rs +++ b/crates/engine/tests/clipboard.rs @@ -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; } diff --git a/crates/engine/tests/dimassoc_mode.rs b/crates/engine/tests/dimassoc_mode.rs new file mode 100644 index 000000000..306b2453c --- /dev/null +++ b/crates/engine/tests/dimassoc_mode.rs @@ -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); +} diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs index e7064c354..404406268 100644 --- a/crates/engine/tests/image_attach.rs +++ b/crates/engine/tests/image_attach.rs @@ -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}"); diff --git a/crates/engine/tests/it/attrib_modes.rs b/crates/engine/tests/it/attrib_modes.rs index 65238823a..260f842c9 100644 --- a/crates/engine/tests/it/attrib_modes.rs +++ b/crates/engine/tests/it/attrib_modes.rs @@ -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::>(), [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"); +} diff --git a/crates/engine/tests/it/dim_baseline_spacing.rs b/crates/engine/tests/it/dim_baseline_spacing.rs index 78fb14c94..13063e89f 100644 --- a/crates/engine/tests/it/dim_baseline_spacing.rs +++ b/crates/engine/tests/it/dim_baseline_spacing.rs @@ -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}"); } diff --git a/crates/engine/tests/it/dynamic_grips.rs b/crates/engine/tests/it/dynamic_grips.rs index 75ed1b787..7f48d8528 100644 --- a/crates/engine/tests/it/dynamic_grips.rs +++ b/crates/engine/tests/it/dynamic_grips.rs @@ -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); +} diff --git a/crates/engine/tests/it/hatch_assoc.rs b/crates/engine/tests/it/hatch_assoc.rs index ac73c27ed..368dd0bdd 100644 --- a/crates/engine/tests/it/hatch_assoc.rs +++ b/crates/engine/tests/it/hatch_assoc.rs @@ -144,6 +144,26 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() { assert!(!hatch(&s, &h).associative); } +#[test] +fn imported_boundary_flags_survive_refill_and_copy() { + let mut session = Session::new(); + let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap()); + let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap()); + session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| { + if let EntityKind::Hatch(hatch) = &mut entity.kind { + hatch.loops[0].boundary_flags = Some(7); + } + }); + let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags; + session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap(); + assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected); + let count = session.doc().unwrap().model.len(); + session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap(); + let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap(); + let EntityKind::Hatch(copied) = ©.kind else { panic!("not a hatch") }; + assert_eq!(copied.loops[0].boundary_flags, expected); +} + #[test] fn non_associative_hatch_keeps_no_sources() { let mut s = Session::new(); @@ -166,7 +186,10 @@ fn hostile_sources_never_panic() { let k = EntityKind::Hatch(Hatch { pattern: "ANSI31".into(), solid: false, - loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }], + loops: vec![ + HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() }, + HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources }, + ], scale: 1.0, angle: 0.0, associative: true, diff --git a/crates/engine/tests/it/insert_attrib_entry.rs b/crates/engine/tests/it/insert_attrib_entry.rs new file mode 100644 index 000000000..a4974b79b --- /dev/null +++ b/crates/engine/tests/it/insert_attrib_entry.rs @@ -0,0 +1,425 @@ +//! INSERT and the attribute modes (gap F17): Preset and constant attributes take their values +//! without asking, ATTREQ 0 gives every attribute its default, ATTDIA 0 asks at the command line +//! (a Verify attribute's value again once every value is in) and ATTDIA 1 (the default) asks for +//! the values all at once in the Edit Attributes dialog (`Session::attribute_entry`), typed +//! answers still working. The JSON form never asks. ATTREQ and ATTDIA are user settings, as in +//! AutoCAD (DWG keeps them in its header only before R2000). + +use std::sync::Arc; + +use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Handle, Text}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::{AttribAsk, Input, Origin, Session}; +use serde_json::json; + +fn def(tag: &str, prompt: &str, default: &str, y: f64, constant: bool, modes: AttribModes) -> Attrib { + Attrib { + tag: tag.into(), + text: Text { + insert: Vec3::new(0.0, y, 0.0), + align_pt: None, + height: 1.0, + value: default.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }, + invisible: false, + constant, + prompt: prompt.into(), + props: Default::default(), + multiline: None, + modes, + } +} + +/// Block T with the definitions A (Verify), B (Preset), C (plain) and D (constant); ATTREQ and +/// ATTDIA as given (their defaults, ATTREQ 1 and ATTDIA 1, otherwise). +fn session(attreq: Option, attdia: Option) -> Session { + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let mut b = Block::new("T"); + let none = AttribModes::default(); + for a in [ + def("A", "First", "1", 2.0, false, AttribModes { verify: true, ..none }), + def("B", "Second", "two", 4.0, false, AttribModes { preset: true, ..none }), + def("C", "Third", "3", 6.0, false, none), + def("D", "", "fixed", 8.0, true, none), + ] { + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(a))); + } + d.blocks.insert("T".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "attribs", None); + if let Some(v) = attreq { + s.settings.attreq = v; + } + if let Some(v) = attdia { + s.settings.attdia = v; + } + s +} + +/// Start INSERT of T at 100,0 and answer the scale and rotation prompts. +fn insert_up_to_the_attributes(s: &mut Session) { + s.start("insert").unwrap(); + s.cmdline("T").unwrap(); + s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap(); + s.input(Input::Enter).unwrap(); // X scale 1 + s.input(Input::Enter).unwrap(); // Y scale = X + s.input(Input::Enter).unwrap(); // rotation 0 +} + +/// The attribute values of the last block reference, in order. +fn values(s: &Session) -> Vec<(String, String)> { + let d = s.doc().unwrap(); + let Some(EntityKind::Insert(i)) = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Insert(_))).last().map(|e| e.kind.clone()) else { + panic!("no block reference") + }; + i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(t, v)| (t.to_string(), v.to_string())).collect() +} + +#[test] +fn a_fresh_session_reads_attdia_1() { + // AutoCAD 2026's ATTDIA page: Type Integer, Saved in Registry, Initial value 1. + let mut s = session(None, None); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1); + assert!(s.settings.attdia); +} + +#[test] +fn typed_insert_asks_verify_again_and_skips_preset_and_constant() { + // ATTDIA 0 set explicitly, so the command line asks. + let mut s = session(Some(true), Some(false)); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 0); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTREQ" })).unwrap()["value"], 1); + insert_up_to_the_attributes(&mut s); + assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog"); + assert_eq!(s.prompt_text(), "INSERT First <1>:", "A first"); + s.input(Input::Text("10".into())).unwrap(); + assert_eq!(s.prompt_text(), "INSERT Third <3>:", "B is Preset: not asked"); + s.input(Input::Enter).unwrap(); // C takes its default + // Then the Verify attributes, with the values typed. + assert_eq!(s.prompt_text(), "INSERT First <10>:"); + s.input(Input::Text("11".into())).unwrap(); // the value typed at Verify replaces it + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "11"), ("B", "two"), ("C", "3")])); + + // Enter at Verify keeps the value given; Enter at A takes its default, verified. + insert_up_to_the_attributes(&mut s); + s.input(Input::Enter).unwrap(); + s.input(Input::Text("c".into())).unwrap(); + assert_eq!(s.prompt_text(), "INSERT First <1>:"); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "c")])); + + // A script answers in turn too. + s.script("-INSERT T 0,50 1 1 0\na\nc\nz\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "z"), ("B", "two"), ("C", "c")])); +} + +#[test] +fn a_point_does_not_answer_an_attribute_prompt() { + // A canvas click reaches INSERT as Input::Point while a text-only attribute prompt waits. + // It is no answer: the prompt stays, and only Enter keeps the default. + let mut s = session(Some(true), Some(false)); + insert_up_to_the_attributes(&mut s); + assert_eq!(s.prompt_text(), "INSERT First <1>:"); + s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap(); + assert_eq!(s.prompt_text(), "INSERT First <1>:", "the click did not take A's default"); + assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog"); + s.input(Input::Text("10".into())).unwrap(); + assert_eq!(s.prompt_text(), "INSERT Third <3>:", "A was answered by the typed text"); + s.input(Input::Enter).unwrap(); // C takes its default + assert_eq!(s.prompt_text(), "INSERT First <10>:", "then A's Verify"); + s.input(Input::Enter).unwrap(); // Verify keeps the value typed + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "10"), ("B", "two"), ("C", "3")])); +} + +#[test] +fn attreq_0_gives_every_attribute_its_default() { + let mut s = session(Some(false), None); + insert_up_to_the_attributes(&mut s); + assert!(s.running.is_none(), "no attribute prompt: {}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "3")])); + // SETVAR changes it. + s.execute("setvar", &json!({ "name": "ATTREQ", "value": 1 })).unwrap(); + s.execute("setvar", &json!({ "name": "ATTDIA", "value": 0 })).unwrap(); + insert_up_to_the_attributes(&mut s); + assert_eq!(s.prompt_text(), "INSERT First <1>:"); +} + +#[test] +fn attdia_1_asks_for_every_value_at_once_and_typed_answers_still_work() { + let mut s = session(None, None); + s.execute("setvar", &json!({ "name": "ATTDIA", "value": 1 })).unwrap(); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1); + s.start("insert").unwrap(); + s.cmdline("T").unwrap(); + assert!(s.attribute_entry().is_none(), "not before the attribute prompts"); + s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap(); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + let e = s.attribute_entry().expect("the dialog's rows"); + assert_eq!(e.block, "T"); + let ask = + |tag: &str, prompt: &str, default: &str, verify: bool| AttribAsk { tag: tag.into(), prompt: prompt.into(), default: default.into(), verify }; + assert_eq!(e.rows, vec![ask("A", "First", "1", true), ask("C", "Third", "3", false)]); + // The dialog's OK: every value, then the Verify attribute's again. + let answers = e.answers(&["x".into(), String::new()]); + assert_eq!(answers, ["x", "", "x"]); + for a in answers { + s.input(Input::Text(a)).unwrap(); + } + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "x"), ("B", "two"), ("C", "")])); + + // Typed instead: the dialog goes away after the first answer. + insert_up_to_the_attributes(&mut s); + assert!(s.attribute_entry().is_some()); + s.input(Input::Text("typed".into())).unwrap(); + assert!(s.attribute_entry().is_none()); + s.input(Input::Enter).unwrap(); // C takes its default + s.input(Input::Enter).unwrap(); // Verify keeps the value typed + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "typed"), ("B", "two"), ("C", "3")])); + + // Cancel from the dialog inserts nothing. + let before = s.doc().unwrap().model.len(); + insert_up_to_the_attributes(&mut s); + s.cancel(); + assert!(s.running.is_none()); + assert_eq!(s.doc().unwrap().model.len(), before); +} + +#[test] +fn json_insert_never_asks_whatever_attreq_and_attdia_say() { + for (req, dia) in [(false, false), (true, true)] { + let mut s = session(Some(req), Some(dia)); + let r = s.execute("insert", &json!({ "name": "T", "at": [0, 0], "attribs": { "a": "given", "B": "preset given" } })).unwrap(); + assert!(r["handle"].is_string()); + assert!(s.running.is_none() && s.attribute_entry().is_none()); + assert_eq!(values(&s), pairs(&[("A", "given"), ("B", "preset given"), ("C", "3")])); + } +} + +#[test] +fn hostile_values_never_panic() { + let mut s = session(None, Some(true)); + insert_up_to_the_attributes(&mut s); + let e = s.attribute_entry().expect("asks"); + // Too few answers take the defaults, too many are ignored. + assert_eq!(e.answers(&[]), ["1", "3", "1"]); + assert_eq!(e.answers(&["p".into(), "q".into(), "r".into()]), ["p", "q", "p"]); + s.cancel(); + for bad in [json!(2), json!(-1), json!("x"), json!(null), json!(1.5)] { + assert!(s.execute("setvar", &json!({ "name": "ATTDIA", "value": bad })).is_err(), "{bad}"); + assert!(s.execute("setvar", &json!({ "name": "ATTREQ", "value": bad })).is_err(), "{bad}"); + } + assert!(s.settings.attdia && s.settings.attreq, "a refused value changes nothing"); + // An INSERT of a block with only Preset and constant attributes asks nothing. + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let mut b = Block::new("P"); + let h: Handle = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(def("P", "p", "v", 0.0, false, AttribModes { preset: true, ..AttribModes::default() })))); + d.blocks.insert("P".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "preset", None); + s.script("-INSERT P 0,0 1 1 0\n").unwrap(); + assert!(s.running.is_none() && s.attribute_entry().is_none()); + assert_eq!(values(&s), pairs(&[("P", "v")])); +} + +#[test] +fn a_script_never_asks_in_the_dialog() { + // A script cannot click a dialog: ATTDIA 1 keeps its prompts at the command line, even when + // the script ends with INSERT still waiting for the first attribute. + let mut s = session(None, Some(true)); + s.script("-INSERT T 0,50 1 1 0\n").unwrap(); + assert_eq!(s.prompt_text(), "INSERT First <1>:", "INSERT still waits after the script"); + assert!(s.attribute_entry().is_none(), "a scripted INSERT never opens the dialog"); + // The command the script started keeps answering at the command line. + s.input(Input::Text("a".into())).unwrap(); + s.input(Input::Text("c".into())).unwrap(); + s.input(Input::Text("a".into())).unwrap(); // A's Verify + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")])); + // A typed INSERT with ATTDIA 1 still asks in the dialog. + insert_up_to_the_attributes(&mut s); + assert!(s.attribute_entry().is_some(), "a typed INSERT asks in the dialog"); +} + +#[test] +fn a_lisp_insert_never_asks_in_the_dialog() { + // (command "-INSERT" …) runs INSERT outside Session::script: the routine cannot click a + // dialog, and it finishes before the first attribute answer. + let mut s = session(None, Some(true)); + let r = s.execute("lisp", &json!({ "code": "(command \"-INSERT\" \"T\" \"0,50\" 1 1 0)" })).unwrap(); + assert!(r.get("error").is_none(), "{r}"); + assert_eq!(s.prompt_text(), "INSERT First <1>:", "INSERT waits at the command line"); + assert!(s.attribute_entry().is_none(), "a LISP-started INSERT never opens the dialog"); + // The command keeps answering at the command line after the routine ended. + s.input(Input::Text("a".into())).unwrap(); + s.input(Input::Text("c".into())).unwrap(); + s.input(Input::Text("a".into())).unwrap(); // A's Verify + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")])); + // A typed INSERT with ATTDIA 1 asks in the dialog again. + insert_up_to_the_attributes(&mut s); + assert!(s.attribute_entry().is_some(), "a typed INSERT asks in the dialog"); + s.cancel(); + + // A LISP expression typed at the command line is the same program: no dialog. + s.cmdline("(command \"-INSERT\" \"T\" \"0,60\" 1 1 0)").unwrap(); + assert_eq!(s.prompt_text(), "INSERT First <1>:"); + assert!(s.attribute_entry().is_none(), "a typed (command …) never opens the dialog"); + s.cancel(); +} + +/// A routine that types a command into a running LINE: `(command "LINE" "0,0" spelling …)`. +/// `extra` answers MINSERT's grid, and the arguments after it answer the attribute prompts. +fn lisp_token_replaces_line(spelling: &str, extra: &str) -> Session { + let mut s = session(None, Some(true)); + let code = format!("(command \"LINE\" \"0,0\" \"{spelling}\" \"T\" \"0,50\" 1 1 0{extra})"); + let r = s.execute("lisp", &json!({ "code": code })).unwrap(); + assert!(r.get("error").is_none(), "{spelling}: {r}"); + s +} + +/// Answer the attribute prompts the routine's INSERT left waiting, as the person at the +/// command line would. +fn answer_the_routines_insert(s: &mut Session) { + s.input(Input::Text("a".into())).unwrap(); + s.input(Input::Text("c".into())).unwrap(); + s.input(Input::Text("a".into())).unwrap(); // A's Verify + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")])); +} + +#[test] +fn a_lisp_insert_token_replacing_a_command_never_asks_in_the_dialog() { + // The token reaches the typed-input path while LINE runs, not the idle start: the INSERT + // that replaces LINE is still the routine's, so ATTDIA 1 opens no dialog nobody can click. + let mut s = lisp_token_replaces_line("'-INSERT", ""); + assert_eq!(s.prompt_text(), "INSERT First <1>:", "asked at the command line"); + assert!(s.attribute_entry().is_none(), "a LISP token never opens the dialog"); + // The command keeps answering at the command line after the routine ended. + answer_the_routines_insert(&mut s); +} + +#[test] +fn a_lisp_minsert_token_replacing_a_command_never_asks_in_the_dialog() { + let mut s = lisp_token_replaces_line("'MINSERT", " 1 1"); + assert_eq!(s.prompt_text(), "MINSERT First <1>:", "asked at the command line"); + assert!(s.attribute_entry().is_none(), "a LISP token never opens the dialog"); + answer_the_routines_insert(&mut s); +} + +#[test] +fn a_person_typing_a_transparent_insert_still_asks_in_the_dialog() { + // The tokens the routine feeds above, typed by a person: the INSERT that replaces LINE is + // theirs, so ATTDIA 1 asks in the dialog. + let mut s = session(None, Some(true)); + s.cmdline("LINE 0,0 '-INSERT T 0,50 1 1 0").unwrap(); + assert!(s.running.is_some(), "{}", s.prompt_text()); + assert!(s.attribute_entry().is_some(), "a typed transparent INSERT asks in the dialog"); + s.cancel(); +} + +/// A person typing `'NAME T …` while a routine waits in `(command "LINE" "0,0" pause)` +/// cancels it; the routine's `*error*` handler then starts a LINE of its own. The handler's +/// command is the program's, and it must not take the origin or number of the person's start. +/// `extra` answers MINSERT's rows and columns. +fn person_replaces_paused_lisp(spelling: &str, extra: &str) -> Session { + let mut s = session(None, Some(true)); + s.cmdline("(defun *error* (msg) (command \"LINE\" \"1,1\" \"2,2\" \"\"))").unwrap(); + s.cmdline("(command \"LINE\" \"0,0\" pause)").unwrap(); + assert!(s.running.is_some(), "the routine's LINE waits for the person: {}", s.prompt_text()); + // The person replaces the waiting routine with their own command. + s.cmdline(&format!("'{spelling} T 0,50 1 1 0{extra}")).unwrap(); + assert!(s.running.is_some(), "{}", s.prompt_text()); + // The handler's LINE is the only one drawn: the paused LINE was cancelled at its first + // point, and the handler's own command ran as the program's (nobody typed 1,1 or 2,2). + let lines: Vec<(Vec2, Vec2)> = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some((l.a.xy(), l.b.xy())), + _ => None, + }) + .collect(); + assert_eq!(lines, vec![(Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], "the error handler's LINE is drawn, and the paused one added nothing"); + s +} + +#[test] +fn a_person_replacing_paused_lisp_keeps_their_insert_dialog() { + let s = person_replaces_paused_lisp("-INSERT", ""); + assert_eq!(s.command_origin(), Origin::Person, "the person's INSERT is not the handler's command"); + let e = s.attribute_entry().expect("ATTDIA 1: the person's INSERT asks in the dialog"); + // The handler's LINE finished as a command of its own; the INSERT's answers belong to a + // later number, so the dialog a cancelled command left behind is not taken. + assert_eq!(s.last_finished.map(|(command, _)| command), Some(e.command.wrapping_sub(1)), "the handler's LINE keeps its own number"); +} + +#[test] +fn a_person_replacing_paused_lisp_keeps_their_minsert_dialog() { + let s = person_replaces_paused_lisp("MINSERT", " 1 1"); + assert_eq!(s.command_origin(), Origin::Person, "the person's MINSERT is not the handler's command"); + let e = s.attribute_entry().expect("ATTDIA 1: the person's MINSERT asks in the dialog"); + assert_eq!(s.last_finished.map(|(command, _)| command), Some(e.command.wrapping_sub(1)), "the handler's LINE keeps its own number"); +} + +#[test] +fn an_entry_belongs_to_the_drawing_and_command_that_asked() { + let mut s = session(None, Some(true)); + insert_up_to_the_attributes(&mut s); + let first = s.attribute_entry().expect("asks"); + assert_eq!(first.drawing, s.state().unwrap().uid); + assert_eq!(first.command, s.commands_started); + // Asked again in a later frame: the same owner. + assert_eq!(s.attribute_entry().map(|e| (e.drawing, e.command)), Some((first.drawing, first.command))); + // Cancelled and started again: a new number, so the old dialog's draft is not taken. + s.cancel(); + insert_up_to_the_attributes(&mut s); + let second = s.attribute_entry().expect("asks again"); + assert_eq!(second.block, "T"); + assert_ne!((second.drawing, second.command), (first.drawing, first.command)); + // Another drawing's INSERT is another owner too. + let mut other = session(None, Some(true)); + insert_up_to_the_attributes(&mut other); + let third = other.attribute_entry().expect("asks there"); + assert_eq!(third.drawing, other.state().unwrap().uid); + assert_ne!(third.drawing, first.drawing); +} + +#[test] +fn two_definitions_with_one_tag_are_both_asked_once() { + // INSERT counted its answers by tag: the second X was asked for ever. + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let mut b = Block::new("DUP"); + for (prompt, y) in [("first", 0.0), ("second", 2.0)] { + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(def("X", prompt, "d", y, false, AttribModes::default())))); + } + d.blocks.insert("DUP".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "dup", None); + s.settings.attdia = false; + s.script("-INSERT DUP 0,0 1 1 0\na\nb\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s).len(), 2); +} diff --git a/crates/engine/tests/it/kept_dimension_snaps.rs b/crates/engine/tests/it/kept_dimension_snaps.rs new file mode 100644 index 000000000..d97ad2b0f --- /dev/null +++ b/crates/engine/tests/it/kept_dimension_snaps.rs @@ -0,0 +1,44 @@ +//! A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` block through +//! a reference in its graphics (#3438); object snaps reach the objects inside that block. + +use cadcraft_engine::doc::Space; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::snap::{self, mode}; + +#[test] +fn a_kept_dimension_snaps_to_its_blocks_objects() { + // The block's base point isn't the origin; its line is where the dimension draws it. + let dxf = "0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\n*D1\n70\n1\n10\n100\n20\n50\n3\n*D1\n0\nLINE\n8\n0\n10\n110\n20\n60\n11\n120\n21\n70\n0\nENDBLK\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLARGE_RADIAL_DIMENSION\n5\n41\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D1\n0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read"); + let at = |p: Vec2, m: u32| snap::osnap(&d, &Space::Model, p + Vec2::new(0.02, -0.01), 0.1, m, None, false).map(|h| (h.point, h.mode)); + let end = Vec2::new(120.0, 70.0); + assert!(at(end, mode::END).is_some_and(|(p, m)| m == mode::END && p.dist(end) < 1e-9), "{:?}", at(end, mode::END)); + let mid = Vec2::new(115.0, 65.0); + assert!(at(mid, mode::MID).is_some_and(|(p, m)| m == mode::MID && p.dist(mid) < 1e-9), "{:?}", at(mid, mode::MID)); +} + +/// A DIMENSION inside a block snaps to the objects of its own `*D` block, as it is drawn; so does +/// one moved by an older AutoCAD (group 12), translated by the move as the renderer draws it. +#[test] +fn dimensions_in_blocks_snap_to_their_blocks_objects() { + let dim = |handle: &str, offset: (f64, f64)| { + format!( + "0\nDIMENSION\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D2\n10\n5\n20\n7\n30\n0\n11\n5\n21\n8\n31\n0\n12\n{}\n22\n{}\n32\n0\n70\n1\n100\nAcDbAlignedDimension\n13\n0\n23\n7\n33\n0\n14\n10\n24\n7\n34\n0\n", + offset.0, offset.1 + ) + }; + let dxf = format!( + "0\nSECTION\n2\nBLOCKS\n\ +0\nBLOCK\n8\n0\n2\n*D2\n70\n1\n10\n0\n20\n0\n3\n*D2\n0\nLINE\n8\n0\n10\n0\n20\n7\n11\n10\n21\n7\n0\nENDBLK\n\ +0\nBLOCK\n8\n0\n2\nNEST\n70\n0\n10\n0\n20\n0\n3\nNEST\n{}0\nENDBLK\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nINSERT\n5\n70\n8\n0\n2\nNEST\n10\n100\n20\n0\n{}0\nENDSEC\n0\nEOF\n", + dim("60", (0.0, 0.0)), + dim("61", (0.0, 50.0)), + ); + let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read"); + let at = |p: Vec2, m: u32| snap::osnap(&d, &Space::Model, p + Vec2::new(0.02, -0.01), 0.1, m, None, false).map(|h| (h.point, h.mode)); + for (p, m) in [(Vec2::new(110.0, 7.0), mode::END), (Vec2::new(105.0, 7.0), mode::MID), (Vec2::new(10.0, 57.0), mode::END)] { + assert!(at(p, m).is_some_and(|(q, k)| k == m && q.dist(p) < 1e-9), "{p:?}: {:?}", at(p, m)); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2f3f9630d..042907eb8 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -76,12 +76,14 @@ mod hidden_grip_targets; mod inquiry_keywords; mod inquiry_variables; mod inquiry_z; +mod insert_attrib_entry; mod insert_attribute_prompts; mod insert_enter; mod insert_prompts; mod isometric; mod join_close; mod json_param_validation; +mod kept_dimension_snaps; mod layer_cmdline; mod layer_merge_delete; mod layer_state_cmdline; @@ -106,6 +108,7 @@ mod mocoro; mod modify_curves; mod mtext_columns; mod mtext_options; +mod mtext_ortho; mod multiline_attributes; mod named_viewports; mod named_views; @@ -133,6 +136,7 @@ mod properties_set_locked; mod properties_set_text_dims; mod props_bad_lineweight; mod props_insert_scale_attribs; +mod purge_kept_dimension_blocks; mod purge_mlinestyles; mod purge_prompts; mod qdim; @@ -146,6 +150,7 @@ mod refedit; mod region; mod rename_cmdline; mod rotate_reference; +mod rotation_grip_input; mod scale_offset_z; mod select_keywords; mod select_similar; diff --git a/crates/engine/tests/it/mtext_ortho.rs b/crates/engine/tests/it/mtext_ortho.rs new file mode 100644 index 000000000..1d4084ed6 --- /dev/null +++ b/crates/engine/tests/it/mtext_ortho.rs @@ -0,0 +1,157 @@ +//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388). + +use cadcraft_doc::{EntityKind, MText}; +use cadcraft_engine::snap::tracking::CursorQuery; +use cadcraft_engine::{Input, Session}; +use cadcraft_geom::{Bounds2, Vec2}; +use serde_json::json; + +/// Move the cursor to `raw` at the current prompt, as the canvas does. +fn hover(s: &mut Session, raw: Vec2) -> Vec2 { + let p = s.current_prompt().unwrap(); + let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false }; + let c = s.snap_cursor(raw, &q).point; + s.cursor = c; + c +} + +fn session(ortho: bool) -> Session { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap(); + s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap(); + s +} + +fn last_mtext(s: &Session) -> MText { + match s.doc().unwrap().model.last().map(|e| e.kind.clone()) { + Some(EntityKind::MText(t)) => t, + k => panic!("no mtext: {k:?}"), + } +} + +/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds, +/// in-place editor box `(insert, width)` and created entity `(insert, width)`. +fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) { + let mut s = session(ortho); + s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!(p.message, "Specify opposite corner"); + assert!(p.corner, "MTEXT opposite corner ignores ortho"); + let c = hover(&mut s, second); + assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}"); + let mut pv = Bounds2::EMPTY; + for e in s.preview(c) { + pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0)); + } + s.input(Input::Point(c)).unwrap(); + let ed = s.editing_mtext().unwrap(); + s.input(Input::Text("Hello".to_string())).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message)); + let t = last_mtext(&s); + assert_eq!(t.contents, "Hello"); + ((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width)) +} + +#[test] +fn mtext_opposite_corner_ignores_ortho() { + let cases = [ + // Wide box (dx > dy) + (Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0), + // Tall box (dy > dx) + (Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0), + // Opposite quadrant (negative dx and dy) + (Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0), + ]; + for (first, second, min, max, insert, width) in cases { + let on = click_mtext(true, first, second); + assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0); + assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1); + assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2); + let off = click_mtext(false, first, second); + assert_eq!(off, on, "ortho changes nothing"); + } +} + +#[test] +fn mtext_coordinate_and_direct_distance_input_with_ortho() { + let mut s = session(true); + // Absolute coordinate input for the opposite corner. + s.cmdline("mtext 0,0").unwrap(); + s.cmdline("10,3").unwrap(); + let ed = s.editing_mtext().unwrap(); + assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9)); + assert!((ed.width - 10.0).abs() < 1e-9); + s.input(Input::Text("Abs".to_string())).unwrap(); + s.input(Input::Enter).unwrap(); + let t = last_mtext(&s); + assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9)); + assert!((t.width - 10.0).abs() < 1e-9); + + // Relative coordinate input for the opposite corner. + s.cmdline("mtext 2,3").unwrap(); + s.cmdline("@4,9").unwrap(); + let ed = s.editing_mtext().unwrap(); + assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9)); + assert!((ed.width - 4.0).abs() < 1e-9); + s.input(Input::Text("Rel".to_string())).unwrap(); + s.input(Input::Enter).unwrap(); + let t = last_mtext(&s); + assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9)); + assert!((t.width - 4.0).abs() < 1e-9); + + // Direct distance entry goes toward the cursor rather than along an axis. + s.cmdline("mtext 0,0").unwrap(); + let c = hover(&mut s, Vec2::new(3.0, 4.0)); + assert!(c.near(Vec2::new(3.0, 4.0), 1e-9)); + s.cmdline("5").unwrap(); + let ed = s.editing_mtext().unwrap(); + assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9)); + assert!((ed.width - 3.0).abs() < 1e-9); + s.input(Input::Text("Dir".to_string())).unwrap(); + s.input(Input::Enter).unwrap(); + let t = last_mtext(&s); + assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9)); + assert!((t.width - 3.0).abs() < 1e-9); +} + +#[test] +fn mtext_escape_cancels_cleanly_with_ortho() { + let mut s = session(true); + // Cancel at the opposite-corner prompt. + s.cmdline("mtext 0,0").unwrap(); + let c = hover(&mut s, Vec2::new(10.0, 3.0)); + assert!(c.near(Vec2::new(10.0, 3.0), 1e-9)); + s.cancel(); + assert!(s.current_prompt().is_none()); + assert!(s.editing_mtext().is_none()); + assert!(s.doc().unwrap().model.is_empty()); + + // Cancel after picking the opposite corner (at the text prompt). + s.cmdline("mtext 0,0").unwrap(); + let c = hover(&mut s, Vec2::new(10.0, 3.0)); + s.input(Input::Point(c)).unwrap(); + assert!(s.editing_mtext().is_some()); + s.cancel(); + assert!(s.current_prompt().is_none()); + assert!(s.editing_mtext().is_none()); + assert!(s.doc().unwrap().model.is_empty()); +} + +#[test] +fn line_and_pline_still_obey_ortho() { + let mut s = session(true); + s.cmdline("line 0,0").unwrap(); + let p = s.current_prompt().unwrap(); + assert!(!p.corner, "LINE next point is constrained by ortho"); + let c = hover(&mut s, Vec2::new(10.0, 3.0)); + assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}"); + s.cancel(); + + s.cmdline("pline 0,0").unwrap(); + let p = s.current_prompt().unwrap(); + assert!(!p.corner, "PLINE next point is constrained by ortho"); + let c = hover(&mut s, Vec2::new(3.0, 10.0)); + assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}"); + s.cancel(); +} diff --git a/crates/engine/tests/it/purge_kept_dimension_blocks.rs b/crates/engine/tests/it/purge_kept_dimension_blocks.rs new file mode 100644 index 000000000..1a370386f --- /dev/null +++ b/crates/engine/tests/it/purge_kept_dimension_blocks.rs @@ -0,0 +1,31 @@ +//! PURGE keeps the `*D` block a dimension kept as read names (LARGE_RADIAL_DIMENSION, +//! ARC_DIMENSION): the dimension draws it, and AutoCAD needs it to read the file (#3438, #1161). + +use std::sync::Arc; + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Block, Common, Entity, EntityKind, Handle, Line, RawTag, Space, Unknown}; +use cadcraft_engine::geom::Vec3; +use serde_json::json; + +#[test] +fn purge_keeps_the_block_a_kept_dimension_names() { + let mut s = Session::new(); + let d = s.doc_mut().unwrap(); + for name in ["*D1", "*D2"] { + let mut b = Block::new(name); + b.entities.push(Entity::new(Handle(0x9000), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) }))); + d.blocks.insert(name.into(), Arc::new(b)); + } + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let dim = Unknown { + dxf_type: "ARC_DIMENSION".into(), + tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbDimension"), tag(2, "*D1"), tag(100, "AcDbArcDimension")], + graphics: Vec::new(), + }; + d.add(&Space::Model, Common::default(), EntityKind::Unknown(dim)).unwrap(); + s.execute("purge", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("*D1").is_some(), "the kept dimension's block stays"); + assert!(d.block("*D2").is_none(), "an unused one goes"); +} diff --git a/crates/engine/tests/it/rotation_grip_input.rs b/crates/engine/tests/it/rotation_grip_input.rs new file mode 100644 index 000000000..ed2d49f47 --- /dev/null +++ b/crates/engine/tests/it/rotation_grip_input.rs @@ -0,0 +1,44 @@ +//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box, +//! holding the angle the cursor would give as Properties will show it. The drawing is the +//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::Handle; +use cadcraft_engine::doc::dynblock::GripPart; +use cadcraft_engine::geom::Vec2; +use serde_json::json; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// A session with Symbol and a reference to it at (100, 100). +fn session() -> (Session, Handle) { + let src = include_str!("../../../io/tests/data/dynblock_symbol.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, "symbol", None); + let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap(); + (s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap()) +} + +#[test] +fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() { + let (mut s, h) = session(); + s.start_dyn_grip(h, 15, GripPart::End).unwrap(); + assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt()); + // The grip is at (102, 100); straight above the base is a quarter turn. + assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°")); + assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°")); + // Nothing is changed by looking. + let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap(); + let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone(); + assert_eq!(angle, json!("0")); +} diff --git a/crates/engine/tests/it/spline_degree.rs b/crates/engine/tests/it/spline_degree.rs index 31193d6cb..5be6b9ebc 100644 --- a/crates/engine/tests/it/spline_degree.rs +++ b/crates/engine/tests/it/spline_degree.rs @@ -30,3 +30,19 @@ fn programmatic_spline_control_count_is_limited() { s.execute("spline", &json!({ "control": control(20_000) })).unwrap(); assert_eq!(s.doc().unwrap().model.len(), 1); } + +#[test] +fn cv_degree_prompt_retries_a_fractional_degree() { + for command in ["spline.cv d", "spline m cv d"] { + let mut s = Session::new(); + s.cmdline(command).unwrap(); + let degree_prompt = s.current_prompt().unwrap(); + assert!(degree_prompt.accept.number); + s.cmdline("2.5").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, degree_prompt.message, "{command}"); + s.cmdline("2 0,0 1,1 2,0 3,1").unwrap(); + s.input(cadcraft_engine::Input::Enter).unwrap(); + let d = s.doc().unwrap(); + assert!(matches!(&d.model.iter().last().unwrap().kind, EntityKind::Spline(sp) if sp.degree == 2)); + } +} diff --git a/crates/engine/tests/it/spline_options.rs b/crates/engine/tests/it/spline_options.rs index a9cc52ad5..01aef8bb6 100644 --- a/crates/engine/tests/it/spline_options.rs +++ b/crates/engine/tests/it/spline_options.rs @@ -171,3 +171,37 @@ fn json_form_takes_the_fit_options() { assert_eq!(sp.fit_opts.start_tangent, None); assert_eq!(sp.fit_opts.end_tangent, Some(-Vec2::Y)); } + +#[test] +fn cv_method_keeps_cv_on_enter_and_can_switch_back_to_fit() { + for entry in ["spline.cv", "spline m cv"] { + let mut s = Session::new(); + s.cmdline(&format!("{entry} d 2 m")).unwrap(); + s.cmdline("").unwrap(); + s.cmdline("m fit 0,0 1,2 3,1").unwrap(); + s.cmdline("").unwrap(); + assert_eq!(last_spline(&s).fit.len(), 3, "{entry}"); + + s.cmdline(&format!("{entry} d 2 m")).unwrap(); + s.cmdline("").unwrap(); + s.cmdline("0,0 1,2 3,1 4,0").unwrap(); + s.cmdline("").unwrap(); + let cv = last_spline(&s); + assert!(cv.fit.is_empty() && cv.degree == 2, "{entry}"); + } +} + +#[test] +fn cv_object_converts_the_picked_polyline() { + for entry in ["spline.cv", "spline m cv"] { + let mut s = Session::new(); + s.execute("pline", &json!({"vertices":[[0,0],[1,2],[3,1]]})).unwrap(); + let h = s.doc().unwrap().model.iter().next().unwrap().handle; + s.cmdline(&format!("{entry} o")).unwrap(); + assert!(s.current_prompt().unwrap().picks_objects(), "{entry}"); + s.input(cadcraft_engine::Input::Pick(vec![h])).unwrap(); + s.cmdline("").unwrap(); + assert!(s.running.is_none() && s.doc().unwrap().model.len() == 1); + assert_eq!(last_spline(&s).fit.len(), 3); + } +} diff --git a/crates/engine/tests/mirror_hatch_direction.rs b/crates/engine/tests/mirror_hatch_direction.rs new file mode 100644 index 000000000..48d155aef --- /dev/null +++ b/crates/engine/tests/mirror_hatch_direction.rs @@ -0,0 +1,135 @@ +//! MIRROR retains a hatch pattern's direction by default, while reflecting its boundary. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle, Hatch}; +use cadcraft_engine::geom::Vec2; +use serde_json::{Value, json}; + +/// Create a rectangular hatch with an oblique pattern direction for reflection checks. +fn fixture() -> (Session, Handle) { + fixture_with(json!({"pattern": "ANSI31", "angle": 30})) +} + +/// Create a nonassociative rectangular hatch with the supplied synthetic fill parameters. +fn fixture_with(mut params: Value) -> (Session, Handle) { + let mut s = Session::new(); + let outline = s.execute("rectang", &json!({"p1": [2, 1], "p2": [8, 4]})).unwrap()["handle"].clone(); + params["handles"] = json!([outline]); + params["associative"] = json!(false); + let result = s.execute("hatch", ¶ms).unwrap(); + let h = result["handles"][0].as_str().unwrap(); + let h = Handle::parse_hex(h).unwrap(); + (s, h) +} + +/// Clone the asserted hatch so its geometry and fill can be compared across edits. +fn hatch(s: &Session, h: Handle) -> Hatch { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Hatch(h) => h.clone(), + _ => panic!("expected hatch"), + } +} + +/// A diagonal mirror reflects the boundary while retaining the fill direction through DXF readback. +#[test] +fn diagonal_mirror_keeps_pattern_direction_and_reflects_boundary() { + let (mut s, source) = fixture(); + let before = hatch(&s, source); + let result = s.execute("mirror", &json!({"handles": [source.hex()], "p1": [0, 0], "p2": [10, 10]})).unwrap(); + let mirrored = Handle::parse_hex(result["handles"][0].as_str().unwrap()).unwrap(); + let after = hatch(&s, mirrored); + assert!((after.angle - before.angle).abs() < 1e-12, "pattern turned from {} to {} degrees", before.angle.to_degrees(), after.angle.to_degrees()); + for (a, b) in before.loops[0].vertices.iter().zip(&after.loops[0].vertices) { + assert!((a.p.x - b.p.y).abs() < 1e-12); + assert!((a.p.y - b.p.x).abs() < 1e-12); + } + assert_eq!(hatch(&s, source), before, "retained source is unchanged"); + let saved = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let EntityKind::Hatch(saved) = &saved.entity(mirrored).unwrap().kind else { panic!("hatch lost on save") }; + assert!((saved.angle - before.angle).abs() < 1e-12); +} + +/// Typed MIRROR previews and committed geometry agree, including undo and redo. +#[test] +fn typed_mirror_previews_match_the_result_and_undo_redo() { + let (mut s, h) = fixture(); + let before = hatch(&s, h); + s.set_selection(vec![h]); + s.cmdline("MIRROR 0,0").unwrap(); + let cursor = Vec2::new(10., 10.); + let previews = s.preview(cursor); + let preview = previews + .iter() + .find_map(|e| match &e.kind { + EntityKind::Hatch(h) => Some(h), + _ => None, + }) + .unwrap(); + assert_eq!(preview.angle, before.angle); + let (drag, _) = s.drag(cursor).unwrap(); + assert!(!drag.handles.contains(&h), "GPU reflection would turn the hatch pattern"); + let drag_hatch = drag + .extra + .iter() + .find_map(|k| match k { + EntityKind::Hatch(h) => Some(h), + _ => None, + }) + .unwrap(); + assert_eq!(drag_hatch, preview); + s.cmdline("10,10").unwrap(); + s.cmdline("Y").unwrap(); + assert!(s.running.is_none()); + let after = hatch(&s, h); + assert_eq!(&after, preview); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(hatch(&s, h), before); + s.execute("redo", &json!({})).unwrap(); + assert_eq!(hatch(&s, h), after); +} + +/// Patterned and gradient fills keep their definitions when the mirrored result replaces its source. +#[test] +fn another_pattern_and_gradient_directions_are_retained() { + for gradient in [false, true] { + let (mut s, h) = fixture(); + if gradient { + s.execute("hatchedit", &json!({"handles": [h.hex()], "gradient": {"name": "LINEAR", "angle": 20}})).unwrap(); + } else { + s.execute("hatchedit", &json!({"handles": [h.hex()], "pattern": "ANSI32"})).unwrap(); + } + let before = hatch(&s, h); + s.execute("mirror", &json!({"handles": [h.hex()], "p1": [1, 2], "p2": [5, -1], "erase": true})).unwrap(); + let after = hatch(&s, h); + assert_eq!(after.angle, before.angle); + assert_eq!(after.pattern, before.pattern); + assert_eq!(after.pattern_lines, before.pattern_lines); + assert_eq!(after.gradient, before.gradient); + } +} + +/// Original asymmetric pattern families retain their line definitions under reflection. +#[test] +fn custom_pattern_line_families_are_not_reflected() { + let (mut s, h) = fixture_with(json!({ + "pattern": "ORIGINAL", "angle": 30, + "patternText": "*ORIGINAL,Original asymmetric regression pattern\n17,0.2,0.4,0.3,0.8,0.5,-0.2\n67,0.1,0.3,0.2,0.9,0.1,-0.4\n" + })); + let before = hatch(&s, h); + assert_eq!(before.pattern_lines.len(), 2); + s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 0], "p2": [10, 10], "erase": true})).unwrap(); + let after = hatch(&s, h); + assert_eq!(after.angle, before.angle); + assert_eq!(after.pattern_lines, before.pattern_lines); +} + +/// Solid hatches remain eligible for the shared GPU reflection preview. +#[test] +fn solid_fills_can_still_use_the_gpu_preview() { + let (mut s, h) = fixture_with(json!({"pattern": "SOLID"})); + s.set_selection(vec![h]); + s.cmdline("MIRROR 0,0").unwrap(); + let (drag, _) = s.drag(Vec2::new(10., 10.)).unwrap(); + assert!(drag.handles.contains(&h)); + assert!(!drag.extra.iter().any(|k| matches!(k, EntityKind::Hatch(_)))); +} diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 171af556c..bccf16da2 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -9,8 +9,11 @@ use serde_json::json; fn session() -> (Session, String) { let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; let mut d = Drawing::new_imperial(); - let kind = - EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] }); + let kind = EntityKind::Unknown(Unknown { + dxf_type: "OLE2FRAME".into(), + tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")], + graphics: Vec::new(), + }); let h = d.add(&Space::Model, Common::default(), kind).unwrap(); let mut s = Session::empty(); s.open_drawing(d, "ole.dxf", None); @@ -75,7 +78,8 @@ fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, Strin tags.push(tag(310, &hex[at..])); } let mut d = Drawing::new_imperial(); - let h = d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags })).unwrap(); + let h = + d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() })).unwrap(); let mut s = Session::empty(); s.open_drawing(d, "ole.dxf", None); (s, h.hex()) @@ -160,8 +164,11 @@ fn a_locked_ole_frame_does_not_block_an_in_place_rotation() { let mut d = Drawing::new_imperial(); d.ensure_layer("L"); let common = Common { layer: "L".into(), ..Common::default() }; - let kind = - EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] }); + let kind = EntityKind::Unknown(Unknown { + dxf_type: "OLE2FRAME".into(), + tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")], + graphics: Vec::new(), + }); let ole = d.add(&Space::Model, common, kind).unwrap(); if let Some(l) = d.layer_mut("L") { l.locked = true; diff --git a/crates/engine/tests/proxy_loss_real_writer.rs b/crates/engine/tests/proxy_loss_real_writer.rs index 5ad1a03e9..440d025fc 100644 --- a/crates/engine/tests/proxy_loss_real_writer.rs +++ b/crates/engine/tests/proxy_loss_real_writer.rs @@ -22,6 +22,7 @@ fn install() { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); set_proxies_lost(cadcraft_io::proxies_lost); + cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost); } /// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes. @@ -87,6 +88,35 @@ fn not_saved(r: &Value) -> Value { r.get("notSaved").cloned().unwrap_or(Value::Null) } +#[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn legacy_visualstyles_warn_only_for_2007_dwg() { + install(); + cadcraft_io::dwg_worker::allow_in_process(); + let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\ + 0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\ + 0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\ + 74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\ + 170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n"; + let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap(); + let mut session = Session::empty(); + session.open_drawing(drawing, "styles.dxf", None); + assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1)); + for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] { + let start = session.log.len(); + let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap(); + if format == "dwg" && version == 2007 { + assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1})); + assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE"))); + } else { + assert_eq!(not_saved(&result), Value::Null); + assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE"))); + } + } +} + #[test] fn a_proxy_no_version_writes_is_not_reported() { install(); diff --git a/crates/engine/tests/read_file_unicode.rs b/crates/engine/tests/read_file_unicode.rs index 4c3c520e8..6732a1063 100644 --- a/crates/engine/tests/read_file_unicode.rs +++ b/crates/engine/tests/read_file_unicode.rs @@ -17,7 +17,8 @@ fn read_file_refuses_a_name_that_is_not_unicode() { let good = dir.join("good.dxf"); let bad = dir.join(OsString::from_vec(b"bad-\xff.dxf".to_vec())); std::fs::write(&good, b"0\nEOF\n").unwrap(); - std::fs::write(&bad, b"0\nEOF\n").unwrap(); + // Validation precedes filesystem access; macOS filesystems may reject this name. + assert!(!bad.exists()); let e = read_file(&bad).err().expect("a non-Unicode name is refused"); assert!(e.contains("not valid Unicode") && e.contains("bad-"), "{e}"); assert!(read_file(&good).is_ok()); diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 2ed3af583..2ba4743ee 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -8,7 +8,7 @@ use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Un use serde_json::json; fn unknown(kind: &str) -> EntityKind { - EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] }) + EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() }) } #[test] @@ -129,6 +129,7 @@ fn proxy_entities_are_reported_only_before_2013() { RawTag { code: 90, value: "498".into() }, RawTag { code: 91, value: class.to_string() }, ], + graphics: Vec::new(), }) }; let mut d = Drawing::new_imperial(); @@ -190,6 +191,7 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { RawTag { code: 1, value: "400 1 1 0".into() }, RawTag { code: 3, value: "End-of-ACIS-data".into() }, ], + graphics: Vec::new(), }); d.add(&Space::Model, Common::default(), sat).unwrap(); let mut s = Session::empty(); @@ -219,7 +221,7 @@ fn a_dxf_2013_loss_is_known_before_saving() { set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); let sat = |d: &mut Drawing| { let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }]; - d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap(); + d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap(); }; let mut modern = Drawing::new_imperial(); modern.header.set_str("ACADVER", "AC1032"); @@ -255,6 +257,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() { RawTag { code: 1, value: "400 1 1 0".into() }, RawTag { code: 3, value: "End-of-ACIS-data".into() }, ], + graphics: Vec::new(), }); d.add(&Space::Model, Common::default(), sat).unwrap(); d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door"))); @@ -276,7 +279,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() { fn a_dwg_keeps_sat_text_solids_only_before_2013() { use cadcraft_engine::cmd::file::{Version, not_saved_as}; let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; - let solid = |tags: Vec| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags }); + let solid = |tags: Vec| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() }); let mut d = Drawing::new_imperial(); d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap(); d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap(); @@ -352,6 +355,7 @@ fn proxy_entity(strings: &str) -> EntityKind { EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(), + graphics: Vec::new(), }) } diff --git a/crates/engine/tests/wblock_pick.rs b/crates/engine/tests/wblock_pick.rs new file mode 100644 index 000000000..750860466 --- /dev/null +++ b/crates/engine/tests/wblock_pick.rs @@ -0,0 +1,60 @@ +//! WBLOCKPICK: the Write Block dialog's canvas picks (objects, base point) and their cancel. + +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +fn session_with_line() -> (Session, cadcraft_engine::doc::Handle) { + let mut s = Session::new(); + let r = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap(); + let h = cadcraft_engine::doc::Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap(); + s.set_selection(Vec::new()); + (s, h) +} + +#[test] +fn objects_keeps_the_selection() { + let (mut s, h) = session_with_line(); + s.start("wblockpick").unwrap(); + s.input(Input::Keyword("Objects".into())).unwrap(); + s.input(Input::Pick(vec![h])).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + let p = s.wblock_picks.take().unwrap(); + assert_eq!((p.handles, p.base), (vec![h], None)); +} + +#[test] +fn base_keeps_the_point() { + let (mut s, _) = session_with_line(); + s.start("wblockpick").unwrap(); + s.input(Input::Keyword("Base".into())).unwrap(); + s.input(Input::Point(Vec2::new(3.0, 4.0))).unwrap(); + assert!(s.running.is_none()); + let p = s.wblock_picks.take().unwrap(); + assert_eq!((p.handles.len(), p.base), (0, Some(Vec2::new(3.0, 4.0)))); +} + +#[test] +fn escape_keeps_nothing() { + let (mut s, h) = session_with_line(); + s.start("wblockpick").unwrap(); + s.input(Input::Keyword("Objects".into())).unwrap(); + s.input(Input::Pick(vec![h])).unwrap(); + s.input(Input::Cancel).unwrap(); + assert!(s.running.is_none()); + assert!(s.wblock_picks.is_none()); +} + +#[test] +fn preexisting_selection_still_prompts() { + // Even if there is a pickfirst selection, WBLOCKPICK Objects must keep prompting + // so the dialog drives picking explicitly — it never bypasses the "Select objects" step. + let (mut s, h) = session_with_line(); + s.set_selection(vec![h]); + s.start("wblockpick").unwrap(); + s.input(Input::Keyword("Objects".into())).unwrap(); + // Must still be running — "Select objects" prompt expected. + assert!(s.running.is_some()); + assert!(s.wblock_picks.is_none()); +} diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index 5c95305a3..f6a19b567 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -134,10 +134,10 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 *point += Vec2::new(offset_y * shear, offset_y); } let origin = Vec2::new(pen_x + glyph.dx * glyph_scale + offset_y * shear, offset_y); - let text = shows.get(n).copied().flatten().filter(|character| !character.is_whitespace()).and_then(|character| { - ttf::text_glyph_at(&outline, character, origin, normalized_height / outline.cap, scale_x, shear) + let texts = shows.get(n).into_iter().flatten().filter(|character| !character.is_whitespace()).filter_map(|character| { + ttf::text_glyph_at(&outline, *character, origin, normalized_height / outline.cap, scale_x, shear) }); - shaped.push_glyph(contours, text); + shaped.push_glyph(contours, texts); } let advance = glyph.advance * glyph_scale; let (underline, overline) = flags(glyph.cluster); @@ -249,46 +249,99 @@ fn shape_run(face: &Face, cs: &[char], r: Range, rtl: bool) -> Vec /// longer one (a hostile run of thousands of stacked marks) take its characters in order. const MAX_MATCHED_CLUSTER: usize = 32; -/// The character each glyph of a left-to-right run shows, for output that keeps text as text +/// The characters each glyph of a left-to-right run shows, for output that keeps text as text /// ([`crate::TextGlyph`]). The shaper reorders, splits and substitutes glyphs inside a cluster /// (a letter with its marks), so within each cluster a glyph that is a character's own glyph /// takes that character first, then the other glyphs take the cluster's remaining characters in -/// order. Each character is shown once: a glyph left over (the second half of a split Thai sara -/// am) shows none and is drawn as an outline only. -fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec> { - let mut out: Vec> = vec![None; glyphs.len()]; +/// order, and characters left over (a ligature such as ฐ with sara u below) are shown by the +/// glyph before them. Each character is shown once, and the glyphs show the characters in typed +/// order wherever that leaves no fewer glyphs showing one, so text read back in drawing order is +/// the typed text: a split Thai sara am is drawn as nikhahit, then any tone mark, then sara aa, +/// so in น้ำ the sara aa shows ำ and the nikhahit, moved before the tone mark, shows none and is +/// drawn as an outline only. +fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec> { + let mut out: Vec> = vec![Vec::new(); glyphs.len()]; let mut i = 0; while let Some(cluster) = glyphs.get(i).map(|g| g.cluster) { let j = glyphs.iter().skip(i).position(|g| g.cluster != cluster).map_or(glyphs.len(), |n| i + n); // Clusters ascend in a left-to-right run: this one's characters end where the next starts. let to = glyphs.get(j).map_or(end, |g| g.cluster).clamp(cluster, end.max(cluster)); let chars = cs.get(cluster..to).unwrap_or_default(); - let mut free: Vec> = chars.iter().copied().map(Some).collect(); - if chars.len() <= MAX_MATCHED_CLUSTER { - let ids = face.glyph_ids(chars); - for n in i..j { - let gid = glyphs.get(n).map(|g| g.gid); - let own = ids.iter().zip(&free).position(|(id, f)| f.is_some() && *id == gid); - if let (Some(p), Some(o)) = (own, out.get_mut(n)) { - *o = free.get_mut(p).and_then(Option::take); - } - } - } - let mut rest = free.into_iter().flatten(); - for o in out.iter_mut().take(j).skip(i).filter(|o| o.is_none()) { - *o = rest.next(); + let ids = if chars.len() <= MAX_MATCHED_CLUSTER { face.glyph_ids(chars) } else { Vec::new() }; + let gids: Vec = glyphs.get(i..j).unwrap_or_default().iter().map(|g| g.gid).collect(); + let any = cluster_chars(chars, &ids, &gids, false).unwrap_or_default(); + // Output that keeps one character per glyph (render, PDF) writes each glyph's first: typed + // order must not leave fewer of them than the plain assignment. + let firsts = |s: &[Vec]| s.iter().filter(|c| !c.is_empty()).count(); + let shows = cluster_chars(chars, &ids, &gids, true).filter(|t| firsts(t) >= firsts(&any)).unwrap_or(any); + for (o, s) in out.iter_mut().skip(i).zip(shows) { + *o = s; } i = j; } out } +/// The characters each glyph `gids` of one cluster shows, of the cluster's characters `chars` +/// with their own glyph ids `ids` (empty: none matched): a glyph that is a character's own glyph +/// takes that character first, then the other glyphs take the remaining characters in order, +/// and the cluster's last glyph takes those left over. `typed`: own glyphs are matched in typed +/// order only and a character with no glyph of its own between them goes with the glyph before +/// it, so the glyphs show the characters in typed order; `None` when a character comes before +/// every glyph that shows one (a vowel sign drawn before its consonant). +fn cluster_chars(chars: &[char], ids: &[Option], gids: &[u32], typed: bool) -> Option>> { + let mut taken = vec![false; chars.len()]; + let mut at: Vec> = vec![Vec::new(); gids.len()]; + let mut from = 0; + for (a, gid) in at.iter_mut().zip(gids) { + let own = ids.iter().zip(&taken).enumerate().skip(from).find(|(_, (id, t))| !**t && **id == Some(*gid)).map(|(p, _)| p); + if let Some(p) = own { + a.push(p); + taken.get_mut(p).into_iter().for_each(|t| *t = true); + from = if typed { p + 1 } else { 0 }; + } + } + // The characters before `next` are shown; `last` is the glyph that shows the latest one. + let (mut next, mut last): (usize, Option) = (0, None); + for k in 0..at.len() { + match at.get(k).and_then(|a| a.first()).copied() { + Some(p) if typed => { + if next < p { + at.get_mut(last?)?.extend(next..p); + } + (next, last) = (p + 1, Some(k)); + } + Some(_) => {} + None => { + while !typed && taken.get(next) == Some(&true) { + next += 1; + } + if taken.get(next) == Some(&false) { + at.get_mut(k)?.push(next); + (next, last) = (next + 1, Some(k)); + } + } + } + } + let rest: Vec = (next..chars.len()).filter(|p| taken.get(*p) == Some(&false)).collect(); + if !rest.is_empty() { + at.last_mut()?.extend(rest); + } + Some(at.into_iter().map(|a| a.into_iter().filter_map(|p| chars.get(p).copied()).collect()).collect()) +} + #[cfg(test)] mod tests { use super::*; /// A single empty glyph with a positive advance, without relying on installed fonts. fn empty_glyph_face() -> Face { + mapped_face(&[]) + } + + /// [`empty_glyph_face`] with a character map: each character to its glyph id (all ids draw + /// the one empty glyph). + fn mapped_face(map: &[(char, u32)]) -> Face { let mut head = vec![0_u8; 54]; head[..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes()); head[18..20].copy_from_slice(&1000_u16.to_be_bytes()); @@ -297,7 +350,16 @@ mod tests { hhea[4..6].copy_from_slice(&800_i16.to_be_bytes()); hhea[6..8].copy_from_slice(&(-200_i16).to_be_bytes()); hhea[34..36].copy_from_slice(&1_u16.to_be_bytes()); + let mut cmap = Vec::from([0, 0, 0, 1, 0, 3, 0, 10, 0, 0, 0, 12, 0, 12, 0, 0]); // Format 12 at 12. + let len = u32::try_from(16 + 12 * map.len()).unwrap(); + cmap.extend(len.to_be_bytes().into_iter().chain([0; 4]).chain(u32::try_from(map.len()).unwrap().to_be_bytes())); + let mut map = map.to_vec(); + map.sort_unstable(); + for (c, gid) in map { + cmap.extend([u32::from(c), u32::from(c), gid].into_iter().flat_map(u32::to_be_bytes)); + } let tables = [ + (*b"cmap", cmap), (*b"head", head), (*b"hhea", hhea), (*b"hmtx", vec![1, 244, 0, 0]), // Advance 500, left side bearing 0. @@ -305,7 +367,7 @@ mod tests { ]; let mut bytes = vec![0_u8; 12 + tables.len() * 16]; bytes[..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes()); - bytes[4..6].copy_from_slice(&4_u16.to_be_bytes()); + bytes[4..6].copy_from_slice(&u16::try_from(tables.len()).unwrap().to_be_bytes()); bytes[6..8].copy_from_slice(&64_u16.to_be_bytes()); bytes[8..10].copy_from_slice(&2_u16.to_be_bytes()); for (i, (tag, data)) in tables.into_iter().enumerate() { @@ -446,6 +508,38 @@ mod tests { assert!(!needed("50x50 mm.") && !needed("Ünïcödé %%c25") && !needed("")); } + /// The shaper splits sara am (ำ) into nikhahit and sara aa and draws the nikhahit before a + /// tone mark: in drawing order the glyphs still show the typed text, each character on a + /// glyph of its own, of its parts or before it (issue #2899). A glyph drawn before the + /// character it stands for (a vowel sign before its consonant) keeps its own character: no + /// character is moved onto another glyph to keep the order. + #[test] + fn reordered_glyphs_show_their_cluster_in_typed_order() { + let (no, mai_tho, sara_am, nikhahit, sara_aa) = ('\u{0E19}', '\u{0E49}', '\u{0E33}', '\u{0E4D}', '\u{0E32}'); + let (deva_ka, deva_i, sara_u) = ('\u{0915}', '\u{093F}', '\u{0E38}'); + let face = mapped_face(&[(no, 1), (mai_tho, 2), (sara_am, 3), (nikhahit, 4), (sara_aa, 5), (deva_ka, 6), (deva_i, 7), (sara_u, 8)]); + let with_gids = |gids: &[u32]| gids.iter().map(|gid| Glyph { gid: *gid, ..glyph(0) }).collect::>(); + let cs = [no, mai_tho, sara_am]; + // What the shaper draws for น้ำ: no, nikhahit, mai tho, sara aa. + let shows = glyph_chars(&face, &cs, &with_gids(&[1, 4, 2, 5]), cs.len()); + assert_eq!(shows.iter().flatten().collect::(), "น้ำ"); + assert_eq!(shows.get(2), Some(&vec![mai_tho]), "the tone mark's glyph shows the tone mark: {shows:?}"); + // A sara u drawn into the letter's glyph goes with it, before the tone mark. + let cs = [no, sara_u, mai_tho]; + let shows = glyph_chars(&face, &cs, &with_gids(&[1, 2]), cs.len()); + assert_eq!(shows, [vec![no, sara_u], vec![mai_tho]]); + // Typed with the tone mark before sara u but drawn after it: in typed order the tone mark + // would only follow no on its glyph, and output that writes a glyph's first character + // would lose it, so each glyph keeps its own character. + let cs = [no, mai_tho, sara_u]; + let shows = glyph_chars(&face, &cs, &with_gids(&[1, 8, 2]), cs.len()); + assert_eq!(shows, [vec![no], vec![sara_u], vec![mai_tho]]); + // Devanagari ki: the vowel sign is drawn first. + let cs = [deva_ka, deva_i]; + let shows = glyph_chars(&face, &cs, &with_gids(&[7, 6]), cs.len()); + assert_eq!(shows, [vec![deva_i], vec![deva_ka]]); + } + fn glyph(cluster: usize) -> Glyph { Glyph { gid: 0, cluster, advance: 500.0, dx: 0.0, dy: 0.0 } } @@ -459,17 +553,20 @@ mod tests { // A run from index 1: cluster 1 has "ab" (two glyphs), cluster 3 has "cd" and a split // character's extra glyph, which shows nothing. let gs = Vec::from([1, 1, 3, 3, 3].map(glyph)); - assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![Some('a'), Some('b'), Some('c'), Some('d'), None]); + assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec!['a'], vec!['b'], vec!['c'], vec!['d'], vec![]]); + // A ligature (ฐ with sara u below as one glyph) shows every character of its cluster. + let gs = Vec::from([1, 3].map(glyph)); + assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec!['a', 'b'], vec!['c', 'd']]); // Clusters out of order, past the run or past the line show nothing and don't panic. let gs = Vec::from([3, 1, usize::MAX, 9].map(glyph)); - assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![None, Some('a'), None, None]); + assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec![], vec!['a', 'b', 'c', 'd'], vec![], vec![]]); assert!(glyph_chars(&face, &cs, &[], 5).is_empty()); // A cluster longer than the matching limit still shows each character once, in order. let long: Vec = std::iter::once('ก').chain(std::iter::repeat_n('\u{0E48}', MAX_CHARS)).collect(); let gs: Vec = (0..long.len()).map(|_| glyph(0)).collect(); let shows = glyph_chars(&face, &long, &gs, long.len()); - assert_eq!(shows.first(), Some(&Some('ก'))); - assert!(shows.iter().all(Option::is_some)); + assert_eq!(shows.first(), Some(&vec!['ก'])); + assert!(shows.iter().all(|s| s.len() == 1)); } /// An installed font with Thai, or `None` (the tests then skip). diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 067293b6b..f64945799 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -408,15 +408,15 @@ pub struct TextGlyph { } impl Shaped { - /// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`]. - /// An empty outline is retained only when text metadata needs its slot. - pub(crate) fn push_glyph(&mut self, contours: Vec>, text: Option) { - if contours.is_empty() && text.is_none() { + /// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`] (one per character it + /// shows: a ligature shows several). An empty outline is retained only when text metadata + /// needs its slot. + pub(crate) fn push_glyph(&mut self, contours: Vec>, text: impl IntoIterator) { + let (outline, before) = (self.glyphs.len(), self.text.len()); + self.text.extend(text.into_iter().map(|t| TextGlyph { outline, ..t })); + if contours.is_empty() && self.text.len() == before { return; } - if let Some(t) = text { - self.text.push(TextGlyph { outline: self.glyphs.len(), ..t }); - } self.glyphs.push(contours); } /// Apply a point transform to every vertex (an affine map: text glyphs keep their axes). @@ -649,31 +649,41 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) { (origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror) } +/// Resolve Aligned/Fit dimensions with the same shaping direction as [`place`]. +/// Missing, coincident or nonfinite points leave the parameters unchanged. +pub fn fit_params(font: &TextFont, s: &str, p: &TextParams) -> TextParams { + let mut fitted = *p; + if !matches!(p.h, Align::Aligned | Align::Fit) { + return fitted; + } + let Some(second) = p.align_pt else { return fitted }; + let distance = p.insert.dist(second); + if !distance.is_finite() || distance <= 1e-12 { + return fitted; + } + fitted.rotation = p.insert.angle_to(second); + let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; + let width = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL).width; + if width.is_finite() && width > 1e-12 { + let scale = distance / width; + if p.h == Align::Aligned { + fitted.height = height * scale; + } else { + fitted.width_factor *= scale; + } + } + fitted +} + /// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its /// bounding box. pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { - let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; - let mut wf = p.width_factor; - let mut rot = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + let fitted = fit_params(font, s, p); + let p = &fitted; + let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; + let rot = if p.rotation.is_finite() { p.rotation } else { 0.0 }; let insert = p.insert; - if matches!(p.h, Align::Aligned | Align::Fit) - && let Some(p2) = p.align_pt - { - let len = insert.dist(p2); - rot = insert.angle_to(p2); - // Measured as it is placed, left to right: the stroke font's trailing gap follows the - // glyph that ends the line. - let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width; - if w > 1e-12 && len > 1e-12 { - let k = len / w; - if p.h == Align::Aligned { - height *= k; - } else { - wf *= k; - } - } - } - let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL); + let mut sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL); let width = sh.width; // Every justification but baseline-left (and aligned/fit, which span both points) is placed by // its alignment point (DXF group 11); the insertion point (group 10) is then a computed point. @@ -740,6 +750,15 @@ mod tests { assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width); } + #[test] + fn two_point_middle_vertical_spans_points() { + for h in [Align::Aligned, Align::Fit] { + let p = TextParams { h, v: VAlign::Middle, align_pt: Some(Vec2::new(12.0, 5.0)), ..TextParams::new(Vec2::ZERO, 2.0) }; + let (shaped, _) = place(&TextFont::Stroke, "SYNTHETIC", &p); + assert!((shaped.width - p.insert.dist(p.align_pt.unwrap())).abs() < 1e-9); + } + } + #[test] fn every_ascii_printable_has_a_glyph() { for c in ' '..='~' { diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index b1db77673..740384c54 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -102,6 +102,9 @@ pub struct MTextLayout { /// Geometry by colour run (strokes plus fillable glyph outlines). pub pieces: Vec, pub bounds: Bounds2, + /// The box of each column, in the order the text flows through them, measured like `bounds` + /// but without the gutters and to each column's own height. One column: `bounds`. + pub column_bounds: Vec, /// Plain text of each laid-out line. pub lines: Vec, /// Whether the geometry stops short: the layout reached its allowance of retained points @@ -731,6 +734,7 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout { out.bounds = Bounds2::from_points( [Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf), ); + out.column_bounds = vec![out.bounds]; out } diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index f87ceaeb1..6a9b3709b 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -700,6 +700,14 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL [Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)] .map(xf), ); + out.column_bounds = (0..n_cols) + .map(|column| { + let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column)); + let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column }; + let x0 = box_x0 + slot as f64 * (col_w + gutter); + Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf)) + }) + .collect(); out } diff --git a/crates/fonts/tests/mtext_paragraphs.rs b/crates/fonts/tests/mtext_paragraphs.rs index 3baaa1885..f09b6681b 100644 --- a/crates/fonts/tests/mtext_paragraphs.rs +++ b/crates/fonts/tests/mtext_paragraphs.rs @@ -109,6 +109,66 @@ fn reversed_columns_run_right_to_left() { assert!(first > 0 && second > 0 && min_x(&l) >= 0.0); } +/// The geometry points inside `b`. +fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize { + l.strokes.iter().flatten().filter(|p| b.contains(**p)).count() +} + +#[test] +fn each_column_has_its_own_box_without_the_gutter() { + let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() })); + let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) }; + assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b)); + assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}"); + assert!(a.width() + b.width() < two.bounds.width()); + let total = two.strokes.iter().map(Vec::len).sum::(); + assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0); + assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box"); + + // Three static columns, the text filling two and a half: the half-full column keeps the + // column height; text past the last column lengthens only that one. + let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() }; + let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone())); + assert_eq!(three.column_bounds.len(), 3); + assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9)); + let over = lay(&"word ".repeat(40), 10.0, Some(spec)); + let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) }; + assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9); + + // Manual heights: each column as tall as its own height. + let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() })); + let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) }; + assert!(a.height() < b.height()); +} + +#[test] +fn an_empty_column_keeps_its_place() { + let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() })); + let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) }; + assert!(a.max.x < b.min.x && b.max.x < c.min.x); + assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0); + assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9); + // Reversed: the column the text starts in is the rightmost. + let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() })); + let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) }; + assert!(a.min.x > b.max.x - 1e-9); +} + +#[test] +fn one_column_is_the_whole_box() { + let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p }; + for (s, width, columns) in [ + ("plain text that wraps a few times", 6.0, None), + ("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None), + ("no width\\Pat all", 0.0, None), + (&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })), + ("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })), + ] { + let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) })); + assert_eq!(l.column_bounds, vec![l.bounds], "{s}"); + } +} + #[test] fn hostile_paragraph_codes_do_not_panic() { let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::>().join(",")); diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 3c1b7d124..a2c22d29d 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -903,6 +903,73 @@ pub fn object_records(d: &Drawing) -> Vec { .collect() } +/// The `dependentOnObject` handle (first group 330 inside the `AcDbAssocDependency` subclass) of +/// a kept associative dependency, when it is non-null. +fn assoc_dependency_target(o: &ForeignObject) -> Option { + let mut in_dep = false; + for r in &o.tags { + if r.code == 100 { + if in_dep { + break; + } + in_dep = r.value.trim().eq_ignore_ascii_case("AcDbAssocDependency"); + } else if in_dep && r.code == 330 { + let v = norm(&r.value); + return (!v.is_empty() && v != "0").then_some(v); + } + } + None +} + +/// The groups of an `AcDbAssocAction` subclass before its dependency count: `100 AcDbAssocAction`, +/// `90` version, `90` status, `330` network, `360` body, `90` index and `90` highest dependency index. +const ASSOC_ACTION_HEADER: [i32; 7] = [100, 90, 90, 330, 360, 90, 90]; + +/// If `tags[at]` is the dependency count (group 90) of an `AcDbAssocAction` subclass, returns the count. +/// The count is followed by one group per dependency: 360 for an owned dependency, 330 for one the +/// action does not own. acadrust writes this layout (`write_assoc_action` in acadrust 0.6.6's +/// `io/dxf/writer/section_writer/associative.rs`) and reads it back (`read_action` in +/// `io/dxf/reader/section_reader/associative.rs`). A DWG reaches this code through that writer, so a +/// kept action from a DWG has this form too. +/// +/// The match is positional on purpose. When the class version is above 1, the list is followed by +/// `90 0`, `90 n` and n group-360 owned parameters. A loose match on a group 90 before handles also +/// takes that second list. +fn assoc_action_dep_count(tags: &[RawTag], at: usize) -> Option { + if at < ASSOC_ACTION_HEADER.len() || tags.get(at)?.code != 90 { + return None; + } + let start = at - ASSOC_ACTION_HEADER.len(); + if !tags[start].value.trim().eq_ignore_ascii_case("AcDbAssocAction") { + return None; + } + if !ASSOC_ACTION_HEADER.iter().enumerate().all(|(k, &c)| tags[start + k].code == c) { + return None; + } + let count = usize::try_from(tags[at].value.trim().parse::().ok()?).ok()?; + let deps = tags.get(at + 1..at + 1 + count)?; + deps.iter().all(|t| matches!(t.code, 330 | 360)).then_some(count) +} + +/// The index of a kept object's `100 AcDbAssocAction` marker. An associative network derives from +/// an action, so it has one too. +fn assoc_action_marker(tags: &[RawTag]) -> Option { + tags.iter().position(|t| t.code == 100 && t.value.trim().eq_ignore_ascii_case("AcDbAssocAction")) +} + +/// The dependency list of a kept action that [`assoc_action_dep_count`] recognizes: the index of +/// its count group and the count. +fn assoc_action_list(tags: &[RawTag]) -> Option<(usize, usize)> { + let at = assoc_action_marker(tags)? + ASSOC_ACTION_HEADER.len(); + Some((at, assoc_action_dep_count(tags, at)?)) +} + +/// Whether a kept object is an action whose dependency list has a form we do not know. Its list +/// cannot be rewritten, so the dependencies it owns are not pruned. +fn is_unknown_assoc_action(tags: &[RawTag]) -> bool { + assoc_action_marker(tags).is_some() && assoc_action_list(tags).is_none() +} + /// Remaps the kept data's handles onto a written file. struct Map<'a> { f: &'a Foreign, @@ -954,6 +1021,7 @@ impl Map<'_> { fn object(&self, o: &ForeignObject, out: &mut Vec) { out.push(Tag::s(0, o.kind.clone())); let dict = is_dictionary(&o.kind); + let list = assoc_action_list(&o.tags); let mut i = 0; while let Some(r) = o.tags.get(i) { i += 1; @@ -997,6 +1065,16 @@ impl Map<'_> { } continue; } + if let Some((_, count)) = list.filter(|&(at, _)| at == i - 1) { + // An entry keeps its own group code. A null entry stays null, because [`Map::get`] + // gives "0" only for a null handle. An entry whose object is gone is left out, and + // the count follows. + let live: Vec = o.tags[i..i + count].iter().filter_map(|n| self.get(&n.value).map(|h| Tag::s(n.code, h))).collect(); + out.push(Tag::i(90, i64::try_from(live.len()).unwrap_or(i64::MAX))); + out.extend(live); + i += count; + continue; + } if r.code == 5 { out.push(Tag::s(5, self.get(&r.value).unwrap_or_else(|| "0".into()))); continue; @@ -1166,7 +1244,7 @@ pub(crate) fn finish( (o.handle.hex(), head(&t).owner) }) .collect(); - let alive_memo = settle(&hard, |kept: &HashMap| { + let mut alive_memo = settle(&hard, |kept: &HashMap| { // Keep established live paths available to descendants during this pass as well. let mut alive_memo: HashMap = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect(); let kept = |h: &str| kept.get(h) == Some(&true); @@ -1207,6 +1285,64 @@ pub(crate) fn finish( } alive_memo }); + // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop + // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an + // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant. + let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); + // A dependency stays when an action of unknown form names it by group 330 or 360, or is its + // owner. That action's list and count stay as read, and only the dangling target becomes null. + // Each kept action is classified once, here. + let unknown_actions: Vec<&ForeignObject> = f.objects.iter().filter(|o| is_unknown_assoc_action(&o.tags)).collect(); + let unknown_handles: HashSet = unknown_actions.iter().map(|o| o.handle.hex()).collect(); + let unknown_refs: HashSet = unknown_actions + .iter() + .flat_map(|o| o.tags.iter().take_while(|t| t.code < 1000).filter(|t| matches!(t.code, 330 | 360)).map(|t| norm(&t.value))) + .collect(); + let in_unknown_action = + |h: &str| unknown_refs.contains(h) || own.get(h).and_then(Option::as_deref).is_some_and(|owner| unknown_handles.contains(owner)); + // Each pass that changes something drops at least one live object, so the loop ends. + loop { + let mut changed = false; + for o in &f.objects { + let h = o.handle.hex(); + if alive_memo.get(&h) != Some(&true) || in_unknown_action(&h) { + continue; + } + let dead_target = assoc_dependency_target(o).is_some_and(|t| { + if objs.contains_key(&t) { + alive_memo.get(&t) != Some(&true) + } else if let Some(role) = handle(&t).and_then(|th| f.targets.get(&th)) { + !roles.contains_key(role) + } else { + !entities.contains(&t) + } + }); + if dead_target { + alive_memo.insert(h, false); + changed = true; + } + } + if !changed { + break; + } + // The owner is found as for the first liveness pass ([`owner_of`]). A null-owner child goes + // with its hard owner, and a child with another live hard owner stays. + let mut cascade = true; + while cascade { + cascade = false; + for o in &f.objects { + let h = o.handle.hex(); + if alive_memo.get(&h) != Some(&true) { + continue; + } + let owner = owner_of(own.get(&h).cloned().flatten(), &h, &hard, |x| alive_memo.get(x) == Some(&true)); + if owner.is_some_and(|owner| objs.contains_key(&owner) && alive_memo.get(&owner) != Some(&true)) { + alive_memo.insert(h, false); + cascade = true; + } + } + } + } // New handles for the written kept objects, above every written handle and the seed. let mut fresh = Fresh::new(tags); // The entities of unmodeled types join the records only below, so their handles are not in @@ -1224,7 +1360,6 @@ pub(crate) fn finish( } } let merged_into: HashMap = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect(); - let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities }; let mut out: Vec = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::()); let mut block = String::new(); @@ -1263,7 +1398,9 @@ pub(crate) fn finish( let x = extra_for(f, &xd, r, b, &block); let joined = joined_into(&merged_into, b); if x.is_none() && Some(r.start) != root && joined.is_none() { - out.extend(b.iter().cloned()); + out.extend(b.iter().map(|tag| { + if r.kind == "LAYOUT" && tag.code == 333 { Tag::s(333, map.get(&tag.str()).unwrap_or_else(|| "0".into())) } else { tag.clone() } + })); continue; } record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out); @@ -1379,6 +1516,8 @@ fn plan_unknown( }; let br = |name: &str| roles.get(&("BLOCK_RECORD".to_string(), up(name))).cloned(); let first_at = |s: &cadcraft_doc::EntityStore| s.iter().find_map(|e| at.get(&e.handle.hex()).copied()); + // The LAYER table as written: proxy graphics name layers by their index in it (#3094). + let written_layers: Vec = recs.iter().filter(|r| r.sec == "TABLES" && r.kind == "LAYER").filter_map(|r| val(body(r), 2)).collect(); let layouts = d.paper_space_layouts(); // (entities, owner, paper space, end of the space, section) let mut stores: Vec<(&cadcraft_doc::EntityStore, Option, bool, Option, &str)> = Vec::new(); @@ -1406,7 +1545,8 @@ fn plan_unknown( { continue; } - let t = unknown_entity(u, e, &owner, paper); + let remapped = u.with_proxy_layers(&d.proxy_layers, &written_layers).map(|tags| Unknown { tags, ..u.clone() }); + let t = unknown_entity(remapped.as_ref().unwrap_or(u), e, &owner, paper); if !t.is_empty() { pending.push((sec.to_string(), t)); } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 7130ab000..5779a8f2e 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -62,6 +62,9 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers). layers: HashMap, + /// Layer, linetype and text style names in the order of the file's tables, which proxy + /// graphics refer to by index (the drawing's own tables are ordered differently). + proxy_tables: cadcraft_doc::ProxyTables, /// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345). ucss: HashMap, /// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport @@ -75,6 +78,84 @@ struct Rx { image_defs: HashMap, } +/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned` +/// names: records the file doesn't have keep their order after the file's own. A file without +/// that table changes nothing. +fn keep_file_order(items: &mut [T], name: impl Fn(&T) -> &str, order: &[String], pinned: &[&str]) { + if order.is_empty() { + return; + } + let mut place: HashMap = HashMap::new(); + for (i, n) in order.iter().enumerate() { + place.entry(n.to_ascii_lowercase()).or_insert(i); + } + items.sort_by_key(|it| { + let n = name(it); + match pinned.iter().position(|p| p.eq_ignore_ascii_case(n)) { + Some(i) => (0, i), + None => place.get(&n.to_ascii_lowercase()).map_or((2, 0), |&i| (1, i)), + } + }); +} + +/// A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` block, as +/// AutoCAD does, in place of the proxy graphics it may carry: those can differ from what AutoCAD +/// shows (an exporter's picture without the arrowheads; #3438). Its graphics become one reference +/// to that block, with the dimension's handle, so it is drawn, measured and picked like a proxy. +/// A reference, not a copy of the contents: nested dimensions, the block's draw order and the +/// renderer's depth and size limits all apply as for any block reference. +fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) { + let pictures = |store: &cadcraft_doc::EntityStore, d: &Drawing| -> Vec<(Handle, Entity)> { + store + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Unknown(u) => { + let block = d.block(u.dimension_block()?)?; + // The block holds the dimension as drawn, in the dimension's coordinates: placed + // at its base point it draws where it is, as a DIMENSION's block does. + let reference = Insert { block: block.name.clone(), insert: block.base, ..Insert::default() }; + // Everything ByBlock, so what the block gives ByBlock is the dimension's own. + let common = Common { + layer: "0".into(), + color: Color::ByBlock, + linetype: "ByBlock".into(), + lineweight: Lineweight::ByBlock, + transparency: Transparency::ByBlock, + plot_style: "ByBlock".into(), + ..Common::default() + }; + (!block.entities.is_empty()).then(|| (e.handle, Entity { handle: e.handle, common, kind: EntityKind::Insert(reference) })) + } + _ => None, + }) + .collect() + }; + let apply = |store: &mut cadcraft_doc::EntityStore, found: Vec<(Handle, Entity)>| { + for (h, reference) in found { + store.modify(h, |e| { + if let EntityKind::Unknown(u) = &mut e.kind { + u.graphics = vec![reference]; + } + }); + } + }; + let found = pictures(&d.model, d); + apply(&mut d.model, found); + for i in 0..d.layouts.len() { + let found = pictures(&d.layouts[i].entities, d); + apply(&mut d.layouts[i].entities, found); + } + let names: Vec = d.blocks.keys().cloned().collect(); + for name in names { + let found = d.blocks.get(&name).map(|b| pictures(&b.entities, d)).unwrap_or_default(); + if !found.is_empty() + && let Some(b) = d.blocks.get_mut(&name) + { + apply(&mut std::sync::Arc::make_mut(b).entities, found); + } + } +} + /// Read a DXF file into a drawing. pub fn read(bytes: &[u8]) -> Result { read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS) @@ -179,12 +260,23 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) _ => {} } } + // Proxy graphics name layers and linetypes by their place in the file's tables, and saving + // writes them unchanged: the tables keep the file's order, with what CADCraft adds after it. + keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]); + // Saving turns the graphics' layer indices from this order into the written table's, so + // removing or adding layers doesn't move them (#3094). + d.proxy_layers.clone_from(&rx.proxy_tables.layers); + keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]); + // A proxy text takes the first style on its font, so the styles keep the file's order too. + let styles: Vec = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect(); + keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]); // A file CADCraft wrote names its own next handle (#495): its table records and objects // are numbered above it and rebuilt on save, so following $HANDSEED would drift every save. let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim())); let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx); place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout); place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout); + draw_kept_dimensions_from_their_blocks(&mut d); number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout)); apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); @@ -212,6 +304,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) // Every record is placed now, and an object holding a reserved handle keeps it from new // objects by itself. Kept, the set would be copied with every undo step of the drawing. d.reserved_handles.clear(); + remember_text_fits(&mut d); Ok(d) } @@ -244,6 +337,23 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections } } +/// Capture after all tables and entity fixups, including files whose tables follow entities. +fn remember_text_fits(d: &mut Drawing) { + let mut fits = std::collections::BTreeMap::new(); + for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) { + let texts: Vec<&Text> = match &e.kind { + EntityKind::Text(t) => vec![t], + EntityKind::AttDef(a) => vec![&a.text], + EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(), + _ => continue, + }; + if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) { + fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect()); + } + } + std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits; +} + /// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the /// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's /// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it. diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 59dcf7107..f2d111ac0 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -119,15 +119,17 @@ pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { /// billionth of the object's size and distance from the origin. A normal that is the Z axis /// or the Z axis turned over moves nothing, and noise in one moves points by a negligible /// amount, so those objects keep their arcs; however small the tilt, an object far enough from -/// the origin to be moved visibly is projected. -pub(super) fn tilted(n: Vec3, pts: impl IntoIterator) -> bool { - if !n.is_finite() || n.len() < 1e-12 { +/// the origin to be moved visibly is projected. The points are only gathered for a normal off +/// the Z axis: along it (x and y exactly 0, as in nearly every drawing) nothing moves, and +/// sampling every arc of every object for that would be wasted. +pub(super) fn tilted>(n: Vec3, pts: impl FnOnce() -> I) -> bool { + if !n.is_finite() || n.len() < 1e-12 || (n.x == 0.0 && n.y == 0.0) { return false; } let m = cadcraft_geom::Mat4::ocs(n); let flip = if n.z < 0.0 { -1.0 } else { 1.0 }; let (mut moved, mut reach) = (0.0f64, 1.0f64); - for p in pts.into_iter().filter(|p| p.is_finite()) { + for p in pts().into_iter().filter(|p| p.is_finite()) { let shown = Vec2::new(flip * p.x, p.y); moved = moved.max((m.apply(p).xy() - shown).len()); reach = reach.max(p.x.abs()).max(p.y.abs()).max(p.z.abs()); @@ -204,3 +206,26 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c let z = if local.is_empty() { elevation } else { local.iter().map(|v| to_plan(v.p).z).sum::() / local.len() as f64 }; (local.into_iter().map(|v| PolyVertex { p: to_plan(v.p).xy(), ..v }).collect(), z) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A normal on the Z axis, either way up and of any length, moves no point, so [`tilted`] + /// answers without sampling the object's arcs; any other normal gathers them. + #[test] + fn a_normal_on_the_z_axis_gathers_no_points() { + let gathered = std::cell::Cell::new(0); + let pts = || { + gathered.set(gathered.get() + 1); + vec![Vec3::new(1.0, 2.0, 3.0)] + }; + for n in [Vec3::Z, Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 2.5), Vec3::new(-0.0, 0.0, -0.1)] { + assert!(!tilted(n, pts), "{n:?}"); + } + assert_eq!(gathered.get(), 0); + assert!(tilted(Vec3::new(0.0, 0.5, -0.75f64.sqrt()), pts)); + assert!(!tilted(Vec3::new(0.0, 1e-15, 1.0), pts), "noise in a plan normal still moves nothing visible"); + assert_eq!(gathered.get(), 2); + } +} diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 8fa4a9cf1..440c9a0cf 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -213,6 +213,7 @@ pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx: layout_objs.sort_by_key(|l| l.1); for (name, order, br, page, limits) in layout_objs.iter() { if name.eq_ignore_ascii_case("Model") { + d.model_page = Some(page.clone()); continue; } d.layouts.push(Layout { page: page.clone(), limits: *limits, ..Layout::new(name, *order) }); diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 9d888af5a..1a4fbaf71 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -84,7 +84,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option { verts.extend(cur); let flags = t.i(70).unwrap_or(0); let mut elevation = t.fd(38, 0.0); - if tilted(c.extrusion, run_points(&verts, elevation, flags & 1 != 0)) { + if tilted(c.extrusion, || run_points(&verts, elevation, flags & 1 != 0)) { // In a tilted plane: drawn as seen from above, at the vertices' mean height, its // vertices now plan coordinates. (verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0); @@ -244,7 +244,7 @@ pub(super) fn entity_with_table_budget( "HATCH" => { let mut k = hatch(tags, &t, curves)?; if let EntityKind::Hatch(h) = &mut k - && tilted(c.extrusion, h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true))) + && tilted(c.extrusion, || h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true))) { // In a tilted plane (a terrain face, a slope): the boundary as seen from above, // at its mean height, and the pattern direction and origin projected the same way. @@ -329,6 +329,7 @@ pub(super) fn entity_with_table_budget( other => EntityKind::Unknown(Unknown { dxf_type: other.to_string(), tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(), + graphics: Vec::new(), }), }; Some((c, k)) @@ -381,8 +382,13 @@ pub(super) fn acad_table(tags: &[Tag], table_cells_left: &mut usize) -> Table { let cell = body.get(i..end).unwrap_or(&[]); i = end; let c = T(cell); - let mut text: String = cell.iter().filter(|x| x.code == 2 || x.code == 3).map(Tag::str).collect(); - text.push_str(&c.s(1).unwrap_or_default()); + let text: String = if cell.iter().any(|x| x.code == 1) { + let mut text: String = cell.iter().filter(|x| x.code == 2 || x.code == 3).map(Tag::str).collect(); + text.push_str(&c.s(1).unwrap_or_default()); + text + } else { + cell.iter().filter(|x| x.code == 302 || x.code == 303).map(Tag::str).collect() + }; let span = |code: i32| c.i(code).and_then(|v| u32::try_from(v).ok()); // A merge starts at the cell whose span (rows 176, columns 175) is more than one cell. // Its own merged flag (173) varies by writer: CADCraft sets it, while AutoCAD-style @@ -488,6 +494,11 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option { /// needs the file's handle maps. pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) { match (kind, k) { + // Its proxy graphics (a proxy's, or the picture another kept entity was saved with), with + // the table indices resolved while the file's order is known. + (_, EntityKind::Unknown(u)) => { + u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h); + } ("DIMENSION", EntityKind::Dimension(dm)) => { dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes); dm.assoc = crate::dxf_ext::read_assoc(tags); @@ -605,7 +616,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) - let closed = flags & 1 != 0; let mut vertices: Vec = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect(); let mut elevation = t.p(10).z; - if tilted(c.extrusion, run_points(&vertices, elevation, closed)) { + if tilted(c.extrusion, || run_points(&vertices, elevation, closed)) { (vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed); thickness_along_z(&mut c); c.extrusion = Vec3::Z; diff --git a/crates/io/src/dxf_read/hatch.rs b/crates/io/src/dxf_read/hatch.rs index 65ccce7f7..a60d9ead0 100644 --- a/crates/io/src/dxf_read/hatch.rs +++ b/crates/io/src/dxf_read/hatch.rs @@ -73,7 +73,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option if !ccw { points.reverse(); } - vertices.extend(points.into_iter().map(PolyVertex::new)); + let skip = usize::from(vertices.last().zip(points.first()).is_some_and(|(last, point)| last.p.near(*point, 1e-9))); + vertices.extend(points.into_iter().skip(skip).map(PolyVertex::new)); } fn spline_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec, budget: &mut EdgeBudget) { diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 91f5ca34f..0ad59e79d 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -445,6 +445,7 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup { Some(0) => "display", Some(1) => "extents", Some(2) => "limits", + Some(3) => "view", Some(4) => "window", _ => "layout", } @@ -455,6 +456,9 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup { // 0,0 is what a page without one writes, so it reads back as none. p.image_origin = t.f(148).zip(t.f(149)).map(|(x, y)| Vec2::new(x, y)).filter(|o| o.is_finite() && o.x.abs() < 1e12 && o.y.abs() < 1e12 && *o != Vec2::ZERO); + if let Some(start) = t.0.iter().position(|tag| tag.code == 100 && tag.str() == "AcDbPlotSettings") { + p.file_plot_settings = Some(Box::new(cadcraft_doc::FilePlotSettings { tags: t.0[start + 1..].to_vec(), page: p.clone() })); + } p } diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 00b289fa4..70cfdc52b 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -296,9 +296,22 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) { for (kind, tags) in recs { let table = T(tags); + // Proxy graphics count every LAYER and LTYPE record, so one without a handle or a name + // keeps its place in the index lists (an empty name) and the records after it don't + // shift (#3094). + if table.s(5).is_none() || table.s(2).is_none() { + let name = table.s(2).unwrap_or_default(); + match kind.as_str() { + "LAYER" => rx.proxy_tables.layers.push(name), + "LTYPE" if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") => rx.proxy_tables.linetypes.push(name), + _ => {} + } + continue; + } let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue }; match kind.as_str() { "STYLE" => { + rx.proxy_tables.styles.push((name.clone(), table.s(3).unwrap_or_default())); rx.styles.insert(handle.trim().to_ascii_uppercase(), name); } "BLOCK_RECORD" => { @@ -310,9 +323,13 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) { rx.brs.insert(handle.trim().to_ascii_uppercase(), name); } "LTYPE" => { + if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") { + rx.proxy_tables.linetypes.push(name.clone()); + } rx.ltypes.insert(handle.trim().to_ascii_uppercase(), name); } "LAYER" => { + rx.proxy_tables.layers.push(name.clone()); rx.layers.insert(handle.trim().to_ascii_uppercase(), name); } "UCS" => { diff --git a/crates/io/src/dxf_region.rs b/crates/io/src/dxf_region.rs index 7c4eb9ef7..2c88976d8 100644 --- a/crates/io/src/dxf_region.rs +++ b/crates/io/src/dxf_region.rs @@ -70,7 +70,8 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option let list = xdata_list(x, "REGION"); let fin = |v: &PolyVertex| v.p.is_finite() && v.bulge.is_finite(); let first_outer = list.iter().find(|t| t.code == 1070).is_none_or(|t| t.i64() != 0); - let mut loops = vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, sources: Vec::new() }]; + let mut loops = + vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }]; let mut total = 0usize; let mut cur: Option = None; let mut expect_flag = false; @@ -81,7 +82,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option if loops.len() >= MAX_REGION_LOOPS { break; } - cur = Some(HatchLoop { vertices: Vec::new(), outer: false, sources: Vec::new() }); + cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() }); expect_flag = true; } 1070 if expect_flag => { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 68604d686..c79a5e8ee 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -165,10 +165,56 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec, std::collections::Hash /// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG /// version's (MULTILEADER from 2007). -pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String { - let mut tags = tags_for(d, Version::R2000, dwg, false); +pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) { + let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true); + let mut unwritten = craft_dwg::Unwritten::new(); + if dwg == Version::R2007 { + let omitted = legacy_visualstyles_kept(d, &kept); + if omitted != 0 { + let mut source = d.clone(); + std::sync::Arc::make_mut(&mut source.foreign).objects.retain(|object| !legacy_visual_style(object)); + tags = tags_for(&source, Version::R2000, dwg, false); + unwritten.insert("VISUALSTYLE".into(), omitted); + } + } bridge_markers(&mut tags); - craft_dxf::write_ascii(&tags) + (craft_dxf::write_ascii(&tags), unwritten) +} + +/// Version-specific DWG compatibility omissions, counted from the actual saved view. +/// Hosts use this before saving and when reporting saves through their byte-only I/O hooks. +pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten { + let mut lost = craft_dwg::Unwritten::new(); + if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) { + let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true); + let omitted = legacy_visualstyles_kept(d, &kept); + if omitted != 0 { + lost.insert("VISUALSTYLE".into(), omitted); + } + } + lost +} + +fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet) -> usize { + d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count() +} + +/// The fixed-property VISUALSTYLE layout in the 2007/2010 DXF Reference has no 176/177 +/// property pairs. The bridge cannot faithfully save this layout as a 2007 DWG. +fn legacy_visual_style(object: &cadcraft_doc::foreign::ForeignObject) -> bool { + if !object.kind.trim().eq_ignore_ascii_case("VISUALSTYLE") { + return false; + } + let mut properties = object.tags.iter().skip_while(|tag| tag.code != 100 || tag.value.trim() != "AcDbVisualStyle"); + properties.next(); + let mut fixed = false; + for tag in properties.take_while(|tag| tag.code != 100 && tag.code < 1000) { + if matches!(tag.code, 176 | 177) { + return false; + } + fixed |= matches!(tag.code, 40 | 71); + } + fixed } /// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling. diff --git a/crates/io/src/dxf_write/blocks.rs b/crates/io/src/dxf_write/blocks.rs index f0ab31491..0b48a164c 100644 --- a/crates/io/src/dxf_write/blocks.rs +++ b/crates/io/src/dxf_write/blocks.rs @@ -35,6 +35,9 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan { } EntityKind::MLeader(m) => used.extend(m.block.as_ref().map(|b| b.block.to_ascii_uppercase())), EntityKind::Dimension(dm) if dims => used.extend(dm.block.as_ref().map(|n| n.to_ascii_uppercase())), + // A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) is written with the + // block it names, which AutoCAD needs to read it (#1161). + EntityKind::Unknown(u) => used.extend(u.dimension_block().map(str::to_ascii_uppercase)), _ => {} }; for e in spaces.iter().flat_map(|s| s.iter()) { diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index eba5eb40a..235a23378 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -254,8 +254,69 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 { if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert } } +fn relative_match(a: f64, b: f64) -> bool { + a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-9 * a.abs().max(b.abs()) +} + +// A fitted dimension depends on the point distance, independently of position and direction. +fn imported_fit_scale(original: &Text, current: &Text) -> Option { + let (Some(first), Some(second)) = (original.align_pt, current.align_pt) else { + return None; + }; + let before = original.insert.xy().dist(first.xy()); + let after = current.insert.xy().dist(second.xy()); + if !before.is_finite() || !after.is_finite() || before <= 0.0 || after <= 0.0 { + return None; + } + if relative_match(before, after) { + return Some(1.0); + } + let scale = after / before; + (scale.is_finite() && scale > 0.0).then_some(scale) +} + /// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB. -pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) { +pub(super) fn text_tags( + w: &mut W, + d: &Drawing, + t: &Text, + attrib: Option<(&Attrib, Version)>, + attdef_prompt: Option<&str>, + source: (cadcraft_doc::Handle, usize), +) { + let fitted; + let t = if matches!(t.halign, HAlign::Aligned | HAlign::Fit) { + let mut resolved = t.clone(); + // Imported dimensions use the originating font's measurements. A substituted font + // must not replace them while the fitting inputs still match the read-time snapshot. + if let Some((original, style)) = d.foreign.text_fits.get(&source.0).and_then(|texts| texts.get(source.1)) + && original.value == t.value + && let Some(scale) = imported_fit_scale(original, t) + && original.style == t.style + && *style == d.text_style(&t.style).cloned().unwrap_or_default() + && original.halign == t.halign + && original.valign == t.valign + && original.oblique == t.oblique + && original.width_factor == t.width_factor + && (t.halign != HAlign::Fit || relative_match(t.height, original.height * scale)) + { + if t.halign == HAlign::Aligned && !t.value.is_empty() { + resolved.height = original.height * scale; + } + if let Some(second) = t.align_pt { + let distance = t.insert.xy().dist(second.xy()); + if distance.is_finite() && distance > 1e-12 { + resolved.rotation = t.insert.xy().angle_to(second.xy()); + } + } + } else { + resolved = cadcraft_render::fitted_text_entity(d, t, &t.value); + } + fitted = resolved; + &fitted + } else { + t + }; let attdef = attdef_prompt.is_some(); // An attribute definition with no default value is drawn as its tag, whatever its prompt: the // baseline start AutoCAD stored is judged against the tag's width too. A stored point that is diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index 81b6411dc..dd0b67f2a 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -53,6 +53,7 @@ pub(super) struct Ctx { /// The version the file ends up in (the DWG version for a DWG save): it decides which /// entity types exist (MULTILEADER from 2007). pub(super) target: Version, + pub(super) modern_table_values: bool, /// A VIEWPORT's frozen layers in group 341, as an R2000 DXF has them; otherwise 331 (DXF 2004 /// and later, and the DWG bridge, which reads only 331). pub(super) frozen_341: bool, diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index fcfa6d204..2d24887d5 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -292,7 +292,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo w.s(0, "TEXT"); common(w, e, owner, paper, "AcDbText"); thickness(w, e); - text_tags(w, d, t, None, None); + text_tags(w, d, t, None, None, (e.handle, 0)); } // Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS. EntityKind::Region(r) => { @@ -312,7 +312,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo EntityKind::AttDef(a) => { w.s(0, "ATTDEF"); common(w, e, owner, paper, "AcDbText"); - text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt)); + text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt), (e.handle, 0)); if cx.target >= Version::R2007 { multiline_tags(w, a, true); } @@ -372,7 +372,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b w.f(45, i.row_spacing); } if !i.attribs.is_empty() { - for a in &i.attribs { + for (index, a) in i.attribs.iter().enumerate() { let ah = w.h(); w.s(0, "ATTRIB"); w.s(5, ah); @@ -385,7 +385,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b w.i(60, 1); } w.s(100, "AcDbText"); - text_tags(w, d, &a.text, Some((a, cx.target)), None); + text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index)); if cx.target >= Version::R2007 { multiline_tags(w, a, false); } @@ -522,27 +522,45 @@ fn write_table_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b let merge = cell.and_then(|x| x.merged).filter(|&(a, b)| a >= 1 && b >= 1 && (a, b) != (1, 1)); w.i(171, 1); w.i(172, 0); - w.i(173, i64::from(covered || merge.is_some())); + w.i(173, i64::from(covered || (!cx.modern_table_values && merge.is_some()))); w.i(174, 0); let (rs, cs) = if covered { (0, 0) } else { merge.map(|(a, b)| (span(a), span(b))).unwrap_or((1, 1)) }; w.i(175, cs); w.i(176, rs); w.i(91, 0); + if cx.modern_table_values { + w.i(92, 0); + } w.i(178, 0); w.f(145, 0.0); if let Some(h) = cell.and_then(|x| x.text_height).filter(|h| h.is_finite() && *h > 0.0) { w.f(140, h); } - // Long text: 250-character code-2 chunks, the rest in code 1. - let chars: Vec = cell.map(|x| x.text.chars().collect()).unwrap_or_default(); + if cx.modern_table_values { + w.s(301, "CELL_VALUE"); + w.i(93, 4); + w.i(90, 4); + } + let chars: Vec = cell.filter(|_| !cx.modern_table_values || !covered).map(|x| x.text.chars().collect()).unwrap_or_default(); let chunks: Vec = chars.chunks(250).map(|c| c.iter().collect()).collect(); let n = chunks.len(); - for (i, ch) in chunks.into_iter().enumerate() { + for (i, ch) in chunks.iter().enumerate() { w.s(if i + 1 == n { 1 } else { 2 }, ch); } if n == 0 { w.s(1, ""); } + if cx.modern_table_values { + w.i(94, 0); + w.s(300, ""); + for (i, ch) in chunks.iter().enumerate() { + w.s(if i + 1 == n { 302 } else { 303 }, ch); + } + if n == 0 { + w.s(302, ""); + } + w.s(304, "ACVALUE_END"); + } } } w.s(1001, dxf_ext::APP); @@ -627,7 +645,7 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo w.i(71, i64::from(h.associative)); w.i(91, h.loops.len() as i64); for l in &h.loops { - w.i(92, 2 | if l.outer { 1 } else { 0 }); + w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16))); let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0); w.i(72, i64::from(has_bulge)); w.i(73, 1); diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 609e95212..553fd6247 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -26,6 +26,7 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("CELTSCALE", 40), ("DIMSCALE", 40), ("DIMSTYLE", 2), + ("DIMASSOC", 280), ("LUNITS", 70), ("LUPREC", 70), ("AUNITS", 70), @@ -124,6 +125,7 @@ fn dim_header_vars(w: &mut W, d: &Drawing) { } } +/// Write modelled HEADER variables with their declared DXF group types, then dimension style variables. pub(super) fn header_vars(w: &mut W, d: &Drawing) { for (name, code) in HEADER_VARS { let Some(v) = d.header.get(name) else { continue }; @@ -153,7 +155,7 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) { w.f(c, f); } } - (c @ (62 | 70 | 290 | 370), v) => { + (c @ (62 | 70 | 280 | 290 | 370), v) => { if let Some(i) = v.as_i64() { w.s(9, format!("${name}")); w.i(c, i); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index de24f3acd..4e18a88e2 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -411,22 +411,28 @@ struct LayoutWriteData<'a> { ucs: Option<&'a Ucs>, /// The layout's limits as read (`None`: the default 0,0 to 12,9). limits: Option<(Vec2, Vec2)>, + /// Whether this is the Model layout (block record *Model_Space). + model: bool, } /// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come /// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where /// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file /// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot -/// styles), and 16 when its scale is standard. -fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 { +/// styles), and 16 when its scale is standard. 1024 ("ModelType", DXF Reference, PLOTSETTINGS +/// group 70) follows the layout: set for the Model layout, cleared for a paper-space layout even +/// when the file had it, since it would mark that layout as model space. +fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 { const MODELED: i64 = 2 | 4 | 128; const STANDARD_SCALE: i64 = 16; + const MODEL_TYPE: i64 = 1024; let kept = match page.file_plot_flags { Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE, Some(f) if !standard => f & !MODELED & !STANDARD_SCALE, Some(f) => f & !MODELED, None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 }, }; + let kept = if model { kept | MODEL_TYPE } else { kept & !MODEL_TYPE }; kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 } } @@ -434,30 +440,33 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData< let d = context.drawing; let layout_dict = context.dictionary; let h = data.handle; - let name = data.name; - let tab = data.tab; - let brh = data.block_record; - let flags = data.flags; let page = data.page; let view = data.view; + w.s(0, "LAYOUT"); + w.s(5, h); + w.s(330, layout_dict.to_string()); + w.s(100, "AcDbPlotSettings"); + write_plot_settings(w, d, page, data.model); + write_layout_data(w, d, data, view); +} + +fn write_plot_settings(w: &mut W, d: &Drawing, page: &PageSetup, model: bool) { + let start = w.t.len(); // Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units // per 143 drawing units). let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 }; // The file's standard scale (such as 1:50) while the scale is still the one read with it. let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code); let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some(); - let plot_flags = plot_layout_flags(page, standard); + let plot_flags = plot_layout_flags(page, standard, model); let plot_type = match page.plot_area.as_str() { "display" => 0, "extents" => 1, "limits" => 2, + "view" => 3, "window" => 4, _ => 5, }; - w.s(0, "LAYOUT"); - w.s(5, h); - w.s(330, layout_dict.to_string()); - w.s(100, "AcDbPlotSettings"); w.s(1, ""); let device = page.device.trim(); w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device }); @@ -494,6 +503,49 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData< let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO); w.f(148, origin.x); w.f(149, origin.y); + if let Some(kept) = &page.file_plot_settings { + let current = w.t.split_off(start); + write_plot_settings(w, d, &kept.page, model); + let baseline = w.t.split_off(start); + let changed = |code| { + (matches!(code, 142 | 143 | 147) && page.scale != kept.page.scale) + || (code == 72 + && (page.paper_mm != kept.page.paper_mm + || (page.paper_mm.is_none() + && kept + .tags + .iter() + .find(|tag| tag.code == 72) + .zip(current.iter().find(|tag| tag.code == 72)) + .is_some_and(|(old, now)| matches!(old.i64(), 0 | 1) && old.i64() != now.i64())))) + || current.iter().find(|tag| tag.code == code) != baseline.iter().find(|tag| tag.code == code) + }; + for tag in &kept.tags { + if changed(tag.code) || (tag.code == 73 && !(0..=3).contains(&tag.i64())) { + if tag.code == 70 + && let Some((now, before)) = current.iter().find(|tag| tag.code == 70).zip(baseline.iter().find(|tag| tag.code == 70)) + { + let mask = (now.i64() ^ before.i64()) | 1024; + w.i(70, (tag.i64() & !mask) | (now.i64() & mask)); + continue; + } + w.t.extend(current.iter().filter(|new| new.code == tag.code).cloned()); + } else if tag.code == 70 { + w.i(70, if model { tag.i64() | 1024 } else { tag.i64() & !1024 }); + } else { + w.t.push(tag.clone()); + } + } + w.t.extend(current.iter().filter(|tag| changed(tag.code) && !kept.tags.iter().any(|old| old.code == tag.code)).cloned()); + } +} + +fn write_layout_data(w: &mut W, d: &Drawing, data: LayoutWriteData<'_>, view: Option<(Vec2, f64)>) { + let name = data.name; + let tab = data.tab; + let flags = data.flags; + let brh = data.block_record; + let page = data.page; w.s(100, "AcDbLayout"); w.s(1, name); w.i(70, flags); @@ -592,8 +644,8 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { w.s(3, &l.name); w.s(350, layout_handles.get(i).cloned().unwrap_or_default()); } - // Model space has no page setup of its own: write what PLOT does for it, the drawing extents - // fitted to the paper (plot type 1, scaled to fit). The default page's "layout" area is + // A new drawing has no saved Model page setup: write the drawing extents fitted to the + // paper (plot type 1, scaled to fit), as PLOT does. The default page's "layout" area is // plot type 5, "Layout information" (DXF Reference, PLOTSETTINGS group 74), which means // nothing for model space: another program's Plot dialog then shows no plot area or scale. let model_page = PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..PageSetup::default() }; @@ -606,10 +658,11 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { tab: 0, block_record: ms_br, flags: 1, - page: &model_page, + page: d.model_page.as_ref().unwrap_or(&model_page), view: None, ucs: None, limits: None, + model: true, }, ); for (i, (_, brh, l)) in ps_brs.iter().enumerate() { @@ -627,6 +680,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { view: l.view, ucs: l.ucs.as_ref(), limits: l.limits, + model: false, }, ); } @@ -1048,7 +1102,7 @@ pub(super) fn tags_kept_for( .collect(); user_blocks.iter_mut().for_each(|b| b.1 = format!("{:X}", 0)); let user_blocks: Vec<(String, String, &Block)> = user_blocks.into_iter().map(|(n, _, b)| (n, w.h(), b)).collect(); - let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, ..Ctx::default() }; + let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, modern_table_values: !bridge && version >= Version::R2007, ..Ctx::default() }; cx.block_records = user_blocks.iter().map(|(n, h, _)| (n.to_ascii_uppercase(), h.clone())).collect(); let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect(); let mut dim_defs = dimension_block_definitions(d, &all_spaces, &dim_plan, &mut w, &mut cx); @@ -1289,9 +1343,49 @@ pub(super) fn tags_kept_for( crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013); add_class_instance_counts(&mut w.t, target); mark_xrefs(&mut w.t, d); + plot_settings_compatibility(&mut w.t, target); (w.t, kept) } +fn plot_settings_compatibility(tags: &mut Vec, target: Version) { + let mut objects = HashSet::new(); + let mut section = String::new(); + let mut section_start = false; + for tag in tags.iter() { + if tag.code == 0 { + section_start = tag.str() == "SECTION"; + if tag.str() == "ENDSEC" { + section.clear(); + } + } else if section_start && tag.code == 2 { + section = tag.str(); + section_start = false; + } else if section == "OBJECTS" && tag.code == 5 { + objects.extend(u64::from_str_radix(tag.str().trim(), 16).ok().filter(|handle| *handle != 0)); + } + } + let mut kind = String::new(); + let mut subclass = String::new(); + tags.retain(|tag| { + if tag.code == 0 { + kind = tag.str(); + subclass.clear(); + } else if tag.code == 100 { + subclass = tag.str(); + } + if !matches!(kind.as_str(), "LAYOUT" | "PLOTSETTINGS") { + return true; + } + if subclass == "AcDbPlotSettings" && matches!(tag.code, 76..=78) { + return target >= Version::R2004; + } + if matches!(subclass.as_str(), "AcDbPlotSettings" | "AcDbLayout") && tag.code == 333 { + return target >= Version::R2007 && u64::from_str_radix(tag.str().trim(), 16).ok().is_some_and(|handle| objects.contains(&handle)); + } + true + }); +} + /// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups /// keep a portrait size and a landscape flag. The values read from the file are written back /// as they were while they still describe that size and orientation, whatever convention the diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 4dba955e4..cd787e3ac 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -38,7 +38,7 @@ pub use cadcraft_doc::Format; pub use craft_dxf::Version; pub use dxf_raw::{ObjectRecord, object_records}; pub use dxf_read::entity_from_groups; -pub use dxf_write::{entity_groups, proxies_lost}; +pub use dxf_write::{dwg_compat_lost, entity_groups, proxies_lost}; pub use pdf::{PdfOptions, pdf, plot}; /// How a drawing is saved as DXF or DWG. @@ -165,8 +165,13 @@ pub fn write_noted(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> R /// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge /// reads them as that version. fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec, craft_dwg::Unwritten)> { - let bridge = dxf_write::dwg_bridge(d, version); - craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error) + let (bridge, omitted) = dxf_write::dwg_bridge(d, version); + let (bytes, mut unwritten) = craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)?; + for (kind, omitted) in omitted { + let count = unwritten.entry(kind).or_default(); + *count = count.saturating_add(omitted); + } + Ok((bytes, unwritten)) } /// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in diff --git a/crates/io/src/pdf_read.rs b/crates/io/src/pdf_read.rs index f683f2e71..7fb394711 100644 --- a/crates/io/src/pdf_read.rs +++ b/crates/io/src/pdf_read.rs @@ -20,7 +20,7 @@ //! Adapted from CADCraft PR #2787, commit ec17f63f189d1dccf91357701f9bba243ca88dd5 //! (MIT OR Apache-2.0). PDF interpretation stays in craft-pdf; this module maps it to CAD entities. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; use std::sync::{ Arc, atomic::{AtomicU8, Ordering}, @@ -237,9 +237,13 @@ struct Collector { /// Characters of text the page may still add. text_left: usize, run: Option, - /// The text last added: where it starts, its string and its size, so the same text drawn again - /// at the same place (a fill and then its stroke, render mode 2) is not added twice. - last_text: Option<(Vec2, String, f64)>, + /// The glyphs filled since the last shape, image or stroked glyph, in paint order: where each + /// starts and its characters. Render mode 2 fills a whole text show and then draws it again for + /// its stroke; a stroke glyph that repeats the next one here is that replay and is skipped. + /// Each was charged to the page's text budget, which bounds the queue. + filled: VecDeque<(Vec2, String)>, + /// Whether a glyph was stroked since the last fill: the next fill starts a new queue. + stroking: bool, left_out: BTreeMap, failure: Option, /// The clips in force, outermost first: a rectangle in page points, or `None` for another shape. @@ -297,7 +301,8 @@ impl Collector { glyphs: 0, text_left: MAX_TEXT_CHARS, run: None, - last_text: None, + filled: VecDeque::new(), + stroking: false, left_out: BTreeMap::new(), failure: None, clips: Vec::new(), @@ -517,7 +522,7 @@ impl Collector { } }) .enumerate() - .map(|(i, (vertices, _))| HatchLoop { vertices, outer: i == 0, sources: Vec::new() }) + .map(|(i, (vertices, _))| HatchLoop { vertices, outer: i == 0, boundary_flags: None, sources: Vec::new() }) .collect(); if kept_whole { self.approximated("curved filled shapes crossing a clip kept whole"); @@ -554,10 +559,15 @@ impl Collector { self.add(LAYER_FILLS, color, Lineweight::ByLayer, EntityKind::Hatch(hatch), verts); } - fn glyph_text(&mut self, glyph: &Glyph<'_>, to_page: Affine, glyph_to_text: Affine, paint: &Paint<'_>) { + fn glyph_text(&mut self, glyph: &Glyph<'_>, to_page: Affine, glyph_to_text: Affine, paint: &Paint<'_>, stroke: bool) { if !self.opts.text || self.failure.is_some() { return; } + if stroke { + self.stroking = true; + } else if std::mem::take(&mut self.stroking) { + self.filled.clear(); + } self.glyphs += 1; if self.glyphs > MAX_GLYPHS { return self.fail(&format!("more than {MAX_GLYPHS} glyphs on the page")); @@ -594,29 +604,42 @@ impl Collector { let end = g.advance_width().map(|w| pt(m * Point::new(f64::from(w), 0.0))).filter(|e| e.x.is_finite() && e.y.is_finite()); // A glyph is kept when its middle (half its advance along, half the cap height up) lies in // the clip. Its origin is no test: a plotter often clips each text to a box drawn through - // that origin (or ends the page clip there), and rounding then puts it a hair outside. + // that origin (or ends the page clip there), and rounding then puts it a hair outside. A clip + // with no area (two clips that only touch) shows nothing. let half = end.map_or(dir * (0.25 * em), |e| (e - origin) * 0.5); let middle = origin + half + ey * (0.5 * CAP_HEIGHT); if let Some((lo, hi)) = self.clip() - && !((lo.x..=hi.x).contains(&middle.x) && (lo.y..=hi.y).contains(&middle.y)) + && !(lo.x < hi.x && lo.y < hi.y && (lo.x..=hi.x).contains(&middle.x) && (lo.y..=hi.y).contains(&middle.y)) { return; } + if stroke { + if self.filled.front().is_some_and(|(at, s)| (*at - origin).len() <= 1e-9 * em.max(1.0) && *s == ch) { + self.filled.pop_front(); + return; + } + self.filled.clear(); + } // The characters this glyph adds, and a space before them, against the page's text budget. let Some(left) = self.text_left.checked_sub(ch.chars().count().saturating_add(1)) else { return self.fail(&format!("more than {MAX_TEXT_CHARS} characters of text on the page")); }; self.text_left = left; + if !stroke { + self.filled.push_back((origin, ch.clone())); + } if let Some(run) = &mut self.run { - // A fill and its stroke (render mode 2) arrive as two calls for one glyph at one origin; - // this is tested first, since the gap measured from where the glyph ended is negative. + // The same glyph drawn again at the same origin adds nothing; this is tested first, + // since the gap measured from where the glyph ended is negative. if run.color == color && (origin - run.last).len() <= 1e-9 * em.max(1.0) && run.text.ends_with(&ch) { return; } let rel = origin - run.last; let along = rel.x * run.dir.x + rel.y * run.dir.y; - let across = (rel.x * run.dir.y - rel.y * run.dir.x).abs(); + // Measured from the first glyph, so a run cannot drift off its baseline a step at a time. + let from_start = origin - run.start; + let across = (from_start.x * run.dir.y - from_start.y * run.dir.x).abs(); let same = run.color == color && (run.em - em).abs() <= 0.02 * em && run.dir.x * dir.x + run.dir.y * dir.y > 0.9999 && across <= 0.1 * em; // Where the previous glyph ended, else the previous origin plus an average glyph. let gap = match run.end { @@ -630,7 +653,7 @@ impl Collector { if gap > 0.15 * em && !run.text.ends_with(' ') && !ch.starts_with(' ') { run.text.push(' '); } - // A fill and its stroke arrive as two calls for one glyph. + // The same glyph drawn again where the last one started adds nothing. if !(along.abs() < 1e-9 * em.max(1.0) && run.text.ends_with(&ch)) { run.text.push_str(&ch); run.glyphs += 1; @@ -650,14 +673,6 @@ impl Collector { if value.trim().is_empty() { return; } - if let Some((at, text, em)) = &self.last_text - && *text == value - && (*at - run.start).len() <= 1e-9 * run.em.max(1.0) - && (*em - run.em).abs() <= 1e-9 * run.em.max(1.0) - { - return; - } - self.last_text = Some((run.start, value.clone(), run.em)); let fit_end = run.end.filter(|e| run.glyphs >= 2 && (*e - run.start).len() > 1e-9); let text = Text { insert: v3(run.start), @@ -695,16 +710,38 @@ fn translucent(paint: &Paint<'_>) -> bool { matches!(paint, Paint::Color(c) if { let [_, _, _, a] = c.to_rgba().to_rgba8(); a > 0 && a < 255 }) } -/// The rectangle a clip path is, when it is an axis-aligned one (four or five straight points). +/// The rectangle a clip path is, when it is one axis-aligned subpath of four or five straight +/// points; a rectangle with no area when its subpaths enclose none, since that clip shows nothing. fn rect_of(path: &BezPath) -> Option { - let mut pts: Vec = Vec::new(); + let mut subpaths: Vec> = Vec::new(); + let mut closed = false; for el in path.elements() { match *el { - PathEl::MoveTo(p) | PathEl::LineTo(p) => pts.push(p), - PathEl::ClosePath => {} + PathEl::MoveTo(p) => { + subpaths.push(vec![p]); + closed = false; + } + PathEl::LineTo(p) => { + // A line after a close starts a new subpath where the closed one started. + if closed { + let start = subpaths.last().and_then(|s| s.first()).copied().unwrap_or(p); + subpaths.push(vec![start]); + closed = false; + } + match subpaths.last_mut() { + Some(s) => s.push(p), + None => subpaths.push(vec![p]), + } + } + PathEl::ClosePath => closed = true, _ => return None, } } + if !subpaths.is_empty() && subpaths.iter().all(|s| collinear(s)) { + return Some(Rect::ZERO); + } + let [pts] = subpaths.as_slice() else { return None }; + let mut pts = pts.clone(); if !(4..=5).contains(&pts.len()) { return None; } @@ -733,6 +770,14 @@ fn rect_of(path: &BezPath) -> Option { .then(|| Rect::new(x0, y0, x1, y1)) } +/// Whether the points lie on one straight line, or at one point, to a millionth of a point. +fn collinear(pts: &[Point]) -> bool { + let Some(&a) = pts.first() else { return true }; + let far = pts.iter().map(|p| *p - a).max_by(|u, v| u.hypot2().total_cmp(&v.hypot2())).unwrap_or_default(); + let len = far.hypot(); + len < 1e-6 || pts.iter().all(|p| (far.cross(*p - a) / len).abs() < 1e-6) +} + /// How a shape lies against a clip rectangle. enum Relation { Inside, @@ -934,7 +979,7 @@ impl<'a> Device<'a> for Collector { } self.flush_text(); // Text drawn again after a shape is a new label on top, not the stroke of the text before. - self.last_text = None; + self.filled.clear(); match mode { PathDrawMode::Fill(rule) => self.fill(path, transform, paint, rule), PathDrawMode::Stroke(p) => { @@ -962,13 +1007,15 @@ impl<'a> Device<'a> for Collector { } } fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, mode: &GlyphDrawMode) { - if matches!(mode, GlyphDrawMode::Fill | GlyphDrawMode::Stroke(_)) { - self.glyph_text(glyph, transform, glyph_transform, paint); + match mode { + GlyphDrawMode::Fill => self.glyph_text(glyph, transform, glyph_transform, paint, false), + GlyphDrawMode::Stroke(_) => self.glyph_text(glyph, transform, glyph_transform, paint, true), + _ => {} } } fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) { self.flush_text(); - self.last_text = None; + self.filled.clear(); self.left_out(LeftOut::Image); } fn pop_clip_path(&mut self) { diff --git a/crates/io/src/pdf_read/fill.rs b/crates/io/src/pdf_read/fill.rs index 948d280c6..a4930bce4 100644 --- a/crates/io/src/pdf_read/fill.rs +++ b/crates/io/src/pdf_read/fill.rs @@ -50,7 +50,10 @@ pub(super) fn normalize(mut loops: Vec, rule: FillRule, max_vertices: match rule { FillRule::EvenOdd => { - let probes: Vec = polygons.iter().map(|p| interior_probe(p)).collect(); + // Contours that don't meet are placed by a point of their own boundary: a point nudged + // inside an edge can land in a contour drawn close to it. + let apart = sampled <= MAX_TOPOLOGY_POINTS && edges_meet(&polygons) == Some(false); + let probes: Vec = polygons.iter().map(|p| if apart { boundary_point(p) } else { interior_probe(p) }).collect(); let mut depth = vec![0usize; loops.len()]; containment(&polygons, &probes, &mut work, |i, _| depth[i] += 1)?; for (loop_, depth) in loops.iter_mut().zip(depth) { @@ -71,7 +74,7 @@ pub(super) fn normalize(mut loops: Vec, rule: FillRule, max_vertices: .collect(); // No two contours meet, so a contour lies inside another exactly when a point of its // own boundary does. - let probes: Vec = polygons.iter().map(|p| longest_edge(p).map_or(Vec2::ZERO, |(a, b)| (a + b) * 0.5)).collect(); + let probes: Vec = polygons.iter().map(|p| boundary_point(p)).collect(); // The winding number just inside each contour. let mut winding = sign.clone(); containment(&polygons, &probes, &mut work, |i, j| winding[i] += sign[j])?; @@ -301,6 +304,11 @@ fn interior_probe(polygon: &[Vec2]) -> Vec2 { Vec2::new((a.x + b.x) * 0.5, (a.y + b.y) * 0.5) } +/// The middle of the longest edge. +fn boundary_point(polygon: &[Vec2]) -> Vec2 { + longest_edge(polygon).map_or(Vec2::ZERO, |(a, b)| (a + b) * 0.5) +} + fn longest_edge(polygon: &[Vec2]) -> Option<(Vec2, Vec2)> { polygon .iter() @@ -311,7 +319,9 @@ fn longest_edge(polygon: &[Vec2]) -> Option<(Vec2, Vec2)> { } fn signed_area(polygon: &[Vec2]) -> f64 { - polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()).map(|(a, b)| a.x * b.y - b.x * a.y).sum::() * 0.5 + // Relative to the first vertex, so the products far from the origin don't round the area away. + let Some(&o) = polygon.first() else { return 0.0 }; + polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()).map(|(a, b)| (*a - o).cross(*b - o)).sum::() * 0.5 } fn contains(polygon: &[Vec2], point: Vec2) -> bool { @@ -368,7 +378,7 @@ fn tessellate_nonzero(polygons: &[Vec], sampled_vertices: usize, max_verti .ok_or("PDF fill tessellation returned an invalid index") }) .collect::, _>>()?; - Ok(HatchLoop { vertices, outer: true, sources: Vec::new() }) + Ok(HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }) }) .collect() } @@ -416,7 +426,12 @@ mod tests { use super::*; fn polygon(points: &[(f64, f64)]) -> HatchLoop { - HatchLoop { vertices: points.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), outer: false, sources: Vec::new() } + HatchLoop { + vertices: points.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), + outer: false, + boundary_flags: None, + sources: Vec::new(), + } } fn square(x0: f64, y0: f64, x1: f64, y1: f64, clockwise: bool) -> HatchLoop { @@ -441,6 +456,7 @@ mod tests { .map(|&(x, y)| PolyVertex { bulge: quarter * turn, ..PolyVertex::new(Vec2::new(x, y)) }) .collect(), outer: false, + boundary_flags: None, sources: Vec::new(), } } @@ -460,7 +476,7 @@ mod tests { #[test] fn a_disc_of_two_half_circles_is_kept() { let half = |x: f64| PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(x, 0.0)) }; - let disc = HatchLoop { vertices: vec![half(-1.0), half(1.0)], outer: false, sources: Vec::new() }; + let disc = HatchLoop { vertices: vec![half(-1.0), half(1.0)], outer: false, boundary_flags: None, sources: Vec::new() }; for rule in [FillRule::EvenOdd, FillRule::NonZero] { let result = normalize(vec![disc.clone()], rule, 10_000, TOL).expect("valid contour"); assert_eq!(result.len(), 1); @@ -557,6 +573,24 @@ mod tests { assert!(filled(&result, Vec2::new(shift + 11.0, shift + 5.1))); } + #[test] + fn a_unit_square_far_from_the_origin_keeps_its_area() { + // At 2^29 the products of the coordinates are too large to keep a unit of area. + for shift in [0.0, 2f64.powi(29)] { + let result = normalize(vec![square(shift, shift, shift + 1.0, shift + 1.0, false)], FillRule::NonZero, 100, TOL).expect("valid contour"); + assert_eq!(result.len(), 1, "at {shift}"); + } + } + + #[test] + fn even_odd_hole_close_to_its_outer_edge_is_classified_by_depth() { + // The hole runs 1e-6 below the outer square's top edge, closer than a point nudged inside + // that edge. + let input = vec![square(0.0, 0.0, 10.0, 8.0, false), square(4.0, 7.0, 6.0, 7.999_999, false)]; + let result = normalize(input, FillRule::EvenOdd, 1000, TOL).expect("valid contours"); + assert!(result[0].outer && !result[1].outer, "{result:?}"); + } + #[test] fn even_odd_nested_contours_are_classified_by_depth() { let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, false)], FillRule::EvenOdd, 1000, TOL) diff --git a/crates/io/src/roundtrip/tests.rs b/crates/io/src/roundtrip/tests.rs index e4d4d2381..89faf7105 100644 --- a/crates/io/src/roundtrip/tests.rs +++ b/crates/io/src/roundtrip/tests.rs @@ -39,7 +39,11 @@ fn drawing() -> Drawing { d.add( &Space::Model, Common::default(), - EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }), + EntityKind::Unknown(Unknown { + dxf_type: "ACME_WIDGET".into(), + tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")], + graphics: Vec::new(), + }), ) .unwrap(); d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap(); @@ -521,7 +525,7 @@ fn corpus_round_trip_report() { fn types_the_dwg_writer_cannot_write_are_reported_lost() { use corpus::{CorpusReport, FileReport, Format, round_trip}; crate::dwg_worker::allow_in_process(); - let unknown = |t: &str, tags: Vec| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags }); + let unknown = |t: &str, tags: Vec| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags, graphics: Vec::new() }); let mut d = Drawing::new_metric(); let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")]; d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap(); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index d3264390c..f56471954 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -111,6 +111,7 @@ fn sample() -> Drawing { loops: vec![HatchLoop { vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(2.0, 0.0)), PolyVertex::new(Vec2::new(2.0, 2.0))], outer: true, + boundary_flags: Some(3), sources: Vec::new(), }], scale: 1.0, @@ -2029,6 +2030,514 @@ fn intl_text(value: &str) -> Text { } } +fn two_point_text_sample() -> Drawing { + let mut drawing = Drawing::new_metric(); + let mut block = Block::new("Labels"); + let mut attribs = Vec::new(); + for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() { + for multiplier in [1.0, 2.0] { + let text = + Text { insert: Vec3::ZERO, align_pt: Some(Vec3::new(30.0 * multiplier, 4.0 * multiplier, 0.0)), halign, ..intl_text("SYNTHETIC") }; + drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap(); + let attribute = Attrib { + tag: format!("LABEL{index}_{multiplier}"), + text, + invisible: false, + constant: false, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + block.entities.push(Entity::new(Handle(0x500 + attribs.len() as u64), EntityKind::AttDef(attribute.clone()))); + attribs.push(attribute); + } + } + drawing.blocks.insert(block.name.clone(), std::sync::Arc::new(block)); + drawing + .add( + &Space::Model, + Common::default(), + EntityKind::Insert(Insert { + block: "Labels".into(), + insert: Vec3::ZERO, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs, + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }), + ) + .unwrap(); + drawing +} + +fn two_point_texts(drawing: &Drawing) -> Vec<&Text> { + let mut texts = Vec::new(); + for entity in drawing.model.iter() { + match &entity.kind { + EntityKind::Text(text) => texts.push(text), + EntityKind::Insert(insert) => texts.extend(insert.attribs.iter().map(|attribute| &attribute.text)), + _ => {} + } + } + texts.extend( + drawing + .block("Labels") + .unwrap() + .entities + .iter() + .filter_map(|entity| if let EntityKind::AttDef(attribute) = &entity.kind { Some(&attribute.text) } else { None }), + ); + texts +} + +fn edit_two_point_texts(d: &mut Drawing, edit: impl Fn(&mut Text)) { + fn store(store: &mut EntityStore, edit: &impl Fn(&mut Text)) { + for handle in store.handles() { + store.modify(handle, |e| match &mut e.kind { + EntityKind::Text(t) => edit(t), + EntityKind::AttDef(a) => edit(&mut a.text), + EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| edit(&mut a.text)), + _ => {} + }); + } + } + store(&mut d.model, &edit); + for block in d.blocks.values_mut() { + store(&mut std::sync::Arc::make_mut(block).entities, &edit); + } +} + +// Original synthetic DXF records with measurements deliberately different from our stroke font. +fn imported_two_point_text_sample() -> Drawing { + let tags = craft_dxf::parse(write_dxf(&two_point_text_sample()).as_bytes()).unwrap(); + let mut altered = tags.clone(); + // Work on complete records, including their leading group 0. + let starts: Vec = tags.iter().enumerate().filter_map(|(i, t)| (t.code == 0).then_some(i)).chain([tags.len()]).collect(); + for pair in starts.windows(2) { + let record = &tags[pair[0]..pair[1]]; + if !matches!(record[0].str().as_ref(), "TEXT" | "ATTDEF" | "ATTRIB") { + continue; + } + let number = |code| record.iter().find(|t| t.code == code).map(|t| t.str().parse::().unwrap()).unwrap_or(0.0); + let distance = Vec2::new(number(10), number(20)).dist(Vec2::new(number(11), number(21))); + let width = cadcraft_fonts::shape_stroke("SYNTHETIC", 2.5, 1.0, 0.0).width; + let aligned = number(72) == 3.0; + let code = if aligned { 40 } else { 41 }; + let dimension = if aligned { 2.5 } else { 1.0 } * distance / width * 1.15; + for tag in &mut altered[pair[0]..pair[1]] { + if tag.code == code { + *tag = craft_dxf::Tag::new(code, craft_dxf::Value::Real(dimension)); + } + if tag.code == 50 { + *tag = craft_dxf::Tag::new(50, craft_dxf::Value::Real(0.0)); + } + } + } + read_dxf(craft_dxf::write_ascii(&altered).as_bytes()).unwrap() +} + +fn check_two_point_save(d: &Drawing, name: &str, recompute: bool, rotation: bool) { + let saved = read(&write(d, name).unwrap(), name).unwrap(); + let before = two_point_texts(d); + let after = two_point_texts(&saved); + assert_eq!(after.len(), before.len()); + for (original, text) in before.into_iter().zip(&after) { + if rotation { + assert!((text.rotation - text.insert.xy().angle_to(text.align_pt.unwrap().xy())).abs() < 1e-10, "{name}: {text:?}"); + } + if recompute { + let width = + cadcraft_fonts::shape_stroke_dir(&original.value, original.height, original.width_factor, original.oblique, Some(false)).width; + let scale = original.insert.xy().dist(original.align_pt.unwrap().xy()) / width; + let (height, factor) = if original.halign == HAlign::Aligned { + (original.height * scale, original.width_factor) + } else { + (original.height, original.width_factor * scale) + }; + assert!((text.height / height - 1.0).abs() < 1e-12, "height: {name}"); + assert!((text.width_factor / factor - 1.0).abs() < 1e-12, "width factor: {name}"); + } else { + assert!((text.height - original.height).abs() < 1e-10, "{name}"); + assert!((text.width_factor - original.width_factor).abs() < 1e-10, "{name}"); + } + } + let again = read(&write(&saved, name).unwrap(), name).unwrap(); + for (first, second) in after.into_iter().zip(two_point_texts(&again)) { + assert!((first.rotation - second.rotation).abs() < 1e-10, "{name}"); + assert!((first.height - second.height).abs() < 1e-10, "{name}"); + assert!((first.width_factor - second.width_factor).abs() < 1e-10, "{name}"); + } +} + +fn two_point_formats() -> [&'static str; 2] { + crate::dwg_worker::allow_in_process(); + ["fit.dxf", "fit.dwg"] +} + +#[test] +fn two_point_imported_measurements_survive_save() { + for name in two_point_formats() { + check_two_point_save(&imported_two_point_text_sample(), name, false, false); + } +} + +#[test] +fn two_point_imported_rotation_follows_points() { + for name in two_point_formats() { + check_two_point_save(&imported_two_point_text_sample(), name, false, true); + } +} + +fn transform_two_point_sample(d: &mut Drawing, matrix: cadcraft_geom::Mat3) { + // Transform the reference itself so attached attributes follow the production path. + for handle in d.model.handles() { + d.model.modify(handle, |entity| entity.kind.transform(&matrix)); + } +} + +#[test] +fn two_point_imported_measurements_survive_move() { + let mut d = imported_two_point_text_sample(); + transform_two_point_sample(&mut d, cadcraft_geom::Mat3::translate(Vec2::new(47.0, -19.0))); + for name in two_point_formats() { + check_two_point_save(&d, name, false, true); + } +} + +#[test] +fn two_point_imported_measurements_survive_rotate() { + let mut d = imported_two_point_text_sample(); + transform_two_point_sample(&mut d, cadcraft_geom::Mat3::rotate_about(Vec2::new(7.0, -3.0), 0.73)); + for name in two_point_formats() { + check_two_point_save(&d, name, false, true); + } +} + +#[test] +fn two_point_imported_measurements_follow_uniform_scale() { + let mut d = imported_two_point_text_sample(); + let imported = d.clone(); + transform_two_point_sample(&mut d, cadcraft_geom::Mat3::scale_about(Vec2::new(7.0, -3.0), 2.0)); + for (before, scaled) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).take(8) { + assert!((scaled.height - before.height * 2.0).abs() < 1e-10); + assert!((scaled.width_factor - before.width_factor).abs() < 1e-10); + } + for name in two_point_formats() { + check_two_point_save(&d, name, false, true); + } +} + +#[test] +fn two_point_changed_fit_height_recomputes_measurements() { + let mut d = imported_two_point_text_sample(); + edit_two_point_texts(&mut d, |t| t.height *= 1.4); + for name in two_point_formats() { + // Aligned height is derived from distance, so editing it alone preserves the import. + let saved = read(&write(&d, name).unwrap(), name).unwrap(); + for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) { + if before.halign == HAlign::Fit { + let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value); + assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12); + } + } + } +} + +#[test] +fn two_point_imported_distance_uses_relative_tolerance() { + let mut d = imported_two_point_text_sample(); + edit_two_point_texts(&mut d, |t| { + let point = t.align_pt.as_mut().unwrap(); + point.x *= 1.0 + 0.5e-9; + point.y *= 1.0 + 0.5e-9; + }); + for name in two_point_formats() { + check_two_point_save(&d, name, false, true); + } +} + +#[test] +fn two_point_changed_fitting_inputs_recompute_measurements() { + for input in ["style", "oblique", "width factor"] { + let mut d = imported_two_point_text_sample(); + edit_two_point_texts(&mut d, |t| match input { + "style" => t.style = "Replacement".into(), + "oblique" => t.oblique += 0.2, + _ => t.width_factor *= 1.2, + }); + for name in two_point_formats() { + check_two_point_save(&d, name, true, true); + } + } +} + +#[test] +fn two_point_changed_string_recomputes_measurements() { + let mut d = imported_two_point_text_sample(); + edit_two_point_texts(&mut d, |t| t.value.push_str(" EDITED")); + for name in two_point_formats() { + check_two_point_save(&d, name, true, false); + } +} + +#[test] +fn two_point_changed_distance_scales_aligned_and_recomputes_fit() { + let mut d = imported_two_point_text_sample(); + let imported = d.clone(); + edit_two_point_texts(&mut d, |t| t.align_pt.as_mut().unwrap().x *= 1.8); + for name in two_point_formats() { + let saved = read(&write(&d, name).unwrap(), name).unwrap(); + for ((before, edited), after) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).zip(two_point_texts(&saved)) { + if before.halign == HAlign::Aligned { + let ratio = edited.insert.xy().dist(edited.align_pt.unwrap().xy()) / before.insert.xy().dist(before.align_pt.unwrap().xy()); + assert!((after.height / (before.height * ratio) - 1.0).abs() < 1e-12, "{name}"); + } else { + let expected = cadcraft_render::fitted_text_entity(&d, edited, &edited.value); + assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12, "{name}"); + } + } + check_two_point_save(&saved, name, false, true); + } +} + +#[test] +fn two_point_authored_text_recomputes_measurements() { + for name in two_point_formats() { + check_two_point_save(&two_point_text_sample(), name, true, false); + } +} + +#[test] +fn two_point_text_save_keeps_degenerate_and_unrelated_values() { + for halign in [HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Middle, HAlign::Aligned, HAlign::Fit] { + for valign in [VAlign::Baseline, VAlign::Bottom] { + for align_pt in [None, Some(Vec3::ZERO), Some(Vec3::new(30.0, 4.0, 0.0))] { + if matches!(halign, HAlign::Aligned | HAlign::Fit) && align_pt.is_some_and(|point| point != Vec3::ZERO) { + continue; + } + let text = Text { insert: Vec3::ZERO, align_pt, halign, valign, rotation: 0.7, width_factor: 0.8, ..intl_text("SYNTHETIC") }; + let mut drawing = Drawing::new_metric(); + drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap(); + let saved = read(&write(&drawing, "edge.dxf").unwrap(), "edge.dxf").unwrap(); + let back = first(&saved, |kind| if let EntityKind::Text(text) = kind { Some(text.clone()) } else { None }); + assert!((text.rotation - back.rotation).abs() < 1e-12); + assert!((text.height - back.height).abs() < 1e-10); + assert!((text.width_factor - back.width_factor).abs() < 1e-10); + } + } + } +} + +#[test] +fn two_point_imported_degenerate_geometry_keeps_edited_height() { + for missing in [false, true] { + let mut d = imported_two_point_text_sample(); + let handle = d.model.handles()[0]; + d.model.modify(handle, |entity| { + if let EntityKind::Text(t) = &mut entity.kind { + t.insert = Vec3::ZERO; + t.align_pt = if missing { None } else { Some(Vec3::ZERO) }; + t.height = 2.0; + } + }); + let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0; + snapshot.insert = Vec3::ZERO; + snapshot.align_pt = if missing { None } else { Some(Vec3::ZERO) }; + snapshot.height = 2.0; + let mut d = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap(); + let handle = d.model.handles()[0]; + let imported = first(&d, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None }); + assert_eq!(imported.align_pt, if missing { None } else { Some(Vec3::ZERO) }); + d.model.modify(handle, |entity| { + if let EntityKind::Text(t) = &mut entity.kind { + t.height = 4.0; + } + }); + let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap(); + let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None }); + assert!((text.height - 4.0).abs() < 1e-10, "missing: {missing}"); + } +} + +#[test] +fn two_point_imported_nonfinite_geometry_keeps_edited_height() { + let mut d = imported_two_point_text_sample(); + let handle = d.model.handles()[0]; + d.model.modify(handle, |entity| { + if let EntityKind::Text(t) = &mut entity.kind { + assert_eq!(t.halign, HAlign::Aligned); + t.insert = Vec3::ZERO; + t.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0)); + t.height = 4.0; + } + }); + let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0; + snapshot.insert = Vec3::ZERO; + snapshot.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0)); + snapshot.height = 2.0; + let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap(); + let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None }); + assert!((text.height - 4.0).abs() < 1e-10); +} + +#[test] +fn two_point_imported_empty_attdef_keeps_dimensions_when_points_move() { + let mut d = imported_two_point_text_sample(); + let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap()); + let handle = block.entities.handles()[0]; + block.entities.modify(handle, |entity| { + if let EntityKind::AttDef(a) = &mut entity.kind { + a.text.value.clear(); + a.text.insert = Vec3::ZERO; + a.text.align_pt = Some(Vec3::new(10.0, 0.0, 0.0)); + a.text.height = 2.0; + a.text.width_factor = 0.8; + } + }); + let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0; + snapshot.value.clear(); + snapshot.insert = Vec3::ZERO; + snapshot.align_pt = Some(Vec3::new(10.0, 0.0, 0.0)); + snapshot.height = 2.0; + snapshot.width_factor = 0.8; + let mut d = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap(); + let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap()); + let handle = block.entities.handles()[0]; + block.entities.modify(handle, |entity| { + if let EntityKind::AttDef(a) = &mut entity.kind { + a.text.align_pt = Some(Vec3::new(0.0, 20.0, 0.0)); + } + }); + let saved = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap(); + let entity = saved.block("Labels").unwrap().entities.iter().next().unwrap(); + let EntityKind::AttDef(a) = &entity.kind else { panic!("expected ATTDEF") }; + assert!((a.text.height - 2.0).abs() < 1e-10); + assert!((a.text.width_factor - 0.8).abs() < 1e-10); + assert!((a.text.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-10); +} + +#[test] +fn two_point_changed_style_definition_recomputes_measurements() { + let mut d = imported_two_point_text_sample(); + d.text_styles.iter_mut().find(|style| style.name.eq_ignore_ascii_case("Standard")).unwrap().backwards = true; + for name in two_point_formats() { + let saved = read(&write(&d, name).unwrap(), name).unwrap(); + for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) { + let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value); + assert!((after.height - expected.height).abs() < 1e-9, "{name}"); + assert!((after.width_factor - expected.width_factor).abs() < 1e-9, "{name}"); + } + } +} + +#[test] +fn two_point_changed_justification_recomputes_measurements() { + for horizontal in [true, false] { + let mut d = imported_two_point_text_sample(); + edit_two_point_texts(&mut d, |t| { + if horizontal { + t.halign = if t.halign == HAlign::Fit { HAlign::Aligned } else { HAlign::Fit }; + } else { + t.valign = VAlign::Middle; + } + }); + for name in two_point_formats() { + check_two_point_save(&d, name, true, true); + } + } +} + +#[test] +fn two_point_dwg_source_preserves_imported_measurements() { + let imported = imported_two_point_text_sample(); + crate::dwg_worker::allow_in_process(); + let dwg = write(&imported, "source.dwg").unwrap(); + let reopened = read(&dwg, "source.dwg").unwrap(); + assert!(!reopened.foreign.text_fits.is_empty()); + for name in two_point_formats() { + check_two_point_save(&reopened, name, false, true); + } +} + +#[test] +fn two_point_block_layout_and_empty_default() { + let mut d = Drawing::new_metric(); + let mut block = Block::new("Labels"); + for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() { + let text = Text { halign, valign: VAlign::Middle, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("SYNTHETIC") }; + block.entities.push(Entity::new(Handle(0x500 + index as u64), EntityKind::Text(text.clone()))); + d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Text(text)).unwrap(); + let empty = Text { halign, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("") }; + block.entities.push(Entity::new( + Handle(0x510 + index as u64), + EntityKind::AttDef(Attrib { + tag: "LABEL".into(), + text: empty, + invisible: false, + constant: false, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }), + )); + } + d.blocks.insert(block.name.clone(), std::sync::Arc::new(block)); + for name in two_point_formats() { + let saved = read(&write(&d, name).unwrap(), name).unwrap(); + for (before, after) in d.block("Labels").unwrap().entities.iter().zip(saved.block("Labels").unwrap().entities.iter()) { + match (&before.kind, &after.kind) { + (EntityKind::Text(a), EntityKind::Text(b)) => { + let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value); + assert!((b.height - expected.height).abs() < 1e-9); + assert!((b.width_factor - expected.width_factor).abs() < 1e-9); + } + (EntityKind::AttDef(a), EntityKind::AttDef(b)) => { + assert!((a.text.height - b.text.height).abs() < 1e-9); + assert!((a.text.width_factor - b.text.width_factor).abs() < 1e-9); + assert!((b.text.rotation - b.text.insert.xy().angle_to(b.text.align_pt.unwrap().xy())).abs() < 1e-9); + } + _ => panic!("unexpected block entity"), + } + } + let before = &d.layout("Layout1").unwrap().entities; + let after = &saved.layout("Layout1").unwrap().entities; + for (a, b) in before.iter().zip(after.iter()) { + if let (EntityKind::Text(a), EntityKind::Text(b)) = (&a.kind, &b.kind) { + let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value); + assert!((b.height - expected.height).abs() < 1e-9); + assert!((b.width_factor - expected.width_factor).abs() < 1e-9); + } + } + assert_eq!(before.len(), after.len()); + } +} + +#[test] +fn two_point_nonuniform_insert_keeps_attribute_fit_in_its_stored_coordinates() { + let mut d = two_point_text_sample(); + for h in d.model.handles() { + d.model.modify(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.scale = Vec3::new(2.0, 0.5, 1.0); + } + }); + } + for name in two_point_formats() { + let saved = read(&write(&d, name).unwrap(), name).unwrap(); + let insert = saved.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i) } else { None }).unwrap(); + let fit = insert.attribs.iter().find(|a| a.text.halign == HAlign::Fit).unwrap(); + let width = cadcraft_fonts::shape_stroke_dir(&fit.text.value, fit.text.height, fit.text.width_factor, fit.text.oblique, Some(false)).width; + assert!((width - fit.text.insert.xy().dist(fit.text.align_pt.unwrap().xy())).abs() < 1e-9); + assert!((insert.scale.x - 2.0).abs() < 1e-9 && (insert.scale.y - 0.5).abs() < 1e-9); + } +} + fn intl_sample() -> Drawing { let mut d = Drawing::new_metric(); let layer = format!("层 {INTL}"); @@ -2443,7 +2952,7 @@ fn gradient_sample() -> (Drawing, Vec>) { let h = Hatch { pattern: "SOLID".into(), solid: true, - loops: vec![HatchLoop { vertices: square.clone(), outer: true, sources: Vec::new() }], + loops: vec![HatchLoop { vertices: square.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }], scale: 1.0, angle: 0.0, associative: false, diff --git a/crates/io/tests/data/dynblock_arrays.txt b/crates/io/tests/data/dynblock_arrays.txt new file mode 100644 index 000000000..26de27b00 --- /dev/null +++ b/crates/io/tests/data/dynblock_arrays.txt @@ -0,0 +1,508 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 200 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 5 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Row +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1C +102 {ACAD_XDICTIONARY +360 70 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Fan +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1B +102 {ACAD_XDICTIONARY +360 80 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Grid +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Row +70 2 +10 0 +20 0 +30 0 +3 Row +1 +0 LWPOLYLINE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 0 +1005 30 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 26 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Fan +70 2 +10 0 +20 0 +30 0 +3 Fan +1 +0 CIRCLE +5 40 +330 1C +100 AcDbEntity +8 0 +100 AcDbCircle +10 0 +20 0 +30 0 +40 1 +1001 AcDbBlockRepETag +1070 1 +1071 0 +1005 40 +0 ENDBLK +5 27 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 28 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Grid +70 2 +10 0 +20 0 +30 0 +3 Grid +1 +0 CIRCLE +5 50 +330 1B +100 AcDbEntity +8 0 +100 AcDbCircle +10 0 +20 0 +30 0 +40 1 +1001 AcDbBlockRepETag +1070 1 +1071 0 +1005 50 +0 ENDBLK +5 29 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +330 60 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 62 +91 1 +93 32 +95 4 +360 63 +0 BLOCKLINEARPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKARRAYACTION +5 63 +330 61 +100 AcDbEvalExpr +90 4 +98 33 +99 232 +100 AcDbBlockElement +300 Array +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 30 +1010 4 +1020 3 +1030 0 +100 AcDbBlockArrayAction +92 1 +93 1 +94 1 +95 1 +301 Base +302 End +303 UpdatedBase +304 UpdatedEnd +140 1 +141 3 +0 DICTIONARY +5 70 +330 1C +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 71 +0 ACAD_EVALUATION_GRAPH +5 71 +330 70 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 72 +91 1 +93 32 +95 4 +360 73 +0 BLOCKPOLARPARAMETER +5 72 +330 71 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Polar +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 3 +1021 4 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockPolarParameter +305 Distance1 +306 +307 Angle1 +308 +140 0 +309 +96 0 +141 0 +142 0 +143 0 +175 0 +410 +97 0 +145 0 +146 0 +147 0 +176 0 +0 BLOCKARRAYACTION +5 73 +330 71 +100 AcDbEvalExpr +90 4 +98 33 +99 232 +100 AcDbBlockElement +300 Array +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 40 +1010 4 +1020 5 +1030 0 +100 AcDbBlockArrayAction +92 1 +93 1 +94 1 +95 1 +301 Base +302 End +303 UpdatedBase +304 UpdatedEnd +140 1 +141 2 +0 DICTIONARY +5 80 +330 1B +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 81 +0 ACAD_EVALUATION_GRAPH +5 81 +330 80 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 82 +91 1 +93 32 +95 6 +360 83 +0 BLOCKXYPARAMETER +5 82 +330 81 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 XY +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 10 +1021 10 +1031 0 +170 4 +91 3 +91 2 +91 4 +91 5 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockXYParameter +305 Y Distance1 +306 X Distance1 +307 +308 +141 0 +140 0 +309 +97 1 +146 0 +147 0 +148 0 +176 0 +410 +96 1 +142 0 +143 0 +144 0 +175 0 +0 BLOCKARRAYACTION +5 83 +330 81 +100 AcDbEvalExpr +90 6 +98 33 +99 232 +100 AcDbBlockElement +300 Array +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 50 +1010 12 +1020 12 +1030 0 +100 AcDbBlockArrayAction +92 1 +93 1 +94 1 +95 1 +301 Base +302 End +303 UpdatedBase +304 UpdatedEnd +140 4 +141 5 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/data/dynblock_params.txt b/crates/io/tests/data/dynblock_params.txt new file mode 100644 index 000000000..7b39a199c --- /dev/null +++ b/crates/io/tests/data/dynblock_params.txt @@ -0,0 +1,1060 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 400 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 6 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Shift +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1C +102 {ACAD_XDICTIONARY +360 70 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Align +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1B +102 {ACAD_XDICTIONARY +360 80 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Turn +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1A +102 {ACAD_XDICTIONARY +360 90 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Many +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 22 +330 1E +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Paper_Space +70 0 +10 0 +20 0 +30 0 +3 *Paper_Space +1 +0 ENDBLK +5 23 +330 1E +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Shift +70 2 +10 0 +20 0 +30 0 +3 Shift +1 +0 LWPOLYLINE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 -10 +20 -2.5 +10 0 +20 -2.5 +10 0 +20 2.5 +10 -10 +20 2.5 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 30 +0 ATTDEF +5 31 +330 1D +100 AcDbEntity +8 0 +100 AcDbText +10 -8 +20 0 +30 0 +40 1 +1 X +7 Standard +100 AcDbAttributeDefinition +3 Tag +2 TAG +70 0 +1001 AcDbBlockRepETag +1070 1 +1071 2 +1005 31 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 26 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Align +70 2 +10 0 +20 0 +30 0 +3 Align +1 +0 LWPOLYLINE +5 40 +330 1C +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 4 +20 0 +10 4 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 40 +0 ENDBLK +5 27 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 28 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Turn +70 2 +10 0 +20 0 +30 0 +3 Turn +1 +0 LWPOLYLINE +5 50 +330 1B +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 4 +20 0 +10 4 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 50 +0 ENDBLK +5 29 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 2A +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Many +70 2 +10 0 +20 0 +30 0 +3 Many +1 +0 LWPOLYLINE +5 A0 +330 1A +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 4 +20 0 +10 4 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 A0 +0 ENDBLK +5 2B +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 E0 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockReference +66 1 +2 Shift +10 100 +20 100 +30 0 +0 ATTRIB +5 E1 +330 E0 +100 AcDbEntity +8 0 +100 AcDbText +10 92 +20 100 +30 0 +40 1 +1 X +7 Standard +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND +5 E2 +330 E0 +100 AcDbEntity +8 0 +0 LINE +5 E3 +330 1F +100 AcDbEntity +8 0 +100 AcDbLine +10 120 +20 100 +30 0 +11 140 +21 111.54700538379251 +31 0 +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +330 60 +100 AcDbEvalGraph +96 3 +97 3 +91 0 +93 32 +95 1 +360 62 +91 1 +93 32 +95 2 +360 63 +91 2 +93 32 +95 3 +360 64 +0 BLOCKBASEPOINTPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Base Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 10 +1020 2.5 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockBasepointParameter +1011 0 +1021 0 +1031 0 +1012 0 +1022 0 +1032 0 +0 BLOCKLINEARPARAMETER +5 63 +330 61 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 -10 +1020 -2.5 +1030 0 +1011 0 +1021 -2.5 +1031 0 +170 4 +91 0 +91 4 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKSTRETCHACTION +5 64 +330 61 +100 AcDbEvalExpr +90 3 +98 33 +99 232 +100 AcDbBlockElement +300 Stretch +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 2 +330 30 +330 62 +1010 2 +1020 3 +1030 0 +100 AcDbBlockStretchAction +92 2 +301 EndXDelta +93 2 +302 EndYDelta +72 2 +1011 -2 +1021 -3.5 +1011 2 +1021 3.5 +73 1 +331 30 +74 2 +94 1 +94 2 +75 0 +140 1 +141 0 +0 DICTIONARY +5 70 +330 1C +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 71 +0 ACAD_EVALUATION_GRAPH +5 71 +330 70 +100 AcDbEvalGraph +96 1 +97 1 +91 0 +93 32 +95 1 +360 72 +0 BLOCKALIGNMENTPARAMETER +5 72 +330 71 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Alignment +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 4 +1021 0 +1031 0 +170 4 +91 2 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockAlignmentParameter +280 1 +0 DICTIONARY +5 80 +330 1B +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 81 +0 ACAD_EVALUATION_GRAPH +5 81 +330 80 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 82 +91 1 +93 32 +95 5 +360 83 +91 2 +93 32 +95 6 +360 84 +91 3 +93 32 +95 10 +360 85 +0 BLOCKROTATIONPARAMETER +5 82 +330 81 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Rotation +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 3 +1021 0 +1031 0 +170 4 +91 0 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockRotationParameter +305 Angle1 +306 +1011 3 +1021 0 +1031 0 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKROTATEACTION +5 83 +330 81 +100 AcDbEvalExpr +90 5 +98 33 +99 232 +100 AcDbBlockElement +300 Rotate +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 50 +1010 5 +1020 0 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockRotationAction +94 1 +303 AngleDelta +0 BLOCKLOOKUPPARAMETER +5 84 +330 81 +100 AcDbEvalExpr +90 6 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 6 +1020 4 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockLookUpParameter +303 Lookup1 +304 +94 0 +0 BLOCKLOOKUPACTION +5 85 +330 81 +100 AcDbEvalExpr +90 10 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup1 +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 0 +1010 6 +1020 5 +1030 0 +100 AcDbBlockLookupAction +92 3 +93 2 +301 +302 1.570796326794896 +302 Up +302 3.141592653589793 +302 Left +302 0 +302 Zero +303 +94 1 +95 40 +96 1 +282 0 +305 Custom +281 0 +304 UpdatedAngle +303 +94 6 +95 1 +96 0 +282 1 +305 Custom +281 1 +304 lookupString +280 1 +0 DICTIONARY +5 90 +330 1A +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 91 +0 ACAD_EVALUATION_GRAPH +5 91 +330 90 +100 AcDbEvalGraph +96 6 +97 6 +91 0 +93 32 +95 1 +360 92 +91 1 +93 32 +95 6 +360 93 +91 2 +93 32 +95 10 +360 94 +91 3 +93 32 +95 14 +360 95 +91 4 +93 32 +95 18 +360 96 +91 5 +93 32 +95 22 +360 97 +0 BLOCKFLIPPARAMETER +5 92 +330 91 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Flip +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 -1 +1030 0 +1011 4 +1021 -1 +1031 0 +170 4 +91 2 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockFlipParameter +305 Flip state1 +306 +307 Not flipped +308 Flipped +1012 2 +1022 -2 +1032 0 +309 UpdatedFlip +96 2 +0 BLOCKXYPARAMETER +5 93 +330 91 +100 AcDbEvalExpr +90 6 +98 33 +99 232 +100 AcDbBlockElement +300 XY +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 4 +1021 2 +1031 0 +170 4 +91 0 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockXYParameter +305 Y Distance1 +306 X Distance1 +307 +308 +141 0 +140 0 +309 +97 0 +146 0 +147 0 +148 0 +176 0 +410 +96 0 +142 0 +143 0 +144 0 +175 0 +0 BLOCKPOLARPARAMETER +5 94 +330 91 +100 AcDbEvalExpr +90 10 +98 33 +99 232 +100 AcDbBlockElement +300 Polar +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 3 +1021 3 +1031 0 +170 4 +91 0 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockPolarParameter +305 Distance1 +306 +307 Angle1 +308 +140 0 +309 +96 0 +141 0 +142 0 +143 0 +175 0 +410 +97 0 +145 0 +146 0 +147 0 +176 0 +0 BLOCKPOINTPARAMETER +5 95 +330 91 +100 AcDbEvalExpr +90 14 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 2 +1020 1 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 2 +1021 3 +1031 0 +0 BLOCKLOOKUPPARAMETER +5 96 +330 91 +100 AcDbEvalExpr +90 18 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 6 +1020 4 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockLookUpParameter +303 Lookup1 +304 +94 0 +0 BLOCKLOOKUPACTION +5 97 +330 91 +100 AcDbEvalExpr +90 22 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup1 +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 0 +1010 6 +1020 5 +1030 0 +100 AcDbBlockLookupAction +92 2 +93 8 +301 +302 1 +302 6 +302 3 +302 5 +302 0.5235987755982987 +302 1 +302 0.5 +302 A +302 0 +302 4 +302 2 +302 4.242640689999999 +302 0.7853981633974482 +302 2 +302 1 +302 B +303 +94 1 +95 70 +96 0 +282 0 +305 Custom +281 0 +304 UpdatedFlip +303 +94 6 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedDistanceX +303 +94 6 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedDistanceY +303 +94 10 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedDistance +303 +94 10 +95 40 +96 1 +282 0 +305 Custom +281 0 +304 UpdatedAngle +303 +94 14 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedX +303 +94 14 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedY +303 +94 18 +95 1 +96 0 +282 1 +305 Custom +281 1 +304 lookupString +280 1 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/data/dynblock_scale_polar.txt b/crates/io/tests/data/dynblock_scale_polar.txt new file mode 100644 index 000000000..dfaad96ff --- /dev/null +++ b/crates/io/tests/data/dynblock_scale_polar.txt @@ -0,0 +1,813 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 200 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 6 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Grow +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1C +102 {ACAD_XDICTIONARY +360 70 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Pinned +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1B +102 {ACAD_XDICTIONARY +360 80 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Sheet +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1A +102 {ACAD_XDICTIONARY +360 90 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Tag +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Grow +70 2 +10 0 +20 0 +30 0 +3 Grow +1 +0 LWPOLYLINE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 30 +0 CIRCLE +5 31 +330 1D +100 AcDbEntity +8 0 +100 AcDbCircle +10 1 +20 1 +30 0 +40 0.5 +1001 AcDbBlockRepETag +1070 1 +1071 2 +1005 31 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 26 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Pinned +70 2 +10 0 +20 0 +30 0 +3 Pinned +1 +0 LWPOLYLINE +5 40 +330 1C +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 40 +0 ENDBLK +5 27 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 28 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Sheet +70 2 +10 0 +20 0 +30 0 +3 Sheet +1 +0 LWPOLYLINE +5 50 +330 1B +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 50 +0 ENDBLK +5 29 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 2A +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Tag +70 2 +10 0 +20 0 +30 0 +3 Tag +1 +0 LINE +5 B0 +330 1A +100 AcDbEntity +8 0 +100 AcDbLine +10 1 +20 0 +30 0 +11 4 +21 0 +31 0 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 B0 +0 CIRCLE +5 B1 +330 1A +100 AcDbEntity +8 0 +100 AcDbCircle +10 4 +20 0 +30 0 +40 0.25 +1001 AcDbBlockRepETag +1070 1 +1071 2 +1005 B1 +0 CIRCLE +5 B2 +330 1A +100 AcDbEntity +8 0 +100 AcDbCircle +10 2 +20 2 +30 0 +40 0.5 +1001 AcDbBlockRepETag +1070 1 +1071 3 +1005 B2 +0 ENDBLK +5 2B +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +330 60 +100 AcDbEvalGraph +96 3 +97 3 +91 0 +93 32 +95 1 +360 62 +91 1 +93 32 +95 2 +360 63 +91 2 +93 32 +95 3 +360 64 +0 BLOCKLINEARPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 1 +141 0 +142 0 +143 0 +175 0 +0 BLOCKPOINTPARAMETER +5 63 +330 61 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 2 +1020 2 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 2 +1021 2 +1031 0 +0 BLOCKSCALEACTION +5 64 +330 61 +100 AcDbEvalExpr +90 3 +98 33 +99 232 +100 AcDbBlockElement +300 Scale +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 3 +330 30 +330 31 +330 63 +1010 4 +1020 3 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockScaleAction +94 1 +95 1 +96 1 +303 Scale +304 XScale +305 YScale +0 DICTIONARY +5 70 +330 1C +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 71 +0 ACAD_EVALUATION_GRAPH +5 71 +330 70 +100 AcDbEvalGraph +96 2 +97 2 +91 0 +93 32 +95 1 +360 72 +91 1 +93 32 +95 2 +360 73 +0 BLOCKLINEARPARAMETER +5 72 +330 71 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKSCALEACTION +5 73 +330 71 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Scale +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 40 +1010 4 +1020 3 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 0 +1012 2 +1022 2 +1032 0 +100 AcDbBlockScaleAction +94 1 +95 1 +96 1 +303 Scale +304 XScale +305 YScale +0 DICTIONARY +5 80 +330 1B +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 81 +0 ACAD_EVALUATION_GRAPH +5 81 +330 80 +100 AcDbEvalGraph +96 2 +97 2 +91 0 +93 32 +95 1 +360 82 +91 1 +93 32 +95 2 +360 83 +0 BLOCKXYPARAMETER +5 82 +330 81 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 XY +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 2 +1031 0 +170 4 +91 3 +91 2 +91 4 +91 5 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockXYParameter +305 Y Distance1 +306 X Distance1 +307 +308 +141 0 +140 0 +309 +97 0 +146 0 +147 0 +148 0 +176 0 +410 +96 0 +142 0 +143 0 +144 0 +175 0 +0 BLOCKSCALEACTION +5 83 +330 81 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Scale +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 50 +1010 4 +1020 3 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockScaleAction +94 1 +95 1 +96 1 +303 Scale +304 XScale +305 YScale +0 DICTIONARY +5 90 +330 1A +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 91 +0 ACAD_EVALUATION_GRAPH +5 91 +330 90 +100 AcDbEvalGraph +96 3 +97 3 +91 0 +93 32 +95 1 +360 92 +91 1 +93 32 +95 2 +360 93 +91 2 +93 32 +95 3 +360 94 +0 BLOCKPOLARPARAMETER +5 92 +330 91 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Polar +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 4 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockPolarParameter +305 Distance1 +306 +307 Angle1 +308 +140 0 +309 +96 0 +141 0 +142 0 +143 0 +175 0 +410 +97 0 +145 0 +146 0 +147 0 +176 0 +0 BLOCKPOINTPARAMETER +5 93 +330 91 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 4 +1020 1 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 4 +1021 1 +1031 0 +0 BLOCKPOLARSTRETCHACTION +5 94 +330 91 +100 AcDbEvalExpr +90 3 +98 33 +99 232 +100 AcDbBlockElement +300 Polar Stretch +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 3 +330 B0 +330 B1 +330 93 +1010 5 +1020 -1 +1030 0 +100 AcDbBlockPolarStretchAction +92 1 +301 EndXDelta +93 1 +302 EndYDelta +94 1 +303 Base +95 1 +304 End +96 1 +305 UpdatedBase +97 1 +306 UpdatedEnd +73 2 +1011 3.5 +1021 -0.5 +1011 4.5 +1021 1.5 +72 1 +331 B2 +74 1 +332 B0 +75 1 +76 1 +78 0 +141 1 +140 0 +77 0 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/data/dynblock_symbol.txt b/crates/io/tests/data/dynblock_symbol.txt new file mode 100644 index 000000000..09dbdc486 --- /dev/null +++ b/crates/io/tests/data/dynblock_symbol.txt @@ -0,0 +1,469 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 200 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 3 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Symbol +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Symbol +70 2 +10 0 +20 0 +30 0 +3 Symbol +1 +0 CIRCLE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbCircle +10 0 +20 0 +30 0 +40 1 +0 LINE +5 31 +330 1D +100 AcDbEntity +8 0 +100 AcDbLine +10 0 +20 0 +30 0 +11 0 +21 3 +31 0 +0 ATTDEF +5 32 +330 1D +100 AcDbEntity +8 0 +100 AcDbText +10 1 +20 2 +30 0 +40 1 +1 X +50 90 +7 Standard +100 AcDbAttributeDefinition +3 Tag +2 TAG +70 0 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +102 {ACAD_REACTORS +330 60 +102 } +330 60 +100 AcDbEvalGraph +96 8 +97 8 +91 0 +93 32 +95 15 +360 62 +92 -1 +92 -1 +92 -1 +92 -1 +91 1 +93 32 +95 16 +360 63 +92 -1 +92 -1 +92 -1 +92 -1 +91 2 +93 32 +95 19 +360 64 +92 -1 +92 -1 +92 -1 +92 -1 +91 3 +93 32 +95 20 +360 65 +92 -1 +92 -1 +92 -1 +92 -1 +91 4 +93 32 +95 21 +360 66 +92 -1 +92 -1 +92 -1 +92 -1 +91 5 +93 32 +95 25 +360 67 +92 -1 +92 -1 +92 -1 +92 -1 +91 6 +93 32 +95 26 +360 68 +92 -1 +92 -1 +92 -1 +92 -1 +91 7 +93 32 +95 30 +360 69 +0 BLOCKROTATIONPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 15 +98 33 +99 232 +100 AcDbBlockElement +300 Rotation +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 0 +91 16 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockRotationParameter +305 Angle1 +306 +1011 2 +1021 0 +1031 0 +140 0 +307 +96 3 +141 0 +142 6.283185307179586 +143 0 +175 0 +0 BLOCKROTATIONGRIP +5 63 +330 61 +100 AcDbEvalExpr +90 16 +98 33 +99 232 +100 AcDbBlockElement +300 Grip +98 33 +99 232 +1071 0 +100 AcDbBlockGrip +91 0 +92 0 +1010 2 +1020 0 +1030 0 +280 0 +93 -1 +100 AcDbBlockRotationGrip +0 BLOCKROTATEACTION +5 64 +330 61 +100 AcDbEvalExpr +90 19 +98 33 +99 232 +100 AcDbBlockElement +300 Rotate +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 2 +91 0 +91 0 +71 4 +330 31 +330 32 +330 65 +330 68 +1010 1 +1020 1 +1030 0 +100 AcDbBlockActionWithBasePt +92 15 +93 15 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockRotationAction +94 15 +303 AngleDelta +0 BLOCKFLIPPARAMETER +5 65 +330 61 +100 AcDbEvalExpr +90 20 +98 33 +99 232 +100 AcDbBlockElement +300 Flip +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 -10 +1021 0 +1031 0 +170 4 +91 21 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockFlipParameter +305 Flip state1 +306 +307 Not flipped +308 Flipped +1012 -12 +1022 0 +1032 0 +309 UpdatedFlip +96 21 +0 BLOCKFLIPGRIP +5 66 +330 61 +100 AcDbEvalExpr +90 21 +98 33 +99 232 +100 AcDbBlockElement +300 Grip +98 33 +99 232 +1071 0 +100 AcDbBlockGrip +91 0 +92 0 +1010 -2 +1020 0 +1030 0 +280 0 +93 -1 +100 AcDbBlockFlipGrip +0 BLOCKFLIPACTION +5 67 +330 61 +100 AcDbEvalExpr +90 25 +98 33 +99 232 +100 AcDbBlockElement +300 Flip1 +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 2 +91 0 +91 0 +71 3 +330 31 +330 32 +330 68 +1010 -6 +1020 0 +1030 0 +100 AcDbBlockFlipAction +92 20 +93 20 +94 20 +95 20 +301 Flip +302 UpdatedFlip +303 UpdatedBase +304 UpdatedEnd +0 BLOCKPOINTPARAMETER +5 68 +330 61 +100 AcDbEvalExpr +90 26 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 0 +1020 3 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 0 +1021 4 +1031 0 +0 BLOCKMOVEACTION +5 69 +330 61 +100 AcDbEvalExpr +90 30 +98 33 +99 232 +100 AcDbBlockElement +300 Move +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 2 +91 0 +91 0 +71 1 +330 32 +1010 0 +1020 4 +1030 0 +100 AcDbBlockMoveAction +92 26 +93 26 +301 XDelta +302 YDelta +140 1 +141 0 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/dimassoc_header.rs b/crates/io/tests/dimassoc_header.rs new file mode 100644 index 000000000..58967174e --- /dev/null +++ b/crates/io/tests/dimassoc_header.rs @@ -0,0 +1,48 @@ +//! DIMASSOC is a drawing variable, written as HEADER group 280, independently of DIMSTYLE. +use cadcraft_doc::Drawing; +use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with}; + +/// Extract every DIMASSOC HEADER entry so duplicate or mistyped values fail the assertions. +fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> { + let tags = craft_dxf::parse(bytes).unwrap(); + let header = craft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap(); + let mut found = Vec::new(); + for pair in header.tags.windows(2) { + if pair[0].code == 9 && pair[0].str() == "$DIMASSOC" { + found.push((pair[1].code, pair[1].i64())); + } + } + found +} + +/// All supported modes use group 280 and survive each tested DXF version and encoding. +#[test] +fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() { + for mode in [0, 1, 2] { + let mut d = Drawing::new_metric(); + d.header.set_i64("DIMASSOC", mode); + for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] { + for binary in [false, true] { + let bytes = write_with(&d, "setting.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + assert_eq!(dimassoc_groups(&bytes), [(280, mode)], "{version:?}, binary{binary}"); + let back = read_dxf(&bytes).unwrap(); + assert_eq!(back.header.i64("DIMASSOC", -1), mode); + } + } + } +} + +/// Editing an imported mode replaces its stored value without emitting a second HEADER entry. +#[test] +fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() { + let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n"; + let mut d = read_dxf(source).unwrap(); + assert_eq!(d.header.i64("DIMASSOC", -1), 1); + for mode in [1, 0, 2] { + d.header.set_i64("DIMASSOC", mode); + let bytes = write(&d, "edited.dxf").unwrap(); + assert_eq!(dimassoc_groups(&bytes), [(280, mode)]); + d = read_dxf(&bytes).unwrap(); + assert_eq!(d.header.i64("DIMASSOC", -1), mode); + } +} diff --git a/crates/io/tests/handle_exhaustion.rs b/crates/io/tests/handle_exhaustion.rs index 88a295d39..705b44c0c 100644 --- a/crates/io/tests/handle_exhaustion.rs +++ b/crates/io/tests/handle_exhaustion.rs @@ -370,7 +370,7 @@ fn top_line_kept_objects_and_unknown(handle: Handle) -> Drawing { RawTag { code: 100, value: "SyntheticWidget".into() }, RawTag { code: 1, value: "widget".into() }, ]; - let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags }); + let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() }); d.model.push(Entity { handle, common: Common::default(), kind }); d } diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index f85b05f67..5cf96b04d 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -166,7 +166,7 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() { use cadcraft_doc::foreign::{Foreign, sat_text_acis}; use cadcraft_doc::{Handle, RawTag, Unknown}; let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; - let solid = |tags: Vec| Unknown { dxf_type: "3DSOLID".into(), tags }; + let solid = |tags: Vec| Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() }; let none = std::collections::BTreeSet::new(); let h = Handle(0x2B); // A stray 1 or 3 outside AcDbModelerGeometry is not SAT text. diff --git a/crates/io/tests/it/assoc_dependency_prune.rs b/crates/io/tests/it/assoc_dependency_prune.rs new file mode 100644 index 000000000..da8a05549 --- /dev/null +++ b/crates/io/tests/it/assoc_dependency_prune.rs @@ -0,0 +1,225 @@ +//! A kept `ACDBASSOCDEPENDENCY` whose `dependentOnObject` (group 330 in `AcDbAssocDependency`) +//! names a handle that is no longer written must not be emitted with `330 = 0` as an active +//! dependency: it is dropped together with the objects whose owner it is, and its owning +//! `ACDBASSOCACTION` drops its list entry (group 330 or 360) and decrements its dependency count. + +/// The parts of the fixture that the tests change. +struct Parts<'a> { + dep1_target: &'a str, + dep2_target: &'a str, + /// Groups added to the action's `AcDbAssocAction` header after its status. + action_extra: &'a str, + /// The action's dependency list after its count (group 330 or 360 per entry). + action_list: &'a str, + /// The body handle (group 360) of dependency 504. + dep1_body: &'a str, + /// The owner (group 330) of XRECORD 506, which dependency 505 hard-owns. + body_owner: &'a str, + /// Objects added at the end of the OBJECTS section. + extra_objects: &'a str, +} + +const PARTS: Parts<'static> = Parts { + dep1_target: "100", + dep2_target: "999", + action_extra: "", + action_list: "360\n504\n360\n505\n", + dep1_body: "0", + body_owner: "505", + extra_objects: "", +}; + +fn dxf_with_assoc_action(dep1_target: &str, dep2_target: &str) -> String { + dxf(&Parts { dep1_target, dep2_target, ..PARTS }) +} + +fn dxf(p: &Parts) -> String { + let Parts { dep1_target, dep2_target, action_extra, action_list, dep1_body, body_owner, extra_objects } = p; + format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1024\n0\nENDSEC\n\ + 0\nSECTION\n2\nCLASSES\n\ + 0\nCLASS\n1\nACDBASSOCNETWORK\n2\nAcDbAssocNetwork\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n\ + 0\nCLASS\n1\nACDBASSOCACTION\n2\nAcDbAssocAction\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n\ + 0\nCLASS\n1\nACDBASSOCDEPENDENCY\n2\nAcDbAssocDependency\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\n100\n102\n{{ACAD_REACTORS\n330\n504\n102\n}}\n330\n1F\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n\ + 10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nACAD_ASSOCNETWORK\n350\n501\n\ + 0\nDICTIONARY\n5\n501\n102\n{{ACAD_REACTORS\n330\nC\n102\n}}\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nACAD_ASSOCNETWORK\n350\n502\n\ + 0\nACDBASSOCNETWORK\n5\n502\n102\n{{ACAD_REACTORS\n330\n501\n102\n}}\n330\n501\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n330\n0\n360\n0\n90\n0\n90\n0\n90\n0\n\ + 100\nAcDbAssocNetwork\n90\n0\n90\n1\n90\n1\n360\n503\n\ + 0\nACDBASSOCACTION\n5\n503\n330\n502\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n{action_extra}330\n502\n360\n0\n90\n1\n90\n2\n90\n2\n{action_list}\ + 0\nACDBASSOCDEPENDENCY\n5\n504\n330\n503\n\ + 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n0\n290\n1\n290\n1\n90\n0\n330\n{dep1_target}\n290\n0\n330\n0\n330\n0\n360\n{dep1_body}\n90\n1\n\ + 0\nACDBASSOCDEPENDENCY\n5\n505\n330\n503\n\ + 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n1\n290\n1\n290\n1\n90\n0\n330\n{dep2_target}\n290\n0\n330\n0\n330\n0\n360\n506\n90\n2\n\ + 0\nXRECORD\n5\n506\n330\n{body_owner}\n100\nAcDbXrecord\n280\n1\n1\nDEP_BODY_MARKER\n\ + {extra_objects}0\nENDSEC\n0\nEOF\n" + ) +} + +fn objects_of(dxf: &str, kind: &str) -> Vec> { + let lines: Vec<&str> = dxf.lines().collect(); + let mut out = Vec::new(); + let mut i = 0; + let mut in_objects = false; + while i + 1 < lines.len() { + let c = lines[i].trim(); + let v = lines[i + 1].trim(); + if c == "2" && v == "OBJECTS" { + in_objects = true; + i += 2; + continue; + } + if in_objects && c == "0" { + if v == "ENDSEC" { + break; + } + let obj_kind = v; + let mut pairs = Vec::new(); + i += 2; + while i + 1 < lines.len() && lines[i].trim() != "0" { + pairs.push((lines[i].trim().to_string(), lines[i + 1].trim().to_string())); + i += 2; + } + if obj_kind == kind { + out.push(pairs); + } + continue; + } + i += 2; + } + out +} + +#[test] +fn orphaned_assoc_dependency_is_pruned_along_with_action_entry_and_body() { + // dep1 points at live LINE 100; dep2 points at missing handle 999 and owns XRECORD 506. + let dxf = dxf_with_assoc_action("100", "999"); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 1, "only the live dependency should be written, got {deps:?}"); + let dep_handle = deps[0].iter().find(|(c, _)| c == "5").map(|(_, v)| v.as_str()).unwrap(); + let dep_target = + deps[0].iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocDependency")).find(|(c, _)| c == "330").map(|(_, v)| v.as_str()); + assert_eq!(dep_target, Some("100"), "live dependency keeps its target handle"); + + // The child XRECORD owned by the dropped dependency must be dropped too. + assert!(!saved.contains("DEP_BODY_MARKER"), "child owned by dropped dependency must not be written"); + + // The owning ACDBASSOCACTION must list only the surviving dependency with count = 1. + let actions = objects_of(&saved, "ACDBASSOCACTION"); + assert_eq!(actions.len(), 1); + let action_sub: Vec<&(String, String)> = actions[0].iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocAction")).collect(); + assert_eq!(action_sub[7], &("90".to_string(), "1".to_string()), "dependency count should be decremented to 1"); + assert_eq!(action_sub[8], &("360".to_string(), dep_handle.to_string()), "only the live dependency remains in 360 list"); + assert_eq!(action_sub.len(), 9, "no stale 360 entry remains"); +} + +#[test] +fn originally_unbound_assoc_dependency_with_null_target_is_kept() { + // dep2 already had dependentOnObject = 0 in the input file, so it is not an unmapped handle. + let dxf = dxf_with_assoc_action("100", "0"); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_null.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 2, "originally unbound dependency should remain kept"); + assert!(saved.contains("DEP_BODY_MARKER")); +} + +/// The groups of the written action from its `100 AcDbAssocAction` marker on. +fn action_subclass(saved: &str) -> Vec<(String, String)> { + let actions = objects_of(saved, "ACDBASSOCACTION"); + assert_eq!(actions.len(), 1, "one action is written"); + actions[0].iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocAction")).cloned().collect() +} + +/// The dependency count at `at` in an action subclass and the handle groups that follow it. +fn dependency_list(sub: &[(String, String)], at: usize) -> (usize, Vec<(String, String)>) { + assert_eq!(sub[at].0, "90", "the dependency count is a group 90"); + let count: usize = sub[at].1.parse().expect("count"); + let entries = sub[at + 1..].iter().take_while(|(c, _)| c == "330" || c == "360").cloned().collect(); + (count, entries) +} + +fn handle_of(object: &[(String, String)]) -> String { + object.iter().find(|(c, _)| c == "5").map(|(_, v)| v.clone()).expect("handle") +} + +#[test] +fn non_owned_dependency_entry_keeps_its_code_when_its_sibling_is_pruned() { + // acadrust writes a non-owned dependency as a group 330 entry. Dependency 505 is dangling. + let dxf = dxf(&Parts { action_list: "330\n504\n360\n505\n", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_mixed.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 1, "the dangling dependency is dropped, got {deps:?}"); + let (count, entries) = dependency_list(&action_subclass(&saved), 7); + assert!(count < 2, "the count drops below the two read entries"); + assert_eq!(count, entries.len(), "the count matches the written list: {entries:?}"); + assert_eq!(entries, vec![("330".to_string(), handle_of(&deps[0]))], "the surviving entry keeps group 330"); +} + +#[test] +fn null_owner_body_goes_with_its_pruned_hard_owner() { + // XRECORD 506 has owner 0. Only the dangling dependency 505 holds it (group 360). + let dxf = dxf(&Parts { body_owner: "0", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_null_owner.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + assert_eq!(objects_of(&saved, "ACDBASSOCDEPENDENCY").len(), 1, "the dangling dependency is dropped"); + assert!(!saved.contains("DEP_BODY_MARKER"), "a body held only by the dropped dependency is dropped"); +} + +#[test] +fn null_owner_body_stays_while_another_live_object_holds_it() { + // Live dependency 504 also holds XRECORD 506 by group 360. + let dxf = dxf(&Parts { body_owner: "0", dep1_body: "506", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_shared_body.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + assert_eq!(objects_of(&saved, "ACDBASSOCDEPENDENCY").len(), 1, "the dangling dependency is dropped"); + assert!(saved.contains("DEP_BODY_MARKER"), "a body with another live holder stays"); +} + +#[test] +fn dependency_of_an_action_with_an_unknown_header_is_not_pruned() { + // An extra group in the action header hides where its list starts, so the list stays as read. + let dxf = dxf(&Parts { action_extra: "290\n1\n", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_unknown_action.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 2, "both dependencies stay, got {deps:?}"); + let (count, entries) = dependency_list(&action_subclass(&saved), 8); + assert_eq!(count, entries.len(), "the count matches the written list: {entries:?}"); + let written: Vec = deps.iter().map(|d| handle_of(d)).collect(); + assert!(entries.iter().all(|(_, h)| written.contains(h)), "every entry names a written dependency: {entries:?}"); +} + +#[test] +fn dependency_listed_by_an_action_with_an_unknown_header_is_not_pruned() { + // Known action 503 owns dangling dependency 505. Action 507 has an unknown header and lists 505 by group 330. + let unknown = "0\nACDBASSOCACTION\n5\n507\n330\n502\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n290\n1\n330\n502\n360\n0\n90\n2\n90\n0\n90\n1\n330\n505\n"; + let dxf = dxf(&Parts { extra_objects: unknown, ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_unknown_lister.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 2, "both dependencies stay, got {deps:?}"); + let written: Vec = deps.iter().map(|d| handle_of(d)).collect(); + let actions = objects_of(&saved, "ACDBASSOCACTION"); + let lister = actions.iter().find(|a| a.iter().any(|(c, _)| c == "290")).expect("the unknown action is written"); + let sub: Vec<(String, String)> = lister.iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocAction")).cloned().collect(); + let (count, entries) = dependency_list(&sub, 8); + assert_eq!(count, entries.len(), "the count matches the written list: {entries:?}"); + assert!(entries.iter().all(|(_, h)| written.contains(h)), "every entry names a written dependency: {entries:?}"); +} diff --git a/crates/io/tests/it/dynblock_array.rs b/crates/io/tests/it/dynblock_array.rs new file mode 100644 index 000000000..b5113f2ec --- /dev/null +++ b/crates/io/tests/it/dynblock_array.rs @@ -0,0 +1,327 @@ +//! Array actions of dynamic blocks: a reference repeats the arrayed objects as far as its linear, +//! polar or XY parameter reaches, as AutoCAD does (one copy per whole column along a distance; a +//! whole number of columns by rows across an XY parameter, or just the object when either is +//! short of one), marks the copies as AutoCAD marks them, and keeps the right number of copies +//! through later changes and a save. +//! +//! The fixture is synthetic: block Row (a 2×2 square, Distance1 from the origin to (2, 0), copies +//! every 3), Fan (a circle, Distance1/Angle1 from the origin to (3, 4), copies every 2) and Grid +//! (a circle, X Distance1/Y Distance1 from the origin to (10, 10), columns every 5 and rows every +//! 4, distances at least 0). + +use cadcraft_doc::dynblock::{ActionKind, GripPart, GripShape, ParameterKind, custom_properties, drag_grip, dynamic_block, grips, set_property}; +use cadcraft_doc::geom::{Vec2, Vec3}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// The fixture with a reference to `block` at (100, 100). +fn reference(block: &str) -> (Drawing, Handle) { + let mut d = read_dxf(dxf(&include_str!("../data/dynblock_arrays.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: block.into(), + insert: Vec3::new(100.0, 100.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() +} + +/// Where each object of the reference's block is (a circle's centre, a polyline's first vertex). +fn places(d: &Drawing, r: Handle) -> Vec<(f64, f64)> { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let round = |v: f64| (v * 1000.0).round() / 1000.0; + d.block(&i.block) + .unwrap() + .entities + .iter() + .map(|e| match &e.kind { + EntityKind::Circle(c) => (round(c.center.x), round(c.center.y)), + EntityKind::LwPolyline(p) => (round(p.vertices[0].p.x), round(p.vertices[0].p.y)), + k => panic!("unexpected {k:?}"), + }) + .collect() +} + +/// Whether each object of the reference's block is marked as an array's copy. +fn marked(d: &Drawing, r: Handle) -> Vec { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let mark = |e: &cadcraft_doc::Entity| e.common.xdata.iter().any(|t| t.code == 1001 && t.value == "AcDbBlockArrayActionTag"); + d.block(&i.block).unwrap().entities.iter().map(|e| mark(e)).collect() +} + +#[test] +fn reads_array_actions_and_polar_and_xy_parameters() { + let (d, _) = reference("Row"); + let m = dynamic_block(&d, "Row").unwrap(); + assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 3.0, row: 1.0 })); + assert_eq!(m.actions[0].connections.len(), 4); + let m = dynamic_block(&d, "Fan").unwrap(); + let ParameterKind::Polar { label, angle_label, .. } = &m.parameters[0].kind else { panic!("a polar parameter") }; + assert_eq!((label.as_str(), angle_label.as_str()), ("Distance1", "Angle1")); + let m = dynamic_block(&d, "Grid").unwrap(); + let ParameterKind::Xy { x_label, y_label, x_values, y_values, .. } = &m.parameters[0].kind else { panic!("an XY parameter") }; + assert_eq!((x_label.as_str(), y_label.as_str()), ("X Distance1", "Y Distance1")); + assert!(x_values.has_minimum() && y_values.has_minimum()); + assert_eq!(m.parameters[0].grips, vec![3, 2, 4, 5], "base, end and the two corner grips"); + assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 5.0, row: 4.0 })); +} + +#[test] +fn polar_and_xy_parameters_show_their_two_properties() { + let (d, r) = reference("Fan"); + assert_eq!(props(&d, r), pairs(&[("Distance1", "5.0000"), ("Angle1", "53")])); + let (d, r) = reference("Grid"); + assert_eq!(props(&d, r), pairs(&[("X Distance1", "10.0000"), ("Y Distance1", "10.0000")])); +} + +#[test] +fn a_distance_repeats_the_objects_once_per_whole_column() { + let (mut d, r) = reference("Row"); + set_property(&mut d, r, "Distance1", "9").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0), (6.0, 0.0)]); + assert_eq!(marked(&d, r), vec![false, true, true], "AutoCAD marks every copy but the first"); + // Short of a whole column: one fewer; short of one: the object alone. + set_property(&mut d, r, "Distance1", "8.9").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0)]); + set_property(&mut d, r, "Distance1", "2.5").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0)]); + assert_eq!(marked(&d, r), vec![false]); + set_property(&mut d, r, "Distance1", "12").unwrap(); + assert_eq!(places(&d, r).len(), 4); +} + +#[test] +fn a_polar_parameter_repeats_along_its_angle() { + let (mut d, r) = reference("Fan"); + set_property(&mut d, r, "Distance1", "7").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (1.2, 1.6), (2.4, 3.2)]); + set_property(&mut d, r, "Angle1", "90").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]); + assert_eq!(props(&d, r), pairs(&[("Distance1", "7.0000"), ("Angle1", "90")])); +} + +#[test] +fn an_xy_parameter_repeats_in_columns_and_rows() { + let (mut d, r) = reference("Grid"); + // 10 × 10 with columns every 5 and rows every 4: 2 by 2. + set_property(&mut d, r, "Y Distance1", "10").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (5.0, 0.0), (0.0, 4.0), (5.0, 4.0)]); + set_property(&mut d, r, "Y Distance1", "13").unwrap(); + assert_eq!(places(&d, r).len(), 6, "2 columns by 3 rows, the earlier copies replaced"); + assert_eq!(marked(&d, r), vec![false, true, true, true, true, true]); + // Short of one column: the object alone, however many rows fit. + set_property(&mut d, r, "X Distance1", "4").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0)]); + // Below the value set's minimum: refused, as AutoCAD refuses it. + assert!(set_property(&mut d, r, "X Distance1", "-10").is_err()); + assert_eq!(props(&d, r), pairs(&[("X Distance1", "4.0000"), ("Y Distance1", "13.0000")])); +} + +#[test] +fn xy_grips_move_the_base_end_and_corners() { + let (mut d, r) = reference("Grid"); + let gs = grips(&d, r); + let summary: Vec<(GripPart, GripShape, (f64, f64))> = gs.iter().map(|g| (g.part, g.shape, (g.at.x, g.at.y))).collect(); + assert_eq!( + summary, + vec![ + (GripPart::Base, GripShape::Point, (100.0, 100.0)), + (GripPart::End, GripShape::Point, (110.0, 110.0)), + (GripPart::BaseXEndY, GripShape::Point, (100.0, 110.0)), + (GripPart::BaseYEndX, GripShape::Point, (110.0, 100.0)), + ] + ); + // The base X and end Y corner, dragged left and up: the base moves left (the circle with + // it, as AutoCAD's arrays follow the base), the end up. + drag_grip(&mut d, r, 1, GripPart::BaseXEndY, Vec2::new(95.0, 112.0)).unwrap(); + assert_eq!(props(&d, r), pairs(&[("X Distance1", "15.0000"), ("Y Distance1", "12.0000")])); + assert_eq!(places(&d, r), vec![(-5.0, 0.0), (0.0, 0.0), (5.0, 0.0), (-5.0, 4.0), (0.0, 4.0), (5.0, 4.0), (-5.0, 8.0), (0.0, 8.0), (5.0, 8.0)]); + // A corner past the base: below the minimum, refused. + assert!(drag_grip(&mut d, r, 1, GripPart::BaseYEndX, Vec2::new(90.0, 100.0)).is_err()); + assert!(drag_grip(&mut d, r, 1, GripPart::At, Vec2::new(90.0, 100.0)).is_err()); +} + +#[test] +fn polar_grips_move_the_end_and_the_base() { + let (mut d, r) = reference("Fan"); + let parts: Vec = grips(&d, r).into_iter().map(|g| g.part).collect(); + assert_eq!(parts, vec![GripPart::Base, GripPart::End]); + drag_grip(&mut d, r, 1, GripPart::End, Vec2::new(100.0, 106.0)).unwrap(); + assert_eq!(props(&d, r), pairs(&[("Distance1", "6.0000"), ("Angle1", "90")])); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]); +} + +#[test] +fn copies_and_values_survive_a_save() { + let (mut d, r) = reference("Grid"); + set_property(&mut d, r, "X Distance1", "12").unwrap(); + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&back, r), props(&d, r)); + assert_eq!(places(&back, r), places(&d, r)); + // Changed again after the save: still one set of copies. + let mut back = back; + set_property(&mut back, r, "Y Distance1", "5").unwrap(); + assert_eq!(places(&back, r), vec![(0.0, 0.0), (5.0, 0.0)]); +} + +#[test] +fn hostile_arrays_are_refused_not_built() { + let (mut d, r) = reference("Grid"); + // A billion columns: refused before any copy is made. + assert!(set_property(&mut d, r, "X Distance1", "1e10").is_err()); + assert!(set_property(&mut d, r, "X Distance1", "NaN").is_err()); + assert!(set_property(&mut d, r, "X Distance1", "inf").is_err()); + assert_eq!(places(&d, r), vec![(0.0, 0.0)]); + let (mut d, r) = reference("Row"); + assert!(set_property(&mut d, r, "Distance1", "1e300").is_err()); + let (mut d, r) = reference("Fan"); + assert!(set_property(&mut d, r, "Angle1", "nan").is_err()); + assert!(set_property(&mut d, r, "Distance1", "0").is_err()); +} + +/// Row with an associative hatch on its square (handle 31), the hatch also in the array's +/// selection. +fn hatched_row() -> (Drawing, Handle) { + let hatch = [ + "0 HATCH", + "5 31", + "330 1D", + "100 AcDbEntity", + "8 0", + "100 AcDbHatch", + "10 0", + "20 0", + "30 0", + "210 0", + "220 0", + "230 1", + "2 SOLID", + "70 1", + "71 1", + "91 1", + "92 3", + "72 0", + "73 1", + "93 4", + "10 0", + "20 0", + "10 2", + "20 0", + "10 2", + "20 2", + "10 0", + "20 2", + "97 1", + "330 30", + "75 0", + "76 1", + "98 0", + "1001 AcDbBlockRepETag", + "1070 1", + "1071 1", + "1005 31", + ] + .join("\n"); + let src = include_str!("../data/dynblock_arrays.txt") + .replace("\r\n", "\n") + .replace("1005 30\n0 ENDBLK", &format!("1005 30\n{hatch}\n0 ENDBLK")) + .replace("71 1\n330 30\n1010 4", "71 2\n330 30\n330 31\n1010 4"); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: "Row".into(), + insert: Vec3::new(100.0, 100.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +#[test] +fn a_repeated_associative_hatch_follows_its_own_outline() { + let (mut d, r) = hatched_row(); + set_property(&mut d, r, "Distance1", "9").unwrap(); + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let b = d.block(&i.block).unwrap(); + let first_x = |e: &cadcraft_doc::Entity| match &e.kind { + EntityKind::LwPolyline(p) => Some(p.vertices[0].p.x), + EntityKind::Hatch(h) => h.loops[0].vertices.first().map(|v| v.p.x), + _ => None, + }; + let outlines: Vec<(Handle, f64)> = + b.entities.iter().filter(|e| matches!(e.kind, EntityKind::LwPolyline(_))).filter_map(|e| Some((e.handle, first_x(e)?))).collect(); + let hatches: Vec<&cadcraft_doc::Entity> = b.entities.iter().filter(|e| matches!(e.kind, EntityKind::Hatch(_))).map(|e| &**e).collect(); + assert_eq!((outlines.len(), hatches.len()), (3, 3), "the square and its hatch, three times"); + let mut xs = Vec::new(); + for h in hatches { + let EntityKind::Hatch(hh) = &h.kind else { continue }; + let [src] = hh.loops[0].sources.as_slice() else { panic!("one source") }; + let (_, outline_x) = outlines.iter().find(|(oh, _)| oh == src).expect("the loop names a square of this block"); + // Each hatch fills the square at its own place, not the first one. + assert!((first_x(h).unwrap() - outline_x).abs() < 1e-9, "{} vs {outline_x}", first_x(h).unwrap()); + xs.push((outline_x * 1000.0).round() as i64); + } + xs.sort_unstable(); + assert_eq!(xs, vec![0, 3000, 6000]); +} + +#[test] +fn a_polar_end_grip_snaps_its_angle_to_the_angle_value_set() { + // Fan with Angle1 limited to 0° and 90° (a list, in radians). + let free = "307 Angle1\n308\n140 0\n309\n96 0\n141 0\n142 0\n143 0\n175 0\n410\n97 0\n145 0\n146 0\n147 0\n176 0"; + let src = include_str!("../data/dynblock_arrays.txt").replace("\r\n", "\n"); + assert_eq!(src.matches(free).count(), 1); + let src = src.replace(free, &free.replace("97 0\n145 0\n146 0\n147 0\n176 0", "97 8\n145 0\n146 0\n147 0\n176 2\n148 0\n148 1.5707963267948966")); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: "Fan".into(), + insert: Vec3::new(100.0, 100.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + // Dragged toward 40°: the nearest allowed angle is 0°, the distance kept. + drag_grip(&mut d, r, 1, GripPart::End, Vec2::new(100.0 + 6.0 * 40f64.to_radians().cos(), 100.0 + 6.0 * 40f64.to_radians().sin())).unwrap(); + assert_eq!(props(&d, r), pairs(&[("Distance1", "6.0000"), ("Angle1", "0")])); + // Toward 60°: 90°. + drag_grip(&mut d, r, 1, GripPart::End, Vec2::new(100.0 + 6.0 * 60f64.to_radians().cos(), 100.0 + 6.0 * 60f64.to_radians().sin())).unwrap(); + assert_eq!(props(&d, r), pairs(&[("Distance1", "6.0000"), ("Angle1", "90")])); +} diff --git a/crates/io/tests/it/dynblock_params.rs b/crates/io/tests/it/dynblock_params.rs new file mode 100644 index 000000000..c04e393f0 --- /dev/null +++ b/crates/io/tests/it/dynblock_params.rs @@ -0,0 +1,301 @@ +//! Base point and alignment parameters of dynamic blocks, and lookup tables that set angles, flip +//! states, XY distances and positions, as AutoCAD applies them: +//! - an action that moves a base point parameter moves the reference's insertion point with it, +//! and the block's objects move back so the parameter stays at the block's base point; +//! - an alignment grip dragged next to an object moves the reference so the alignment's base is on +//! the object and turns it so the alignment runs along the object, its right side toward the +//! cursor; +//! - lookup tables set and read rotation angles (`UpdatedAngle`, radians), flip states +//! (`UpdatedFlip`), XY distances (`UpdatedDistanceX`/`Y`), polar distances and angles and +//! positions (`UpdatedX`/`Y`, from the block's base point). +//! +//! The fixture is synthetic, laid out as AutoCAD writes these blocks: Shift (a 10×5 rectangle left +//! of the origin, Distance1 along its bottom, a stretch of its right side holding the base point +//! parameter, an attribute TAG at (-8, 0); a reference at (100, 100) with its attribute at (92, 100)), +//! Align (a 4×2 rectangle, a perpendicular alignment from the origin along X), Turn (a 4×2 +//! rectangle turned by Angle1 about the origin; Lookup1 gives Up 90°, Left 180°, Zero 0°) and Many +//! (Flip state1, X/Y Distance1, polar Distance1/Angle1 and Position1, all set by Lookup1's rows A +//! and B, B being the block's own values). A line at 30° runs from (120, 100) to (140, 111.547). + +use cadcraft_doc::dynblock::{GripShape, ParameterKind, Value, align_grip, custom_properties, dynamic_block, grips, reference, set_property}; +use cadcraft_doc::geom::{Vec2, Vec3}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +fn fixture() -> Drawing { + read_dxf(dxf(&include_str!("../data/dynblock_params.txt").replace("\r\n", "\n")).as_bytes()).unwrap() +} + +/// The fixture with a reference to `block` at (100, 100) turned by `rotation`. +fn reference_to(block: &str, rotation: f64) -> (Drawing, Handle) { + let mut d = fixture(); + let ins = cadcraft_doc::Insert { + block: block.into(), + insert: Vec3::new(100.0, 100.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +fn prop(d: &Drawing, r: Handle, name: &str) -> String { + props(d, r).into_iter().find(|(n, _)| n == name).map(|(_, v)| v).unwrap_or_else(|| panic!("no {name}")) +} + +fn round(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 + 0.0 +} + +fn insert(d: &Drawing, r: Handle) -> &cadcraft_doc::Insert { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + i +} + +/// The reference's polyline corners (lowest and highest) in block coordinates. +fn outline(d: &Drawing, r: Handle) -> [f64; 4] { + let b = d.block(&insert(d, r).block).unwrap(); + let pl = b + .entities + .iter() + .find_map(|e| match &e.kind { + EntityKind::LwPolyline(p) => Some(p), + _ => None, + }) + .unwrap(); + let xs = pl.vertices.iter().map(|v| v.p.x); + let ys = pl.vertices.iter().map(|v| v.p.y); + [ + round(xs.clone().fold(f64::MAX, f64::min)), + round(ys.clone().fold(f64::MAX, f64::min)), + round(xs.fold(f64::MIN, f64::max)), + round(ys.fold(f64::MIN, f64::max)), + ] +} + +fn at(d: &Drawing, r: Handle) -> (f64, f64) { + let i = insert(d, r); + (round(i.insert.x), round(i.insert.y)) +} + +#[test] +fn reads_the_alignment_type_and_shows_its_grip() { + let (d, r) = reference_to("Align", 0.0); + let m = dynamic_block(&d, "Align").unwrap(); + assert!(matches!(m.parameters[0].kind, ParameterKind::Alignment { perpendicular: true, .. })); + let g = grips(&d, r); + let a = g.iter().find(|g| g.shape == GripShape::Alignment).expect("an alignment grip"); + // At the base point, pointing to the left of the alignment's direction (as AutoCAD draws it). + assert_eq!((round(a.at.x), round(a.at.y)), (100.0, 100.0)); + assert_eq!((round(a.dir.x), round(a.dir.y)), (0.0, 1.0)); +} + +#[test] +fn a_moved_base_point_moves_the_insertion_point() { + let mut d = fixture(); + let r = Handle(0xE0); + set_property(&mut d, r, "Distance1", "15").unwrap(); + // Measured in AutoCAD: the reference moves to (105, 100) and its block runs from -15 to 0. + assert_eq!(at(&d, r), (105.0, 100.0)); + assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]); + assert_eq!(prop(&d, r, "Distance1"), "15.0000"); + // The values as AutoCAD records them: the base point at the block's base, the distance moved back. + let v = reference(&d, r).unwrap().values; + assert_eq!(v.get(&1), Some(&Value::Point { at: Vec3::new(0.0, 0.0, 0.0) })); + assert_eq!(v.get(&2), Some(&Value::Points { base: Vec3::new(-15.0, -2.5, 0.0), end: Vec3::new(0.0, -2.5, 0.0) })); + // The attribute stays where it was in the drawing (its definition didn't move). + let a = &insert(&d, r).attribs[0]; + assert_eq!((round(a.text.insert.x), round(a.text.insert.y)), (92.0, 100.0)); + // And back, from there. + set_property(&mut d, r, "Distance1", "12").unwrap(); + assert_eq!(at(&d, r), (102.0, 100.0)); + assert_eq!(outline(&d, r), [-12.0, -2.5, 0.0, 2.5]); + // A save keeps it. + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(at(&back, r), (102.0, 100.0)); + assert_eq!(prop(&back, r, "Distance1"), "12.0000"); +} + +/// AutoCAD takes a distance of 0 (title block value lists offer it); the distance keeps its +/// direction for the next change. +#[test] +fn a_distance_of_0_keeps_its_direction() { + let mut d = fixture(); + let r = Handle(0xE0); + set_property(&mut d, r, "Distance1", "0").unwrap(); + assert_eq!(prop(&d, r, "Distance1"), "0.0000"); + assert_eq!(at(&d, r), (90.0, 100.0)); + set_property(&mut d, r, "Distance1", "15").unwrap(); + assert_eq!(at(&d, r), (105.0, 100.0)); + assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]); + assert!(set_property(&mut d, r, "Distance1", "-1").is_err()); +} + +#[test] +fn a_turned_reference_moves_along_its_own_axis() { + let (mut d, r) = reference_to("Shift", std::f64::consts::FRAC_PI_2); + set_property(&mut d, r, "Distance1", "15").unwrap(); + assert_eq!(at(&d, r), (100.0, 105.0)); +} + +#[test] +fn an_alignment_follows_a_line() { + let line = Vec2::new(30f64.to_radians().cos(), 30f64.to_radians().sin()); + let foot = Vec2::new(120.0, 100.0) + line * 10.0; + // Measured in AutoCAD: from below the line the reference turns to 30°, from above to 210°, its + // alignment's base on the line. + for (side, rotation) in [(-0.5, 30.0), (0.5, 210.0)] { + let (mut d, r) = reference_to("Align", 0.0); + let cursor = foot + line.perp() * side; + align_grip(&mut d, r, 1, cursor, Some((foot, line))).unwrap(); + assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation); + assert_eq!(at(&d, r), (round(foot.x), round(foot.y))); + } +} + +#[test] +fn an_alignment_follows_a_circle() { + // A circle about (150, 150), its nearest point at 225°: outside, the reference turns to 315° + // (counterclockwise along the circle), inside to 135°, as in AutoCAD. + let c = Vec2::new(150.0, 150.0); + let out = Vec2::new(225f64.to_radians().cos(), 225f64.to_radians().sin()); + let foot = c + out * 10.0; + for (r_cursor, rotation) in [(10.5, 315.0), (9.5, 135.0)] { + let (mut d, r) = reference_to("Align", 0.0); + align_grip(&mut d, r, 1, c + out * r_cursor, Some((foot, out.perp()))).unwrap(); + assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation); + } +} + +#[test] +fn an_alignment_grip_away_from_objects_only_moves() { + let (mut d, r) = reference_to("Align", 0.5); + align_grip(&mut d, r, 1, Vec2::new(90.0, 80.0), None).unwrap(); + assert_eq!(at(&d, r), (90.0, 80.0)); + assert_eq!(insert(&d, r).rotation, 0.5); + // On the object itself, the side the grip came from decides. + let (mut d, r) = reference_to("Align", 0.0); + let line = Vec2::new(1.0, 0.0); + align_grip(&mut d, r, 1, Vec2::new(110.0, 90.0), Some((Vec2::new(110.0, 90.0), line))).unwrap(); + // The grip was above the line (y = 90): its right side faces up, so the alignment runs to -X. + assert_eq!(round(insert(&d, r).rotation.to_degrees()), 180.0); + assert!(align_grip(&mut d, r, 1, Vec2::new(f64::NAN, 0.0), None).is_err()); + assert!(align_grip(&mut d, r, 7, Vec2::new(0.0, 0.0), None).is_err()); +} + +#[test] +fn a_lookup_sets_and_reads_an_angle() { + let (mut d, r) = reference_to("Turn", 0.0); + assert_eq!(prop(&d, r, "Lookup1"), "Zero"); + set_property(&mut d, r, "Lookup1", "Up").unwrap(); + assert_eq!(prop(&d, r, "Angle1"), "90"); + assert_eq!(outline(&d, r), [-2.0, 0.0, 0.0, 4.0]); + // Reverse: an angle in the table gives its row. + set_property(&mut d, r, "Angle1", "180").unwrap(); + assert_eq!(prop(&d, r, "Lookup1"), "Left"); + set_property(&mut d, r, "Angle1", "45").unwrap(); + assert_eq!(prop(&d, r, "Lookup1"), "Custom"); + assert!(custom_properties(&d, r).unwrap().1.iter().any(|p| p.name == "Lookup1" && p.editable)); +} + +#[test] +fn a_lookup_sets_flips_xy_polar_and_positions() { + let (mut d, r) = reference_to("Many", 0.0); + // The block's own values are row B. + assert_eq!(prop(&d, r, "Lookup1"), "B"); + set_property(&mut d, r, "Lookup1", "A").unwrap(); + // As AutoCAD sets them. + for (name, value) in [ + ("Flip state1", "Flipped"), + ("X Distance1", "6.0000"), + ("Y Distance1", "3.0000"), + ("Distance1", "5.0000"), + ("Angle1", "30"), + ("Position1 X", "1.0000"), + ("Position1 Y", "0.5000"), + ("Lookup1", "A"), + ] { + assert_eq!(prop(&d, r, name), value, "{name}"); + } + // The values are recorded as AutoCAD lays them out (it doesn't take the reference otherwise): a + // flip state after its points, and the flip grip's state on its own after two header groups. + let codes: Vec> = d + .foreign + .objects + .iter() + .filter(|o| o.kind == "XRECORD") + .map(|o| o.tags.iter().map(|t| t.code).filter(|c| [10, 70].contains(c)).collect()) + .collect(); + assert!(codes.contains(&vec![10, 10, 70]), "{codes:?}"); + assert!(codes.contains(&vec![70, 70, 70, 70]), "{codes:?}"); + // A save keeps it, and the reverse lookup reads it back. + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(prop(&back, r, "Lookup1"), "A"); + assert_eq!(prop(&back, r, "Flip state1"), "Flipped"); + // One input off the table's rows: no row matches. + set_property(&mut d, r, "Flip state1", "Not flipped").unwrap(); + assert_eq!(prop(&d, r, "Lookup1"), "Custom"); + set_property(&mut d, r, "Lookup1", "B").unwrap(); + assert_eq!(prop(&d, r, "X Distance1"), "4.0000"); + assert_eq!(prop(&d, r, "Position1 X"), "2.0000"); +} + +#[test] +fn a_lookup_cell_that_isnt_a_number_is_refused() { + let src = include_str!("../data/dynblock_params.txt").replace("\r\n", "\n").replace("302 1.570796326794896", "302 up-ish"); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: "Turn".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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + let before = insert(&d, r).block.clone(); + assert!(set_property(&mut d, r, "Lookup1", "Up").is_err()); + assert_eq!(insert(&d, r).block, before); + // The other rows still work, and reading the table doesn't trip on the bad cell. + set_property(&mut d, r, "Lookup1", "Left").unwrap(); + assert_eq!(prop(&d, r, "Angle1"), "180"); +} + +#[test] +fn an_xy_distance_past_the_number_range_is_refused() { + // With an X scale of 1e-12, 1e308 typed is past the range in block units. + let (mut d, r) = reference_to("Many", 0.0); + let _ = d.modify_entity(r, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.scale.x = 1e-12; + } + }); + let before = prop(&d, r, "X Distance1"); + assert!(set_property(&mut d, r, "X Distance1", "1e308").is_err()); + assert_eq!(prop(&d, r, "X Distance1"), before); +} diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index 51c83ac40..0bae128b2 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -114,7 +114,7 @@ fn a_scale_action_survives_a_dwg_save() { cadcraft_io::dwg_worker::allow_in_process(); let d = read_dxf(dxf(&with_scale_action()).as_bytes()).unwrap(); let before = dynamic_block(&d, "Door").unwrap(); - assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale)), "{:?}", before.actions); + assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale { .. })), "{:?}", before.actions); let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); @@ -347,9 +347,7 @@ fn bad_values_are_refused_and_change_nothing() { let ps = cadcraft_doc::dynblock::custom_properties(&d, h("80")).unwrap().1; let editable: Vec<(&str, bool)> = ps.iter().map(|p| (p.name.as_str(), p.editable)).collect(); assert_eq!(editable, [("Visibility1", true), ("Width", true), ("Size", true)]); - for (name, value) in - [("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "0"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")] - { + for (name, value) in [("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")] { assert!(cadcraft_doc::dynblock::set_property(&mut d, h("80"), name, value).is_err(), "{name}={value}"); } assert!(cadcraft_doc::dynblock::set_property(&mut d, h("30"), "Visibility1", "Open").is_err(), "not a reference"); @@ -800,3 +798,55 @@ fn a_dynamic_block_with_handles_above_2_pow_48_is_kept() { let again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); assert_eq!(by_node(dynamic_block(&again, "Door").unwrap()), by_node(before)); } + +/// A multiline attribute (LABEL, two lines) in the stretch's selection: when Width changes, the +/// reference's attribute moves with its definition, its multiline text too. +#[test] +fn a_stretch_moves_a_multiline_attributes_text() { + let attdef = "0 ATTDEF\n5 3A\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbText\n10 35\n20 0\n30 0\n40 1\n1 SITE\n7 Standard\n100 AcDbAttributeDefinition\n280 0\n3 Label\n2 LABEL\n70 0\n280 1\n71 4\n72 0\n11 35\n21 0\n31 0\n101 Embedded Object\n10 35\n20 0\n30 0\n40 1\n41 0\n46 0\n71 1\n72 5\n1 SITE\\PNAME\n7 Standard\n73 1\n44 1\n"; + let src = fixture().replace("71 1\n330 30\n1010 40", "71 2\n330 30\n330 3A\n1010 40"); + // Into Door's block, before its end. + let door = src.find("2 Door\n70 0").unwrap(); + let end = door + src[door..].find("0 ENDBLK").unwrap(); + let src = format!("{}{attdef}{}", &src[..end], &src[end..]); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let def = d + .block("Door") + .unwrap() + .entities + .iter() + .find_map(|e| if let cadcraft_doc::EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }) + .expect("the attribute definition"); + assert!(def.multiline.is_some(), "a multiline definition"); + // A reference at (100, 0) with its attribute where the definition puts it. + let r = door_at_100(&mut d); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + let mut a = def.clone(); + let m = cadcraft_doc::geom::Mat3::translate(cadcraft_doc::geom::Vec2::new(100.0, 0.0)); + let mut k = cadcraft_doc::EntityKind::Text(a.text.clone()); + k.transform(&m); + if let cadcraft_doc::EntityKind::Text(t) = k { + a.text = t; + } + a.transform_multiline(&m); + i.attribs.push(a); + } + }) + .unwrap(); + // Width 36 → 30: the attribute moves 6 to the left, its multiline text with it. + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + let Some(cadcraft_doc::EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") }; + let a = &i.attribs[0]; + assert_eq!(a.text.insert.x, 129.0); + assert_eq!(a.multiline.as_ref().unwrap().mtext.insert.x, 129.0); + // Saved (in the drawing's version, 2018: R2000 DXF has no multiline attributes) and reopened: + // the moved attribute and its multiline text stay where they went. + let again = cadcraft_io::read(&cadcraft_io::write(&d, "door.dxf").unwrap(), "door.dxf").unwrap(); + let Some(cadcraft_doc::EntityKind::Insert(i)) = again.entity(r).map(|e| &e.kind) else { panic!("no reference after reopening") }; + let a = &i.attribs[0]; + assert_eq!((a.text.insert.x, a.text.insert.y), (129.0, 0.0)); + let m = &a.multiline.as_ref().expect("still multiline").mtext; + assert_eq!((m.insert.x, m.insert.y), (129.0, 0.0)); + assert_eq!(m.contents, r"SITE\PNAME"); +} diff --git a/crates/io/tests/it/dynblock_rotate_flip.rs b/crates/io/tests/it/dynblock_rotate_flip.rs new file mode 100644 index 000000000..b89efd83e --- /dev/null +++ b/crates/io/tests/it/dynblock_rotate_flip.rs @@ -0,0 +1,285 @@ +//! Rotation and flip parameters of dynamic blocks: their rotate and flip actions turn and mirror +//! the objects (text stays readable), carry the parameters in their selection, record the +//! change as AutoCAD does, and give the reference a rotation grip and a flip grip. +//! +//! The fixture is synthetic: block Symbol (a circle, a line from the origin to (0, 3) and an +//! attribute TAG at (1, 2) turned 90°) with Angle1 (base at the origin, radius to (2, 0)) and its +//! rotate action, Flip state1 (reflection line from the origin to (-10, 0)) and its flip action, +//! and Position1 at (0, 3) with a move action. + +use cadcraft_doc::dynblock::{ + ActionKind, GripPart, GripShape, ParameterKind, Value, custom_properties, drag_grip, dynamic_block, grip_stops, grips, reference, set_property, +}; +use cadcraft_doc::geom::{Vec2, Vec3}; +use cadcraft_doc::{Drawing, EntityKind, Handle, RawTag}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// Symbol and a reference to it at (100, 100) with its attribute. +fn symbol() -> (Drawing, Handle) { + symbol_from(&include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n")) +} + +/// As [`symbol`], from the fixture's text `src` (changed by a test). +fn symbol_from(src: &str) -> (Drawing, Handle) { + let mut d = read_dxf(dxf(src).as_bytes()).unwrap(); + let def = + d.block("Symbol").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap(); + let mut a = def.clone(); + a.text.insert = a.text.insert + Vec3::new(100.0, 100.0, 0.0); + let ins = cadcraft_doc::Insert { + block: "Symbol".into(), + insert: Vec3::new(100.0, 100.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: vec![a], + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() +} + +/// The reference's block: its line's end and attribute definition (insertion, rotation in degrees). +fn shown(d: &Drawing, r: Handle) -> (Vec2, Vec2, f64) { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") }; + let b = d.block(&i.block).unwrap(); + let line = b.entities.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.b.xy()) } else { None }).unwrap(); + let (at, rot) = + b.entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some((a.text.insert.xy(), a.text.rotation)) } else { None }).unwrap(); + (line, at, rot.to_degrees()) +} + +fn near(a: Vec2, b: (f64, f64)) -> bool { + (a.x - b.0).abs() < 1e-6 && (a.y - b.1).abs() < 1e-6 +} + +#[test] +fn rotation_and_flip_are_read() { + let (d, _) = symbol(); + let m = dynamic_block(&d, "Symbol").unwrap(); + let p = |node: i32| &m.parameters.iter().find(|p| p.node == node).unwrap().kind; + assert!(matches!(p(15), ParameterKind::Rotation { label, values, .. } if label == "Angle1" && values.maximum > 6.0)); + assert!( + matches!(p(20), ParameterKind::Flip { label, states, .. } if label == "Flip state1" && states == &["Not flipped".to_string(), "Flipped".to_string()]) + ); + let a = |node: i32| m.actions.iter().find(|a| a.node == node).unwrap(); + assert!(matches!(&a(19).kind, ActionKind::Rotate { base } if base.dependent)); + assert_eq!(a(19).connections.last(), Some(&(15, "AngleDelta".to_string()))); + assert!(matches!(a(25).kind, ActionKind::Flip)); + assert_eq!(a(25).connections.len(), 4); +} + +#[test] +fn an_angle_turns_and_a_flip_mirrors_what_their_actions_hold() { + let (mut d, r) = symbol(); + assert_eq!(props(&d, r), pairs(&[("Angle1", "0"), ("Flip state1", "Not flipped"), ("Position1 X", "0.0000"), ("Position1 Y", "3.0000")])); + + // 30°: the line, the attribute and Position1 turn about the origin; the text turns with them. + set_property(&mut d, r, "angle1", "30").unwrap(); + let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let (line, at, rot) = shown(&d, r); + assert!(near(line, (-3.0 * s, 3.0 * c)), "{line:?}"); + assert!(near(at, (c - 2.0 * s, s + 2.0 * c)), "{at:?}"); + assert!((rot - 120.0).abs() < 1e-9); + assert_eq!(props(&d, r), pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped"), ("Position1 X", "-1.5000"), ("Position1 Y", "2.5981")])); + // The reference's attribute follows its definition. + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") }; + assert!(near(i.attribs[0].text.insert.xy(), (100.0 + at.x, 100.0 + at.y))); + + // Flipped: mirrored across the reflection line, which turned with them (now at 30°); the + // text keeps reading left to right. + set_property(&mut d, r, "Flip state1", "Flipped").unwrap(); + let (s2, c2) = (60f64.to_radians().sin(), 60f64.to_radians().cos()); + let mirror = |p: Vec2| (p.x * c2 + p.y * s2, p.x * s2 - p.y * c2); + let (line2, at2, rot) = shown(&d, r); + assert!(near(line2, mirror(line)), "{line2:?}"); + assert!(near(at2, mirror(at)), "{at2:?}"); + assert!((rot - 120.0).abs() < 1e-9, "readable"); + assert_eq!(props(&d, r)[1..], pairs(&[("Flip state1", "Flipped"), ("Position1 X", "1.5000"), ("Position1 Y", "-2.5981")])); + + // Both survive a save. + let again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&again, r), props(&d, r)); + // Back to not flipped: back to the turned geometry. + set_property(&mut d, r, "Flip state1", "0").unwrap(); + assert!(near(shown(&d, r).1, (at.x, at.y))); +} + +#[test] +fn rotation_and_flip_grips() { + let (mut d, r) = symbol(); + set_property(&mut d, r, "Angle1", "30").unwrap(); + let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let g = grips(&d, r); + let rot = g.iter().find(|g| g.shape == GripShape::Rotation).unwrap(); + assert_eq!((rot.node, rot.part), (15, GripPart::End)); + assert!(near(rot.at, (100.0 + 2.0 * c, 100.0 + 2.0 * s)), "at the radius' end: {:?}", rot.at); + let flip = g.iter().find(|g| g.shape == GripShape::Flip).unwrap(); + assert_eq!((flip.node, flip.part, flip.choices.len()), (20, GripPart::Base, 2)); + // The flip grip object at (-2, 0) turned with the reflection line. + assert!(near(flip.at, (100.0 - 2.0 * c, 100.0 - 2.0 * s)), "{:?}", flip.at); + + // Dragging the rotation grip straight up from the base: 90°. + drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 105.0)).unwrap(); + assert_eq!(props(&d, r)[0].1, "90"); + // A flip grip is clicked, not dragged; the base of the angle is not a point to aim at. + assert!(drag_grip(&mut d, r, 20, GripPart::Base, Vec2::new(90.0, 90.0)).is_err()); + assert!(drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 100.0)).is_err()); +} + +#[test] +fn a_rotation_grip_off_the_radius_stays_where_its_grip_object_is() { + // The grip object a quarter turn round from the radius' end (as AutoCAD saves blocks whose + // grip was moved there): the circle is drawn there and turns with the angle, and dragging + // it turns the block by the cursor's turn, not to the cursor's direction. + let src = include_str!("../data/dynblock_symbol.txt") + .replace("\r\n", "\n") + .replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n"); + let (mut d, r) = symbol_from(&src); + let at = |d: &Drawing| grips(d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap(); + assert!(near(at(&d), (100.0, 102.0)), "{:?}", at(&d)); + // Dropped where it is: no turn. + drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 102.0)).unwrap(); + assert!(props(&d, r).contains(&("Angle1".to_string(), "0".to_string())), "{:?}", props(&d, r)); + // A quarter turn further round: Angle1 90, and the grip is there. + drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(98.0, 100.0)).unwrap(); + assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r)); + assert!(near(at(&d), (98.0, 100.0)), "{:?}", at(&d)); +} + +#[test] +fn an_angle_shows_and_is_typed_as_the_drawing_measures_angles() { + // Angles measured clockwise from north (ANGBASE 90°, ANGDIR 1): AutoCAD shows Angle1 0 as + // 90 and 0.5 rad as 61.35, and a typed angle is read the same way. + let (mut d, r) = symbol(); + d.header.set_f64("ANGBASE", std::f64::consts::FRAC_PI_2); + d.header.set_i64("ANGDIR", 1); + assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r)); + // 60 shown is 30° counterclockwise: the grip turns from (102, 100) to there. + set_property(&mut d, r, "Angle1", "60").unwrap(); + assert!(props(&d, r).contains(&("Angle1".to_string(), "60".to_string())), "{:?}", props(&d, r)); + let at = grips(&d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap(); + let want = (100.0 + 2.0 * 30f64.to_radians().cos(), 100.0 + 2.0 * 30f64.to_radians().sin()); + assert!(near(at, want), "{at:?} vs {want:?}"); +} + +#[test] +fn an_angle_by_increments_marks_its_stops_round_the_circle() { + // Angle1 by 90° from 0 to a full turn: its grip stops at four points round the base, the + // full turn being no turn; the way it travels there is round the circle. + let src = include_str!("../data/dynblock_symbol.txt") + .replace("\r\n", "\n") + .replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n"); + let (d, r) = symbol_from(&src); + let stops = grip_stops(&d, r, 15, GripPart::End); + let at: Vec = stops.iter().map(|(p, _)| *p).collect(); + assert_eq!(at.len(), 4, "{at:?}"); + for (p, want) in at.iter().zip([(102.0, 100.0), (100.0, 102.0), (98.0, 100.0), (100.0, 98.0)]) { + assert!(near(*p, want), "{p:?} vs {want:?}"); + } + for (p, way) in &stops { + assert!((*p - Vec2::new(100.0, 100.0)).dot(*way).abs() < 1e-9, "across the radius"); + } + // The block as it comes (any angle) marks nothing; nor does a flip grip. + let (d, r) = symbol(); + assert!(grip_stops(&d, r, 15, GripPart::End).is_empty()); + assert!(grip_stops(&d, r, 20, GripPart::Base).is_empty()); +} + +#[test] +fn an_angle_s_stops_follow_a_grip_off_the_radius() { + // The grip object a quarter turn round and 90° increments: each stop is where the grip is + // at that angle, the first (0) where it is now. + let src = include_str!("../data/dynblock_symbol.txt") + .replace("\r\n", "\n") + .replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n") + .replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n"); + let (d, r) = symbol_from(&src); + let at: Vec = grip_stops(&d, r, 15, GripPart::End).into_iter().map(|(p, _)| p).collect(); + assert_eq!(at.len(), 4, "{at:?}"); + for (p, want) in at.iter().zip([(100.0, 102.0), (98.0, 100.0), (100.0, 98.0), (102.0, 100.0)]) { + assert!(near(*p, want), "{p:?} vs {want:?}"); + } +} + +#[test] +fn bad_angles_and_states_change_nothing() { + let (mut d, r) = symbol(); + let before = d.clone(); + for (name, value) in [("Angle1", "steep"), ("Angle1", "inf"), ("Flip state1", "Sideways"), ("Flip state1", "2")] { + assert!(set_property(&mut d, r, name, value).is_err(), "{name}={value}"); + } + assert_eq!(d, before); +} + +/// The saved value record of parameter `node` on the reference (the XRECORD its +/// `ACAD_ENHANCEDBLOCKDATA` entry names), as its index in the drawing's kept objects. +fn record(d: &Drawing, node: i32) -> usize { + let objects = &d.foreign.objects; + let after = |o: &cadcraft_doc::foreign::ForeignObject, key: &str| { + let i = o.tags.iter().position(|t| t.code == 3 && t.value == key)?; + Handle::parse_hex(&o.tags.get(i + 1)?.value) + }; + let cache = objects.iter().find_map(|o| after(o, "ACAD_ENHANCEDBLOCKDATA")).unwrap(); + let dict = objects.iter().find(|o| o.handle == cache).unwrap(); + let h = after(dict, &node.to_string()).unwrap(); + objects.iter().position(|o| o.handle == h).unwrap() +} + +#[test] +fn a_value_record_takes_its_shape_from_its_parameter() { + let (mut d, r) = symbol(); + set_property(&mut d, r, "Angle1", "30").unwrap(); + set_property(&mut d, r, "Flip state1", "Flipped").unwrap(); + let mut again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + // A stray group 70 after the rotation's points, and a flip record without its state. + let rot = record(&again, 15); + std::sync::Arc::make_mut(&mut again.foreign).objects[rot].tags.push(RawTag { code: 70, value: "1".into() }); + let flip = record(&again, 20); + let tags = &mut std::sync::Arc::make_mut(&mut again.foreign).objects[flip].tags; + let last70 = tags.iter().rposition(|t| t.code == 70).unwrap(); + tags.remove(last70); + let values = reference(&again, r).unwrap().values; + assert!(matches!(values.get(&15), Some(Value::Points { .. })), "{:?}", values.get(&15)); + assert!(matches!(values.get(&20), Some(Value::Flip { flipped: false, .. })), "{:?}", values.get(&20)); + assert_eq!(props(&again, r)[..2], pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped")])); +} + +#[test] +fn a_flip_selection_that_repeats_its_objects_mirrors_them_once() { + // The flip action's selection lists the line, the circle and Position1 twice: each is mirrored + // once, as with the selection listing them once (twice would mirror them back). + let src = include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n"); + let once = "71 3\n330 31\n330 32\n330 68\n1010 -6"; + assert_eq!(src.matches(once).count(), 1); + let (mut twice, r) = symbol_from(&src.replace(once, "71 6\n330 31\n330 32\n330 68\n330 31\n330 32\n330 68\n1010 -6")); + let (mut plain, _) = symbol(); + for d in [&mut twice, &mut plain] { + set_property(d, r, "Flip state1", "Flipped").unwrap(); + } + let ((l1, a1, r1), (l2, a2, r2)) = (shown(&twice, r), shown(&plain, r)); + assert!(near(l1, (l2.x, l2.y)) && near(a1, (a2.x, a2.y)) && (r1 - r2).abs() < 1e-9, "{l1:?} {l2:?}"); + assert_eq!(props(&twice, r), props(&plain, r)); +} diff --git a/crates/io/tests/it/dynblock_scale_polar.rs b/crates/io/tests/it/dynblock_scale_polar.rs new file mode 100644 index 000000000..69f745fd3 --- /dev/null +++ b/crates/io/tests/it/dynblock_scale_polar.rs @@ -0,0 +1,214 @@ +//! Scale and polar stretch actions of dynamic blocks, as AutoCAD applies them: a scale action +//! scales its objects about its base point by how much the distance it follows grew (a 2×2 square +//! scaled by a distance going from 2 to 4 is 4×4); a polar stretch turns its objects about the +//! polar parameter's base by the change of its angle and moves the vertices in its frame (and the +//! objects it doesn't stretch) with the end, while its rotate-only objects just turn. Both carry +//! the parameters in their selection, and the results survive a save. +//! +//! The fixture is synthetic: block Grow (a 2×2 square and a circle at (1, 1), Distance1 from the +//! origin to (2, 0), scaled about the distance's base; Position1 at (2, 2) is in the selection), +//! Pinned (the square, scaled about the fixed point (2, 2)) and Sheet (the square, scaled by the +//! diagonal of X Distance1 and Y Distance1, from the origin to (2, 2), as AutoCAD scales by an XY +//! parameter); Tag (a line from (1, 0) to (4, 0), a circle at its end and one at (2, 2), a polar +//! Distance1/Angle1 from the origin to (4, 0); the polar stretch's frame holds the line's end and +//! Position1 at (4, 1); the circle at (2, 2) only turns). + +use cadcraft_doc::dynblock::{ActionKind, custom_properties, dynamic_block, set_property}; +use cadcraft_doc::geom::Vec3; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// The fixture with a reference to `block` at (100, 100). +fn reference(block: &str) -> (Drawing, Handle) { + let mut d = read_dxf(dxf(&include_str!("../data/dynblock_scale_polar.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: block.into(), + insert: Vec3::new(100.0, 100.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +/// Each object of the reference's block, in block coordinates: a polyline's corners (lowest and +/// highest), a circle's centre and radius, a line's ends. +fn shapes(d: &Drawing, r: Handle) -> Vec<[f64; 4]> { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let round = |v: f64| (v * 1000.0).round() / 1000.0 + 0.0; + d.block(&i.block) + .unwrap() + .entities + .iter() + .map(|e| match &e.kind { + EntityKind::LwPolyline(p) => { + let xs = p.vertices.iter().map(|v| v.p.x); + let ys = p.vertices.iter().map(|v| v.p.y); + [ + round(xs.clone().fold(f64::MAX, f64::min)), + round(ys.clone().fold(f64::MAX, f64::min)), + round(xs.fold(f64::MIN, f64::max)), + round(ys.fold(f64::MIN, f64::max)), + ] + } + EntityKind::Circle(c) => [round(c.center.x), round(c.center.y), round(c.radius), 0.0], + EntityKind::Line(l) => [round(l.a.x), round(l.a.y), round(l.b.x), round(l.b.y)], + k => panic!("unexpected {k:?}"), + }) + .collect() +} + +#[test] +fn reads_the_scale_actions_base_and_connections() { + let (d, _) = reference("Grow"); + let m = dynamic_block(&d, "Grow").unwrap(); + let a = m.actions.iter().find(|a| matches!(a.kind, ActionKind::Scale { .. })).unwrap(); + let ActionKind::Scale { base } = a.kind else { unreachable!() }; + assert!(base.dependent); + let names: Vec<&str> = a.connections.iter().map(|(_, c)| c.as_str()).collect(); + assert_eq!(names, ["UpdatedBaseX", "UpdatedBaseY", "Scale", "XScale", "YScale"]); + let m = dynamic_block(&d, "Pinned").unwrap(); + let ActionKind::Scale { base } = m.actions[0].kind else { panic!("a scale action") }; + assert!(!base.dependent); + assert_eq!((base.at.x, base.at.y), (2.0, 2.0)); +} + +#[test] +fn a_distance_scales_its_objects_about_the_base() { + let (mut d, r) = reference("Grow"); + set_property(&mut d, r, "Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 4.0], [2.0, 2.0, 1.0, 0.0]]); + // The point parameter in the selection is scaled with them. + let p = props(&d, r); + assert!(p.contains(&("Position1 X".into(), "4.0000".into())), "{p:?}"); + assert!(p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}"); + // From there, by the ratio of the new distance to the one it has now. + set_property(&mut d, r, "Distance1", "1").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.0, 1.0], [0.5, 0.5, 0.25, 0.0]]); +} + +#[test] +fn a_fixed_base_point_stays() { + let (mut d, r) = reference("Pinned"); + set_property(&mut d, r, "Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[-2.0, -2.0, 2.0, 2.0]]); +} + +#[test] +fn an_xy_parameter_scales_by_its_diagonal() { + let (mut d, r) = reference("Sheet"); + // From (2, 2) to (4, 2): the diagonal grows from √8 to √20. + set_property(&mut d, r, "X Distance1", "4").unwrap(); + let s = (20.0f64 / 8.0).sqrt() * 2.0; + let round = |v: f64| (v * 1000.0).round() / 1000.0; + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, round(s), round(s)]]); + // A distance of 0 along one axis still leaves a diagonal: 4 long, twice the square's √8 / 2. + set_property(&mut d, r, "Y Distance1", "0").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.828, 2.828]]); +} + +#[test] +fn scaled_objects_and_values_survive_a_save() { + let (mut d, r) = reference("Grow"); + set_property(&mut d, r, "Distance1", "3").unwrap(); + let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&back, r), props(&d, r)); + assert_eq!(shapes(&back, r), shapes(&d, r)); + set_property(&mut back, r, "Distance1", "6").unwrap(); + assert_eq!(shapes(&back, r), vec![[0.0, 0.0, 6.0, 6.0], [3.0, 3.0, 1.5, 0.0]]); +} + +#[test] +fn hostile_scales_are_refused_and_change_nothing() { + let (mut d, r) = reference("Grow"); + for v in ["0", "-3", "NaN", "inf", "1e-300", "1e200"] { + assert!(set_property(&mut d, r, "Distance1", v).is_err(), "{v}"); + } + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.0, 2.0], [1.0, 1.0, 0.5, 0.0]]); + // A large factor within the limit is a large block. + set_property(&mut d, r, "Distance1", "2e6").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2e6, 2e6], [1e6, 1e6, 5e5, 0.0]]); + // Both XY distances 0 would scale the objects to nothing; from there no ratio is known. + let (mut d, r) = reference("Sheet"); + set_property(&mut d, r, "X Distance1", "0").unwrap(); + assert!(set_property(&mut d, r, "Y Distance1", "0").is_err()); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.414, 1.414]]); +} + +#[test] +fn reads_the_polar_stretch_action() { + let (d, _) = reference("Tag"); + let m = dynamic_block(&d, "Tag").unwrap(); + let ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, .. } = &m.actions[0].kind else { panic!("a polar stretch") }; + assert_eq!(frame.len(), 2); + assert_eq!(vertices, &vec![(Handle(0xB0), vec![1])]); + assert_eq!(rotate_only, &vec![Handle(0xB2)]); + assert_eq!(*multiplier, 1.0); + assert_eq!(m.actions[0].connections.len(), 6); +} + +#[test] +fn a_polar_distance_stretches_the_frame_along_it() { + let (mut d, r) = reference("Tag"); + set_property(&mut d, r, "Distance1", "6").unwrap(); + // The line's end and the head follow the end; the rotate-only circle stays. + assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 6.0, 0.0], [6.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]); + let p = props(&d, r); + assert!(p.contains(&("Position1 X".into(), "6.0000".into())), "{p:?}"); +} + +#[test] +fn a_polar_angle_turns_everything_about_the_base() { + let (mut d, r) = reference("Tag"); + set_property(&mut d, r, "Angle1", "90").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 4.0], [0.0, 4.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]); + let p = props(&d, r); + assert!(p.contains(&("Position1 X".into(), "-1.0000".into())) && p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}"); + // Then a distance along the new direction, and back to the start. + set_property(&mut d, r, "Distance1", "6").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 6.0], [0.0, 6.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]); + set_property(&mut d, r, "Angle1", "0").unwrap(); + set_property(&mut d, r, "Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]); +} + +#[test] +fn polar_stretched_objects_survive_a_save() { + let (mut d, r) = reference("Tag"); + set_property(&mut d, r, "Angle1", "90").unwrap(); + let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&back, r), props(&d, r)); + assert_eq!(shapes(&back, r), shapes(&d, r)); + set_property(&mut back, r, "Distance1", "2").unwrap(); + assert_eq!(shapes(&back, r), vec![[0.0, 1.0, 0.0, 2.0], [0.0, 2.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]); +} + +#[test] +fn hostile_polar_values_are_refused() { + let (mut d, r) = reference("Tag"); + for (n, v) in [("Distance1", "0"), ("Distance1", "NaN"), ("Distance1", "-inf"), ("Angle1", "nan"), ("Angle1", "1e400")] { + assert!(set_property(&mut d, r, n, v).is_err(), "{n} {v}"); + } + assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]); +} diff --git a/crates/io/tests/it/entity_props_roundtrip.rs b/crates/io/tests/it/entity_props_roundtrip.rs index 189a66d79..27f41a5b2 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -118,7 +118,7 @@ fn hatch(pattern: &str, gradient: Option) -> Hatch { Hatch { pattern: pattern.into(), solid: pattern == "SOLID", - loops: vec![HatchLoop { vertices: square(10.0), outer: true, sources: Vec::new() }], + loops: vec![HatchLoop { vertices: square(10.0), outer: true, boundary_flags: None, sources: Vec::new() }], scale: 2.0, angle: 0.25, associative: false, diff --git a/crates/io/tests/it/hatch_assoc_roundtrip.rs b/crates/io/tests/it/hatch_assoc_roundtrip.rs index f31942e78..e75b150df 100644 --- a/crates/io/tests/it/hatch_assoc_roundtrip.rs +++ b/crates/io/tests/it/hatch_assoc_roundtrip.rs @@ -41,8 +41,8 @@ fn source_boundary_objects_roundtrip() { let outer = poly(&mut d, square(0.0, 20.0)); let island = poly(&mut d, square(5.0, 5.0)); let loops = vec![ - HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] }, - HatchLoop { vertices: square(5.0, 5.0), outer: false, sources: vec![island] }, + HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] }, + HatchLoop { vertices: square(5.0, 5.0), outer: false, boundary_flags: None, sources: vec![island] }, ]; d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops.clone(), true))).expect("add"); // A non-associative hatch writes no sources; a source that is gone isn't written. @@ -79,7 +79,7 @@ fn join(p: &[(i32, String)]) -> String { fn sources_after_spline_fit_data_and_hostile_counts() { let mut d = Drawing::new_imperial(); let outer = poly(&mut d, square(0.0, 20.0)); - let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] }]; + let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] }]; d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops, true))).expect("add"); let p = pairs(&write_dxf(&d)); let start = p.iter().position(|(c, v)| *c == 0 && v == "HATCH").expect("HATCH"); @@ -127,11 +127,11 @@ fn a_hatch_in_a_block_keeps_its_boundary_and_the_boundary_its_reactor() { let fill = d.new_handle(); let k = EntityKind::LwPolyline(LwPolyline { vertices: square(0.0, 10.0), closed: true, const_width: 0.0, elevation: 0.0, plinegen: false }); b.entities.push(Entity::new(outline, k)); - let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }]; + let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }]; b.entities.push(Entity::new(fill, EntityKind::Hatch(hatch(loops, true)))); d.blocks.insert("Tag".into(), std::sync::Arc::new(b)); // A model-space hatch whose source is in the block is not linked to it. - let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }]; + let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }]; let other = d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(stray, true))).expect("add"); let p = pairs(&write_dxf(&d)); let poly = record(&p, "LWPOLYLINE", outline); diff --git a/crates/io/tests/it/hatch_elliptic_edge_dedup.rs b/crates/io/tests/it/hatch_elliptic_edge_dedup.rs new file mode 100644 index 000000000..0c595377b --- /dev/null +++ b/crates/io/tests/it/hatch_elliptic_edge_dedup.rs @@ -0,0 +1,65 @@ +//! An elliptic HATCH boundary edge that meets the previous edge at its start point must not emit +//! that shared vertex twice, in either traversal direction (CCW or CW). Otherwise the resulting +//! polyline boundary contains consecutive duplicate vertices. + +use cadcraft_doc::EntityKind; + +fn dxf_hatch_with_elliptic_edge(ccw: bool) -> String { + // Closed D-shaped boundary: + // - CCW: line (0,0)->(10,0), elliptic quarter-arc (10,0)->(0,5) (0..90 deg), line (0,5)->(0,0) + // - CW: line (0,0)->(0,5), elliptic quarter-arc (0,5)->(10,0) (270..360 deg CW, i.e. 0..90 reversed), line (10,0)->(0,0) + let (e1, ell, e3) = if ccw { + ( + "72\n1\n10\n0.0\n20\n0.0\n11\n10.0\n21\n0.0\n", + "72\n3\n10\n0.0\n20\n0.0\n11\n10.0\n21\n0.0\n40\n0.5\n50\n0.0\n51\n90.0\n73\n1\n", + "72\n1\n10\n0.0\n20\n5.0\n11\n0.0\n21\n0.0\n", + ) + } else { + ( + "72\n1\n10\n0.0\n20\n0.0\n11\n0.0\n21\n5.0\n", + "72\n3\n10\n0.0\n20\n0.0\n11\n10.0\n21\n0.0\n40\n0.5\n50\n270.0\n51\n360.0\n73\n0\n", + "72\n1\n10\n10.0\n20\n0.0\n11\n0.0\n21\n0.0\n", + ) + }; + format!( + "0\nSECTION\n2\nENTITIES\n\ + 0\nHATCH\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n\ + 10\n0.0\n20\n0.0\n30\n0.0\n210\n0.0\n220\n0.0\n230\n1.0\n\ + 2\nSOLID\n70\n1\n71\n0\n\ + 91\n1\n92\n1\n93\n3\n{e1}{ell}{e3}97\n0\n\ + 75\n0\n76\n1\n98\n0\n\ + 0\nENDSEC\n0\nEOF\n" + ) +} + +fn assert_no_consecutive_duplicate_vertices(dxf: &str) { + let doc = cadcraft_io::read(dxf.as_bytes(), "elliptic.dxf").expect("read DXF"); + let EntityKind::Hatch(h) = &doc.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).expect("hatch").kind else { + panic!("expected hatch"); + }; + assert_eq!(h.loops.len(), 1); + let verts = &h.loops[0].vertices; + assert!(verts.len() >= 4, "expected tessellated loop, got {} vertices", verts.len()); + for i in 0..verts.len() { + let a = verts[i].p; + let b = verts[(i + 1) % verts.len()].p; + assert!(!a.near(b, 1e-9), "duplicate consecutive vertices at index {i}: {a:?} and {b:?}"); + } +} + +#[test] +fn ccw_elliptic_edge_does_not_duplicate_shared_start_vertex() { + let dxf = dxf_hatch_with_elliptic_edge(true); + assert_no_consecutive_duplicate_vertices(&dxf); + + // Round-trip through DXF write -> read keeps the polyline boundary free of duplicate vertices. + let doc = cadcraft_io::read(dxf.as_bytes(), "elliptic.dxf").unwrap(); + let saved = cadcraft_io::write_dxf(&doc); + assert_no_consecutive_duplicate_vertices(&saved); +} + +#[test] +fn cw_elliptic_edge_does_not_duplicate_shared_start_vertex() { + let dxf = dxf_hatch_with_elliptic_edge(false); + assert_no_consecutive_duplicate_vertices(&dxf); +} diff --git a/crates/io/tests/it/hatch_loop_flags.rs b/crates/io/tests/it/hatch_loop_flags.rs new file mode 100644 index 000000000..71e8e8cf3 --- /dev/null +++ b/crates/io/tests/it/hatch_loop_flags.rs @@ -0,0 +1,145 @@ +use cadcraft_doc::{Drawing, EntityKind, HatchLoop, Region}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn boundary(points: &[(f64, f64)], flags: i64) -> String { + let mut text = format!("92\n{flags}\n"); + if flags & 2 != 0 { + text.push_str(&format!("72\n0\n73\n1\n93\n{}\n", points.len())); + for (point_x, point_y) in points { + text.push_str(&format!("10\n{point_x}\n20\n{point_y}\n")); + } + } else { + text.push_str(&format!("93\n{}\n", points.len())); + for (start, end) in points.iter().zip(points.iter().cycle().skip(1)) { + text.push_str(&format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", start.0, start.1, end.0, end.1)); + } + } + text.push_str("97\n0\n"); + text +} + +fn logo(flags: [i64; 4]) -> String { + let hexagon = [(-10.0, 0.0), (-5.0, -8.0), (5.0, -8.0), (10.0, 0.0), (5.0, 8.0), (-5.0, 8.0)]; + let letter = [(-3.0, -4.0), (3.0, -4.0), (3.0, -2.0), (-1.0, -2.0), (-1.0, 4.0), (-3.0, 4.0)]; + let right: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x + 28.0, *point_y)).collect(); + let hole: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x * 0.6 + 28.0, point_y * 0.6)).collect(); + let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"); + for (index, loops) in + [[(&hexagon[..], flags[0]), (&letter[..], flags[1])], [(&right[..], flags[2]), (&hole[..], flags[3])]].into_iter().enumerate() + { + text.push_str(&format!( + "0\nHATCH\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n91\n2\n", + 0x100 + index + )); + for (points, flags) in loops { + text.push_str(&boundary(points, flags)); + } + text.push_str("75\n1\n76\n1\n98\n0\n"); + } + text.push_str("0\nENDSEC\n0\nEOF\n"); + text +} + +fn flags_written(drawing: &Drawing) -> Vec { + let text = write_dxf(drawing); + let lines: Vec<_> = text.lines().collect(); + let mut hatch = false; + lines + .as_chunks::<2>() + .0 + .iter() + .filter_map(|pair| { + let code: i32 = pair[0].trim().parse().unwrap(); + if code == 0 { + hatch = pair[1].trim() == "HATCH"; + } + if hatch && code == 92 { Some(pair[1].trim().parse().unwrap()) } else { None } + }) + .collect() +} + +#[test] +fn boundary_flags_survive_dxf_open_and_save() { + for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] { + let drawing = read_dxf(logo(flags).as_bytes()).unwrap(); + let expected = flags.map(|flag| flag | 2); + assert_eq!(flags_written(&drawing), expected); + let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap(); + assert_eq!(flags_written(&back), expected); + for entity in back.model.iter() { + if let EntityKind::Hatch(hatch) = &entity.kind { + let json = serde_json::to_vec(&hatch.loops).unwrap(); + let restored: Vec = serde_json::from_slice(&json).unwrap(); + assert_eq!(restored, hatch.loops); + } + } + } +} + +#[test] +fn reclassified_loops_write_current_external_bit() { + for imported in [7, 23] { + let mut drawing = read_dxf(logo([7, imported, 7, 6]).as_bytes()).unwrap(); + let handle = drawing.model.iter().next().unwrap().handle; + drawing.model.modify(handle, |entity| { + let EntityKind::Hatch(hatch) = &mut entity.kind else { panic!("expected hatch") }; + assert!(hatch.loops[1].outer); + let mut region = Region { loops: hatch.loops.clone() }; + assert!(region.renest()); + hatch.loops = region.loops; + assert!(!hatch.loops[1].outer); + assert_eq!(hatch.loops[1].boundary_flags, Some(imported)); + }); + let written = flags_written(&drawing)[1]; + assert_eq!(written & 1, 0); + assert_eq!(written & (4 | 16), imported & (4 | 16)); + assert_ne!(written & 2, 0); + let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap(); + assert_eq!(flags_written(&back), flags_written(&drawing)); + } +} + +#[test] +fn undocumented_boundary_bits_are_not_written_back() { + let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22]; + let drawing = read_dxf(logo(flags).as_bytes()).unwrap(); + let expected = flags.map(|flag| (flag & 31) | 2); + assert_eq!(flags_written(&drawing), expected); + let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap(); + assert_eq!(flags_written(&back), expected); +} + +#[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn boundary_flags_survive_dwg_open_and_both_save_formats() { + cadcraft_io::dwg_worker::allow_in_process(); + for flags in [[7, 22, 7, 6], [7, 22, 6, 20]] { + let drawing = read_dxf(logo(flags).as_bytes()).unwrap(); + let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap(); + let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap(); + let expected = flags.map(|flag| flag | 2); + assert_eq!(flags_written(&back), expected); + let again = cadcraft_io::write(&back, "logo.dwg").unwrap(); + assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected); + } +} + +#[test] +fn old_serialized_loops_keep_locally_created_flags() { + let mut drawing = read_dxf(logo([7, 22, 6, 20]).as_bytes()).unwrap(); + let mut expected = Vec::new(); + let handles: Vec<_> = drawing.model.iter().map(|entity| entity.handle).collect(); + for handle in handles { + drawing.model.modify(handle, |entity| { + if let EntityKind::Hatch(hatch) = &mut entity.kind { + for boundary in &mut hatch.loops { + let mut json = serde_json::to_value(&*boundary).unwrap(); + json.as_object_mut().unwrap().remove("boundary_flags"); + *boundary = serde_json::from_value::(json).unwrap(); + expected.push(2 | i64::from(boundary.outer)); + } + } + }); + } + assert_eq!(flags_written(&drawing), expected); +} diff --git a/crates/io/tests/it/hatch_pattern_def.rs b/crates/io/tests/it/hatch_pattern_def.rs index 6d2502c56..98add4dd6 100644 --- a/crates/io/tests/it/hatch_pattern_def.rs +++ b/crates/io/tests/it/hatch_pattern_def.rs @@ -8,7 +8,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn square() -> HatchLoop { let v = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(); - HatchLoop { vertices: v, outer: true, sources: Vec::new() } + HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() } } fn hatch(pattern: &str, scale: f64, angle: f64, origin: Vec2, lines: Vec) -> Hatch { diff --git a/crates/io/tests/it/large_radial_dimension.rs b/crates/io/tests/it/large_radial_dimension.rs new file mode 100644 index 000000000..44e7fd3c8 --- /dev/null +++ b/crates/io/tests/it/large_radial_dimension.rs @@ -0,0 +1,355 @@ +//! A dimension CADCraft keeps as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` +//! block, as AutoCAD does, else the proxy graphics in its AcDbEntity part (#3438); saving keeps +//! the block, which AutoCAD needs to read the dimension (#1161). + +use cadcraft_doc::{EntityKind, Space}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn chunk(kind: u32, data: &[u8]) -> Vec { + let mut d = data.to_vec(); + d.resize(d.len().div_ceil(4) * 4, 0); + let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec(); + out.extend(kind.to_le_bytes()); + out.extend(d); + out +} + +fn v3(x: f64, y: f64, z: f64) -> Vec { + [x, y, z].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// POLYLINE_WITH_NORMAL: the count, the points and the normal. +fn line_with_normal(a: (f64, f64), b: (f64, f64)) -> Vec { + let mut d = 2u32.to_le_bytes().to_vec(); + d.extend(v3(a.0, a.1, 0.0)); + d.extend(v3(b.0, b.1, 0.0)); + d.extend(v3(0.0, 0.0, 1.0)); + chunk(32, &d) +} + +/// An ARC of radius 500 and a LARGE_RADIAL_DIMENSION on it whose proxy graphics are its jogged +/// leader and the text "R500" (TEXT2), as in the issue's example; `block: true` adds its `*D1` +/// block, which also holds the arrowhead (a SOLID), as an exporter's picture may not. +fn file(block: bool) -> String { + let mut text = v3(255.0, 245.0, 0.0); + text.extend(v3(0.0, 0.0, 1.0)); + text.extend(v3(1.0, 0.0, 0.0)); + text.extend(b"R500\0\0\0\0"); + text.extend(4i32.to_le_bytes()); + text.extend(0i32.to_le_bytes()); + for v in [15.0f64, 1.0, 0.0, 0.0] { + text.extend(v.to_le_bytes()); + } + text.extend([0u8; 20]); + text.extend(b"txt\0\0\0\0\0"); + let chunks = [ + line_with_normal((250.0, 150.0), (290.0, 190.0)), + line_with_normal((290.0, 190.0), (300.0, 230.0)), + line_with_normal((300.0, 230.0), (353.553, 353.553)), + chunk(11, &text), + ]; + let body = chunks.concat(); + let mut g = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + g.extend((chunks.len() as u32).to_le_bytes()); + g.extend(body); + let mut t: Vec<(i32, String)> = Vec::new(); + if block { + for (c, v) in [ + (0, "SECTION"), + (2, "BLOCKS"), + (0, "BLOCK"), + (8, "0"), + (2, "*D1"), + (70, "1"), + (10, "0"), + (20, "0"), + (3, "*D1"), + (0, "SOLID"), + (8, "0"), + (10, "353.553"), + (20, "353.553"), + (11, "335"), + (21, "345"), + (12, "345"), + (22, "335"), + (13, "345"), + (23, "335"), + (0, "LINE"), + (8, "0"), + (10, "250"), + (20, "150"), + (11, "353.553"), + (21, "353.553"), + (0, "TEXT"), + (8, "0"), + (10, "255"), + (20, "245"), + (40, "15"), + (1, "R500"), + (0, "ENDBLK"), + (0, "ENDSEC"), + ] { + t.push((c, v.into())); + } + } + for (c, v) in [(0, "SECTION"), (2, "ENTITIES"), (0, "ARC"), (5, "40"), (8, "0"), (10, "0"), (20, "0"), (40, "500"), (50, "20"), (51, "70")] { + t.push((c, v.into())); + } + for (c, v) in [(0, "LARGE_RADIAL_DIMENSION"), (5, "41"), (100, "AcDbEntity"), (8, "0")] { + t.push((c, v.into())); + } + t.push((92, g.len().to_string())); + t.extend(g.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect()))); + for (c, v) in [ + (100, "AcDbDimension"), + (2, "*D1"), + (10, "353.553"), + (20, "353.553"), + (70, "9"), + (100, "AcDbRadialDimensionLarge"), + (13, "250"), + (23, "150"), + (14, "295"), + (24, "210"), + (15, "353.553"), + (25, "353.553"), + (40, "0.785398"), + (0, "ENDSEC"), + (0, "EOF"), + ] { + t.push((c, v.into())); + } + t.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +fn graphics_kinds(d: &cadcraft_doc::Drawing) -> Vec { + d.model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Unknown(u) if u.dxf_type == "LARGE_RADIAL_DIMENSION" => { + Some(u.graphics.iter().map(|g| g.kind.dxf_name().to_string()).collect()) + } + _ => None, + }) + .expect("kept as read") +} + +/// With its `*D` block the dimension draws the block (with the arrowhead), not its proxy +/// graphics, and saving keeps the block. +#[test] +fn a_kept_dimension_draws_its_block_and_saving_keeps_it() { + let d = read_dxf(file(true).as_bytes()).expect("read"); + // A reference to the block, which holds the arrowhead the proxy graphics lack. + assert_eq!(graphics_kinds(&d), ["INSERT"]); + // ByBlock throughout, so the block's ByBlock objects take the dimension's own. + let reference = d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) => u.graphics.first().map(|g| g.common.clone()), + _ => None, + }); + assert!( + reference.is_some_and(|c| c.transparency == cadcraft_doc::Transparency::ByBlock && c.plot_style == "ByBlock" && c.layer == "0"), + "the reference passes the dimension's traits on" + ); + let b = d.extents(&Space::Model); + assert!(b.max.x >= 353.0 && b.min.x <= 250.0, "{b:?}"); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert!(again.block("*D1").is_some_and(|b| b.entities.len() == 3)); + assert_eq!(graphics_kinds(&again), ["INSERT"]); +} + +/// The example from #1161: an ARC_DIMENSION and its `*D1` block survive a save. +#[test] +fn an_arc_length_dimensions_block_survives_a_save() { + let lines = [ + "0", + "SECTION", + "2", + "BLOCKS", + "0", + "BLOCK", + "8", + "0", + "2", + "*D1", + "70", + "1", + "10", + "0", + "20", + "0", + "30", + "0", + "3", + "*D1", + "0", + "LINE", + "8", + "0", + "10", + "320", + "20", + "150", + "11", + "330", + "21", + "175", + "0", + "ENDBLK", + "0", + "ENDSEC", + "0", + "SECTION", + "2", + "ENTITIES", + "0", + "ARC", + "8", + "0", + "10", + "300", + "20", + "150", + "40", + "20", + "50", + "0", + "51", + "90", + "0", + "ARC_DIMENSION", + "5", + "41", + "100", + "AcDbEntity", + "8", + "0", + "100", + "AcDbDimension", + "2", + "*D1", + "10", + "333.8", + "20", + "169.5", + "11", + "327.6", + "21", + "177.6", + "70", + "5", + "42", + "31.4159", + "100", + "AcDbArcDimension", + "13", + "320", + "23", + "150", + "14", + "300", + "24", + "170", + "15", + "300", + "25", + "150", + "40", + "0", + "41", + "1.5708", + "0", + "ENDSEC", + "0", + "EOF", + ]; + let d = read_dxf((lines.join("\n") + "\n").as_bytes()).expect("read"); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert!(again.block("*D1").is_some_and(|b| b.entities.len() == 1)); + // Drawn from the block: its line reaches (330, 175). + let b = again.extents(&Space::Model); + assert!(b.max.x >= 330.0 && b.max.y >= 175.0, "{b:?}"); +} + +/// A kept dimension: its record, naming block `block`, at handle `handle`. +fn kept_dim(handle: &str, block: &str) -> String { + format!( + "0\nARC_DIMENSION\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n{block}\n10\n0\n20\n0\n70\n5\n100\nAcDbArcDimension\n13\n0\n23\n0\n14\n1\n24\n0\n15\n0\n25\n0\n40\n0\n41\n1\n" + ) +} + +fn block(name: &str, body: &str) -> String { + format!("0\nBLOCK\n8\n0\n2\n{name}\n70\n1\n10\n0\n20\n0\n3\n{name}\n{body}0\nENDBLK\n") +} + +/// A dimension whose block holds another kept dimension draws through it: the inner one draws +/// its own block, here a line to (40, 30). +#[test] +fn a_dimension_inside_a_dimension_block_draws_too() { + let blocks = block("*D2", "0\nLINE\n8\n0\n10\n0\n20\n0\n11\n40\n21\n30\n") + &block("*D1", &kept_dim("51", "*D2")); + let text = format!("0\nSECTION\n2\nBLOCKS\n{blocks}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{}0\nENDSEC\n0\nEOF\n", kept_dim("50", "*D1")); + let d = read_dxf(text.as_bytes()).expect("read"); + let b = d.extents(&Space::Model); + assert!(b.max.x >= 40.0 && b.max.y >= 30.0, "{b:?}"); +} + +/// 25 blocks, each with two kept dimensions naming the one before: reading doesn't copy the +/// contents (2^25 lines), and measuring stays within the block depth limit. +#[test] +fn nested_dimension_blocks_are_not_multiplied() { + let mut blocks = block("*D0", "0\nLINE\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n"); + let mut h = 0x100; + for i in 1..25 { + let mut body = String::new(); + for _ in 0..2 { + body += &kept_dim(&format!("{h:X}"), &format!("*D{}", i - 1)); + h += 1; + } + blocks += &block(&format!("*D{i}"), &body); + } + let text = format!("0\nSECTION\n2\nBLOCKS\n{blocks}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{}0\nENDSEC\n0\nEOF\n", kept_dim("50", "*D24")); + let start = std::time::Instant::now(); + let d = read_dxf(text.as_bytes()).expect("read"); + let graphics: usize = d + .blocks + .values() + .flat_map(|b| b.entities.iter()) + .map(|e| match &e.kind { + EntityKind::Unknown(u) => u.graphics.len(), + _ => 0, + }) + .sum(); + assert_eq!(graphics, 48, "one reference per kept dimension"); + let _ = d.extents(&Space::Model); + assert!(start.elapsed().as_secs() < 10); +} + +/// Without a block it draws its proxy graphics. +#[test] +fn a_jogged_radius_dimension_draws_the_picture_it_was_saved_with() { + let d = read_dxf(file(false).as_bytes()).expect("read"); + let dim = d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) if u.dxf_type == "LARGE_RADIAL_DIMENSION" => Some(u.clone()), + _ => None, + }); + let dim = dim.expect("kept as read"); + let kinds: Vec<&str> = dim.graphics.iter().map(|g| g.kind.dxf_name()).collect(); + assert_eq!(kinds, ["LINE", "LINE", "LINE", "TEXT"]); + assert!(matches!(&dim.graphics[3].kind, EntityKind::Text(t) if t.value == "R500")); + // The extents reach the leader's start at (250, 150), inside the arc's own box. + let b = d.extents(&Space::Model); + assert!(b.min.x <= 250.0 && b.min.y <= 150.0, "{b:?}"); +} + +/// A `*D` block whose base point isn't the origin: its contents are in the dimension's +/// coordinates, so it draws where they are, as a DIMENSION's block does. +#[test] +fn a_dimension_block_with_a_base_point_draws_in_place() { + let dxf = "0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\n*D1\n70\n1\n10\n100\n20\n50\n3\n*D1\n0\nLINE\n8\n0\n10\n110\n20\n60\n11\n120\n21\n70\n0\nENDBLK\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLARGE_RADIAL_DIMENSION\n5\n41\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D1\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(dxf.as_bytes()).expect("read"); + let b = d.extents(&Space::Model); + assert!( + (b.min.x - 110.0).abs() < 1e-9 && (b.min.y - 60.0).abs() < 1e-9 && (b.max.x - 120.0).abs() < 1e-9 && (b.max.y - 70.0).abs() < 1e-9, + "{b:?}" + ); +} diff --git a/crates/io/tests/it/layout_plot_flags.rs b/crates/io/tests/it/layout_plot_flags.rs index 35d6cdeb9..09a678052 100644 --- a/crates/io/tests/it/layout_plot_flags.rs +++ b/crates/io/tests/it/layout_plot_flags.rs @@ -72,3 +72,41 @@ fn the_page_still_decides_the_bits_cadcraft_models() { d.layouts.last_mut().unwrap().page = PageSetup::default(); assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16)); } + +/// Each LAYOUT object's name and plot layout flags (the AcDbLayout group 1 and the +/// AcDbPlotSettings group 70) in DXF text. +fn layout_plot_flags(text: &str) -> Vec<(String, i64)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None); + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + match *code { + "0" => { + if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) { + out.push((n, f)); + } + (inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None); + } + "100" if inside => subclass = value, + "70" if inside && subclass == "AcDbPlotSettings" => flags = value.parse().ok(), + "1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()), + _ => {} + } + } + out +} + +#[test] +fn only_the_model_layout_carries_the_model_type_flag() { + // 1024 is "ModelType" (DXF Reference, PLOTSETTINGS group 70): the plot settings of model space. + // The Model layout carries it; a paper layout does not, even when it was read with it. + for read in [688, 688 | 1024] { + let bytes = write(&drawing(read), "sheet.dxf").unwrap(); + let layouts = layout_plot_flags(&String::from_utf8_lossy(&bytes)); + let flags = |name: &str| layouts.iter().find(|(n, _)| n == name).map(|&(_, f)| f); + let (model, sheet) = (flags("Model").unwrap(), flags("SHEET").unwrap()); + assert_ne!(model & 1024, 0, "Model, SHEET read with {read}: {layouts:?}"); + assert_eq!(sheet & 1024, 0, "SHEET read with {read}: {layouts:?}"); + } +} diff --git a/crates/io/tests/it/layout_plot_settings.rs b/crates/io/tests/it/layout_plot_settings.rs new file mode 100644 index 000000000..4d9ef4d1c --- /dev/null +++ b/crates/io/tests/it/layout_plot_settings.rs @@ -0,0 +1,343 @@ +//! Original synthetic plot subclasses covering the Autodesk DXF Reference's PLOTSETTINGS fields. + +use cadcraft_doc::{Drawing, NamedView}; +use cadcraft_io::{SaveOptions, Version, read, write, write_dxf, write_with}; +use std::collections::BTreeMap; + +fn normalized(text: &str) -> String { + let lines = text.lines().enumerate().map(|(index, line)| if index % 2 == 0 { line.trim() } else { line }).collect::>(); + lines.join("\n") + "\n" +} + +fn settings(seed: usize, plot_type: i64, flags: i64) -> String { + format!( + "1\nSetup {seed}\n2\nDraft-{seed}.pc3\n4\nSheet_{seed}_(11.00_x_17.00_Inches)\n6\nPlot view {seed}\n\ + 40\n2.1\n41\n3.2\n42\n4.3\n43\n5.4\n44\n279.4\n45\n431.8\n46\n7.5\n47\n8.5\n\ + 48\n-10\n49\n-20\n140\n300\n141\n400\n142\n1\n143\n3.56\n70\n{flags}\n72\n0\n\ + 73\n2\n74\n{plot_type}\n7\nDraft-{seed}.ctb\n75\n0\n76\n2\n77\n5\n78\n450\n\ + 147\n0.37\n148\n1.25\n149\n2.5\n333\nF00\n" + ) +} + +fn source(plot_type: i64, flags: i64) -> String { + let mut drawing = Drawing::new_imperial(); + for index in 1..=3 { + drawing.views.push(NamedView { + name: format!("Plot view {index}"), + height: 100.0, + width: 150.0, + layout: (index > 1).then(|| format!("Layout{}", index - 1)), + ..Default::default() + }); + } + let text = normalized(&write_dxf(&drawing)).replacen("AC1015", "AC1032", 1); + let mut result = String::new(); + for (index, part) in text.split("100\nAcDbPlotSettings\n").enumerate() { + if index == 0 { + result.push_str(part); + } else { + result.push_str("100\nAcDbPlotSettings\n"); + result.push_str(&settings(index, plot_type, flags)); + let (_, tail) = part.split_once("100\nAcDbLayout\n").unwrap(); + result.push_str("100\nAcDbLayout\n"); + result.push_str(tail); + } + } + result + .replacen("2\nCLASSES\n", "2\nCLASSES\n0\nCLASS\n1\nRENDERSETTINGS\n2\nAcDbRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n", 1) + .replacen( + "0\nENDSEC\n0\nEOF\n", + "0\nRENDERSETTINGS\n5\nF00\n330\n0\n100\nAcDbRenderSettings\n90\n2\n1\nDraft render\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n0\nENDSEC\n0\nEOF\n", + 1, + ) +} + +fn plots(text: &str) -> BTreeMap> { + normalized(text) + .split("100\nAcDbPlotSettings\n") + .skip(1) + .map(|part| { + let (plot, layout) = part.split_once("100\nAcDbLayout\n").unwrap(); + let name = layout.lines().nth(1).unwrap().to_string(); + let lines: Vec<_> = plot.lines().collect(); + let tags = lines.as_chunks::<2>().0.iter().map(|pair| (pair[0].trim().parse().unwrap(), pair[1].to_string())).collect(); + (name, tags) + }) + .collect() +} + +fn expected_plots(text: &str) -> BTreeMap> { + plots(text) + .into_iter() + .map(|(layout, mut tags)| { + let flags = tags[&70].parse::().unwrap(); + tags.insert(70, (if layout == "Model" { flags | 1024 } else { flags & !1024 }).to_string()); + tags.remove(&333); + (layout, tags) + }) + .collect() +} + +fn saved_plots(drawing: &Drawing) -> BTreeMap> { + plots(&String::from_utf8(write(drawing, "saved.dxf").unwrap()).unwrap()) +} + +fn assert_plot_eq(expected: &BTreeMap, actual: &BTreeMap, context: &str) { + let mut differences = Vec::new(); + for (code, value) in expected { + let Some(back) = actual.get(code) else { + differences.push(format!("missing group {code}")); + continue; + }; + let equal = if (40..=49).contains(code) || (140..=149).contains(code) { + (value.parse::().unwrap() - back.parse::().unwrap()).abs() < 1e-10 + } else if (70..=78).contains(code) { + value.trim().parse::().unwrap() == back.trim().parse::().unwrap() + } else { + value == back.trim() + }; + if !equal { + differences.push(format!("group {code}: {value:?} != {back:?}")); + } + } + assert!(differences.is_empty(), "{context}: {differences:?}"); +} + +#[test] +fn every_layout_keeps_all_plot_settings_in_dxf_and_dwg() { + cadcraft_io::dwg_worker::allow_in_process(); + for plot_type in [0, 3, 4] { + for flags in [11952, 11936] { + let source = source(plot_type, flags); + let expected = expected_plots(&source); + assert_eq!(expected.len(), 3); + assert!(expected.contains_key("Model")); + let drawing = read(source.as_bytes(), "source.dxf").unwrap(); + for name in ["saved.dxf", "saved.dwg"] { + let bytes = write(&drawing, name).unwrap(); + let text = if name.ends_with("dwg") { + String::from_utf8(craft_dwg::dwg_to_dxf(&bytes).unwrap()).unwrap() + } else { + String::from_utf8(bytes.clone()).unwrap() + }; + let actual = plots(&text); + assert_eq!(expected.keys().collect::>(), actual.keys().collect::>(), "{name}"); + for (layout, tags) in &expected { + assert_plot_eq(tags, &actual[layout], &format!("{name}: {layout}")); + } + let reopened = read(&bytes, name).unwrap(); + let again = saved_plots(&reopened); + for (layout, tags) in &expected { + assert_plot_eq(tags, &again[layout], &format!("reopened {name}: {layout}")); + } + } + } + } +} + +#[test] +fn changed_page_fields_override_only_their_saved_groups() { + cadcraft_io::dwg_worker::allow_in_process(); + let source = source(3, 11952).replace("72\n0\n", "72\n2\n"); + let expected = expected_plots(&source); + let mut drawing = read(source.as_bytes(), "source.dxf").unwrap(); + let pages = drawing.model_page.iter_mut().chain(drawing.layouts.iter_mut().map(|layout| &mut layout.page)); + for page in pages { + page.plot_area = "extents".into(); + page.scale = 0.5; + page.scale_to_fit = false; + page.plot_style_table = "Changed.ctb".into(); + page.paper_mm = Some(false); + } + for name in ["changed.dxf", "changed.dwg"] { + let reopened = read(&write(&drawing, name).unwrap(), name).unwrap(); + let actual = saved_plots(&reopened); + for (layout, original) in &expected { + let mut tags = original.clone(); + for (code, value) in [(74, "1"), (142, "0.5"), (143, "1"), (147, "0.5"), (70, "11936"), (75, "16"), (7, "Changed.ctb"), (72, "0")] { + tags.insert(code, value.into()); + } + if layout != "Model" { + tags.insert(70, (11936 & !1024).to_string()); + } + assert_plot_eq(&tags, &actual[layout], &format!("{name}: {layout}")); + } + } +} + +#[test] +fn changing_only_paper_or_device_keeps_other_plot_settings() { + cadcraft_io::dwg_worker::allow_in_process(); + let source = source(3, 11952); + let expected = expected_plots(&source); + for (code, value) in [(4, "Changed_paper"), (2, "Changed-device.pc3")] { + let mut drawing = read(source.as_bytes(), "source.dxf").unwrap(); + let pages = drawing.model_page.iter_mut().chain(drawing.layouts.iter_mut().map(|layout| &mut layout.page)); + for page in pages { + let mut edited = page.clone(); + if code == 4 { + edited.paper = value.into(); + } else { + edited.device = value.into(); + } + *page = edited; + } + for name in ["changed.dxf", "changed.dwg"] { + let bytes = write(&drawing, name).unwrap(); + let text = if name.ends_with("dwg") { + String::from_utf8(craft_dwg::dwg_to_dxf(&bytes).unwrap()).unwrap() + } else { + String::from_utf8(bytes.clone()).unwrap() + }; + let saved = plots(&text); + let reopened = read(&bytes, name).unwrap(); + let again = saved_plots(&reopened); + for (layout, original) in &expected { + let mut tags = original.clone(); + tags.insert(code, value.into()); + assert_plot_eq(&tags, &saved[layout], &format!("saved {name}: {layout}, changed group {code}")); + assert_plot_eq(&tags, &again[layout], &format!("reopened {name}: {layout}, changed group {code}")); + } + } + } +} + +#[test] +fn kept_model_type_is_corrected_with_and_without_page_edits() { + cadcraft_io::dwg_worker::allow_in_process(); + let source = source(0, 688); + let source = source.replacen(&settings(2, 0, 688), &settings(2, 0, 1712), 1); + let drawing = read(source.as_bytes(), "source.dxf").unwrap(); + for edited in [false, true] { + let mut drawing = drawing.clone(); + if edited { + for page in drawing.model_page.iter_mut().chain(drawing.layouts.iter_mut().map(|layout| &mut layout.page)) { + page.center = true; + } + } + for name in ["saved.dxf", "saved.dwg"] { + let bytes = write(&drawing, name).unwrap(); + let text = if name.ends_with("dwg") { craft_dwg::dwg_to_dxf(&bytes).unwrap() } else { bytes.clone() }; + let actual = plots(&String::from_utf8(text).unwrap()); + let centered = if edited { 4 } else { 0 }; + assert_eq!(actual["Model"][&70].trim().parse::().unwrap(), 1712 | centered, "{name}, edited {edited}"); + assert_eq!(actual["Layout1"][&70].trim().parse::().unwrap(), 688 | centered, "{name}, edited {edited}"); + let reopened = read(&bytes, name).unwrap(); + assert_eq!(reopened.model_page.as_ref().unwrap().file_plot_flags, Some(1712 | centered)); + assert_eq!(reopened.layouts.iter().find(|layout| layout.name == "Layout1").unwrap().page.file_plot_flags, Some(688 | centered)); + } + } +} + +#[test] +fn shade_plot_groups_follow_the_target_version_not_the_source() { + let source = source(0, 688); + let drawing = read(source.as_bytes(), "source.dxf").unwrap(); + for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] { + let bytes = write_with(&drawing, "saved.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let text = String::from_utf8(bytes).unwrap(); + for (layout, tags) in plots(&text) { + for code in [76, 77, 78] { + assert_eq!(tags.contains_key(&code), version >= Version::R2004, "{version:?}: {layout}, group {code}"); + } + assert!(!tags.contains_key(&333), "unwritten shade plot object: {version:?}: {layout}"); + } + for layout in normalized(&text).split("100\nAcDbLayout\n").skip(1) { + let lines = layout.lines().collect::>(); + assert!(lines.as_chunks::<2>().0.iter().take_while(|pair| pair[0] != "0").any(|pair| pair[0] == "76"), "layout UCS group: {version:?}"); + } + } +} + +#[test] +fn shade_plot_handle_names_a_written_object_or_is_omitted() { + cadcraft_io::dwg_worker::allow_in_process(); + let source = source(0, 688); + let root = source.split("2\nOBJECTS\n").nth(1).unwrap().split("0\nDICTIONARY\n5\n").nth(1).unwrap().lines().next().unwrap(); + let source = source.replacen("3\nACAD_GROUP\n", "3\nDraft render\n350\nF00\n3\nACAD_GROUP\n", 1).replacen( + "5\nF00\n330\n0\n", + &format!("5\nF00\n330\n{root}\n"), + 1, + ); + let drawing = read(source.as_bytes(), "source.dxf").unwrap(); + assert!(drawing.foreign.objects.iter().any(|object| object.kind == "RENDERSETTINGS")); + for keep_object in [true, false] { + let mut drawing = drawing.clone(); + if !keep_object { + std::sync::Arc::make_mut(&mut drawing.foreign).objects.retain(|object| object.kind != "RENDERSETTINGS"); + } + for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] { + for name in ["saved.dxf", "saved.dwg"] { + let bytes = write_with(&drawing, name, &SaveOptions { version: Some(version), binary: false }).unwrap(); + let text = if name.ends_with("dwg") { craft_dwg::dwg_to_dxf(&bytes).unwrap() } else { bytes }; + let text = normalized(&String::from_utf8(text).unwrap()); + let written = text.split("0\nRENDERSETTINGS\n5\n").nth(1).and_then(|part| part.lines().next()); + for (layout, tags) in plots(&text) { + if keep_object && version >= Version::R2007 { + assert_eq!(tags.get(&333).map(String::as_str), written, "{name}, {version:?}: {layout}"); + assert!(tags.contains_key(&333), "{name}, {version:?}: {layout}"); + } else { + assert!(!tags.contains_key(&333), "{name}, {version:?}: {layout}"); + } + } + } + } + } +} + +#[test] +fn inherited_paper_units_follow_measurement_when_saved_again() { + for (initial, changed, expected_unit) in [(1, 0, 25.4), (0, 1, 1.0)] { + let mut drawing = Drawing::new_imperial(); + drawing.header.set_i64("MEASUREMENT", initial); + let original = write_dxf(&drawing); + let original_plots = plots(&original); + assert!(original_plots.values().all(|tags| tags[&72] == initial.to_string())); + let mut loaded = read(original.as_bytes(), "original.dxf").unwrap(); + assert!(loaded.layouts.iter().all(|layout| layout.page.paper_mm.is_none())); + loaded.header.set_i64("MEASUREMENT", changed); + let saved = write_dxf(&loaded); + assert!(plots(&saved).values().all(|tags| tags[&72] == changed.to_string()), "saved plot units must follow MEASUREMENT"); + let reopened = read(saved.as_bytes(), "saved.dxf").unwrap(); + for layout in &reopened.layouts { + assert_eq!(layout.page.paper_mm, None); + assert_eq!(cadcraft_render::paper::page_unit_mm(&reopened, &layout.page), expected_unit); + } + } +} + +fn pixel_paper_units(edit: Option) { + cadcraft_io::dwg_worker::allow_in_process(); + let input = source(3, 11952).replace("72\n0\n", "72\n2\n"); + let mut drawing = read(input.as_bytes(), "source.dxf").unwrap(); + for page in drawing.model_page.iter_mut().chain(drawing.layouts.iter_mut().map(|layout| &mut layout.page)) { + assert_eq!(page.paper_mm, None); + match edit { + Some(false) => page.device = "Changed-device.pc3".into(), + Some(true) => page.paper_mm = Some(true), + None => {} + } + } + for name in ["saved.dxf", "saved.dwg"] { + let bytes = write(&drawing, name).unwrap(); + let text = if name.ends_with("dwg") { craft_dwg::dwg_to_dxf(&bytes).unwrap() } else { bytes }; + for (layout, tags) in plots(&String::from_utf8(text).unwrap()) { + assert_eq!(tags[&72].trim(), if edit == Some(true) { "1" } else { "2" }, "{name}: {layout}"); + } + } +} + +#[test] +fn pixel_units_survive_unchanged() { + pixel_paper_units(None); +} + +#[test] +fn pixel_units_survive_device_edit() { + pixel_paper_units(Some(false)); +} + +#[test] +fn pixel_units_follow_explicit_unit_edit() { + pixel_paper_units(Some(true)); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 3f31133b8..0f61901d5 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -5,6 +5,7 @@ mod angle_header; mod annotative_orientation; mod annotative_roundtrip; mod assoc_array_roundtrip; +mod assoc_dependency_prune; mod attdef_insert_dwg; mod attrib_modes; mod attrib_props; @@ -25,18 +26,27 @@ mod dwg_layout_owner; mod dwg_roundtrip_losses; mod dwt_template; mod dxf_versions; +mod dynblock_array; +mod dynblock_params; mod dynblock_read; +mod dynblock_rotate_flip; +mod dynblock_scale_polar; mod entity_props_roundtrip; mod exhausted_handseed; mod followups_626; mod groups_roundtrip; mod hatch_assoc_roundtrip; +mod hatch_elliptic_edge_dedup; +mod hatch_loop_flags; mod hatch_pattern_def; mod helix_roundtrip; +mod large_radial_dimension; mod layer_states_acad; mod layout_limits_roundtrip; mod layout_paper_units; mod layout_plot_flags; +#[cfg(not(target_arch = "wasm32"))] +mod layout_plot_settings; mod layout_plot_window; mod leader_vertex_elevation; #[cfg(not(target_arch = "wasm32"))] @@ -69,6 +79,8 @@ mod plot_model_png_scale; mod plot_styles; mod polyface_roundtrip; mod portable_fonts; +mod proxy_graphics; +mod proxy_layers; mod region_roundtrip; #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] mod render_settings_version; @@ -91,5 +103,7 @@ mod user_lin_pat_roundtrip; mod view_tables_roundtrip; mod view_target; mod viewport_clip_roundtrip; +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +mod visualstyle_dwg; mod xclip_roundtrip; mod xref_roundtrip; diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 44aa08270..7bb0bc8c7 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -168,6 +168,16 @@ fn rotated_text_keeps_its_angle() { assert!((t.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{t:?}"); } +#[test] +fn text_that_climbs_a_step_each_glyph_leaves_its_first_baseline() { + // Each glyph is 0.08 em above the one before: close enough to join it, but after a few the + // glyphs are well off the baseline the text is placed on. + let d = import("BT /F1 10 Tf 100 100 Td (A) Tj 0.8 Ts (B) Tj 1.6 Ts (C) Tj 2.4 Ts (D) Tj 3.2 Ts (E) Tj 4 Ts (F) Tj ET"); + assert_eq!(texts(&d).concat(), "ABCDEF"); + let rises: Vec = kinds(&d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.insert.y) } else { None }).collect(); + assert!(rises.len() > 1 && rises.windows(2).all(|w| w[1] > w[0]), "{:?}: {rises:?}", texts(&d)); +} + #[test] fn words_far_apart_on_a_line_are_separate_texts() { let d = import("BT /F1 10 Tf 50 100 Td (Left) Tj 400 0 Td (Right) Tj ET"); @@ -226,6 +236,17 @@ fn text_starting_on_a_clip_edge_is_kept() { assert_eq!(texts(&d), ["Z"]); } +#[test] +fn text_inside_a_clip_with_no_area_is_left_out() { + // A 1000 point 0 is 556 points wide, so its middle lies on x = 300, where the two clips touch. + let content = |clips: &str| format!("q {clips} BT /F1 1000 Tf 22 100 Td (0) Tj ET Q"); + let points = PdfImportOptions { unit: 1.0, ..Default::default() }; + let (d, _) = read(&page(&content("0 0 300 800 re W n")), &points).unwrap(); + assert_eq!(texts(&d), ["0"], "a glyph whose middle lies on the clip's edge is kept"); + let (d, _) = read(&page(&content("0 0 300 800 re W n 300 0 300 800 re W n")), &points).unwrap(); + assert!(texts(&d).is_empty(), "{:?}", texts(&d)); +} + #[test] fn a_shape_outside_its_clip_is_left_out() { let d = import("q 100 100 50 50 re W n 0 0 m 10 10 l S Q"); @@ -371,6 +392,24 @@ fn text_drawn_as_fill_and_stroke_is_one_text() { assert_eq!(texts, ["Hello"]); } +#[test] +fn text_drawn_as_fill_and_stroke_is_one_text_when_it_splits_into_runs() { + // The whole TJ is filled before it is stroked: fill Left, fill Right, stroke Left, stroke Right. + let d = import("BT /F1 12 Tf 50 100 Td 2 Tr [(Left) -30000 (Right)] TJ ET"); + assert_eq!(texts(&d), ["Left", "Right"]); + // Text that is only stroked is kept. + let d = import("BT /F1 12 Tf 50 100 Td 1 Tr [(Left) -30000 (Right)] TJ ET"); + assert_eq!(texts(&d), ["Left", "Right"]); +} + +#[test] +fn the_same_text_filled_again_in_another_colour_is_kept() { + // A black label, then the same label in red over it, with nothing drawn between. + let d = import("BT /F1 12 Tf 20 20 Td (Label) Tj ET 1 0 0 rg BT /F1 12 Tf 20 20 Td (Label) Tj ET"); + assert_eq!(texts(&d), ["Label", "Label"]); + assert_eq!(kinds(&d).last().map(|e| e.common.color), Some(Color::True(Rgb(255, 0, 0)))); +} + #[test] fn a_plot_of_a_drawing_imports_back_as_its_geometry() { let mut d = Drawing::new_metric(); @@ -519,6 +558,14 @@ fn a_path_that_doubles_back_along_an_edge_is_not_a_rectangular_clip() { assert!(line.b.x > 100.0 * MM_PER_PT, "the line was cut at the box: {line:?}"); } +#[test] +fn a_clip_of_separate_segments_is_empty_not_a_rectangle() { + // Two open segments reach the four corners of a box, but neither encloses any area. + let d = import("q 0 0 m 100 0 l 100 100 m 0 100 l W n 0 50 m 150 50 l S Q"); + assert!(kinds(&d).is_empty(), "{:?}", kinds(&d)); + assert!(!d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")), "{:?}", d.read_notes); +} + #[test] fn raster_only_pages_are_identified_without_fabricated_geometry() { let d = import("q 100 0 0 100 0 0 cm BI /W 1 /H 1 /CS /RGB /BPC 8 /F /AHx ID FF0000> EI Q"); diff --git a/crates/io/tests/it/proxy_graphics.rs b/crates/io/tests/it/proxy_graphics.rs new file mode 100644 index 000000000..653a0af69 --- /dev/null +++ b/crates/io/tests/it/proxy_graphics.rs @@ -0,0 +1,172 @@ +//! ACAD_PROXY_ENTITY draws its proxy graphics (#2646): read from DXF with the table indices of the +//! file, measured in the extents, and written back unchanged. + +use cadcraft_doc::color::Color; +use cadcraft_doc::{EntityKind, Space}; +use cadcraft_io::{read_dxf, write_dxf}; + +/// A proxy graphics chunk of type `kind`, its data padded to four bytes. +fn chunk(kind: u32, data: &[u8]) -> Vec { + let mut d = data.to_vec(); + d.resize(d.len().div_ceil(4) * 4, 0); + let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec(); + out.extend(kind.to_le_bytes()); + out.extend(d); + out +} + +/// A point in the XY plane as three doubles. +fn pt(x: f64, y: f64) -> Vec { + [x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// A balloon: layer 1 of the file's LAYER table, colour 1, a circle, a leader and the number. +fn balloon() -> Vec { + let mut circle = pt(175.0, 115.0); + circle.extend(6.0f64.to_le_bytes()); + circle.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + let mut leader = 2u32.to_le_bytes().to_vec(); + leader.extend(pt(170.8, 110.8)); + leader.extend(pt(150.0, 90.0)); + let mut text = pt(172.9, 112.0); + text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + text.extend(pt(1.0, 0.0)); + text.extend(b"1\0\0\0"); + text.extend(1i32.to_le_bytes()); + text.extend(0i32.to_le_bytes()); + for v in [6.0f64, 1.0, 0.0, 0.0] { + text.extend(v.to_le_bytes()); + } + text.extend([0u8; 20]); + text.extend(b"isocp.shx\0\0\0\0\0\0\0"); + let chunks = [chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text)]; + let body = chunks.concat(); + let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + out.extend((chunks.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// A DXF whose LAYER table holds 0 and BALLOONS only (CADCraft keeps Defpoints at index 1 of +/// its own table), a text style on isocp.shx, a line and one proxy balloon. +fn file() -> String { + let graphics = balloon(); + let hex: Vec = graphics.chunks(127).map(|c| c.iter().map(|b| format!("{b:02X}")).collect()).collect(); + let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "CLASSES".into())]; + for (c, v) in [(0, "CLASS"), (1, "SYNBALLOON"), (2, "SynBalloon"), (3, "SyntheticProxyApp"), (90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC")] { + tags.push((c, v.into())); + } + for (c, v) in [ + (0, "SECTION"), + (2, "TABLES"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (5, "10"), + (2, "0"), + (62, "7"), + (0, "LAYER"), + (5, "11"), + (2, "BALLOONS"), + (62, "3"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "STYLE"), + (0, "STYLE"), + (5, "12"), + (2, "ISO"), + (3, "isocp.shx"), + (0, "ENDTAB"), + (0, "ENDSEC"), + (0, "SECTION"), + (2, "ENTITIES"), + (0, "LINE"), + (5, "20"), + (8, "0"), + (10, "50"), + (20, "40"), + (11, "150"), + (21, "90"), + (0, "ACAD_PROXY_ENTITY"), + (5, "21"), + (100, "AcDbEntity"), + (8, "0"), + (100, "AcDbProxyEntity"), + (90, "498"), + (91, "500"), + (95, "0"), + (70, "0"), + ] { + tags.push((c, v.into())); + } + tags.push((92, graphics.len().to_string())); + tags.extend(hex.into_iter().map(|h| (310, h))); + for (c, v) in [(93, "0"), (94, "0"), (0, "ENDSEC"), (0, "EOF")] { + tags.push((c, v.into())); + } + tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +#[test] +fn a_proxy_draws_its_graphics_with_the_files_table_indices() { + let d = read_dxf(file().as_bytes()).expect("read"); + let proxy = d.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy"); + let EntityKind::Unknown(u) = &proxy.kind else { unreachable!() }; + let kinds: Vec<(&str, &str, Color)> = u.graphics.iter().map(|g| (g.kind.dxf_name(), g.common.layer.as_str(), g.common.color)).collect(); + // Layer index 1 is BALLOONS, the file's second layer, not CADCraft's Defpoints. + assert_eq!(kinds, [("CIRCLE", "BALLOONS", Color::Index(1)), ("LINE", "BALLOONS", Color::Index(1)), ("TEXT", "BALLOONS", Color::Index(1))]); + assert!(matches!(&u.graphics[2].kind, EntityKind::Text(t) if t.value == "1" && t.style == "ISO")); + // The extents reach the balloon (the line alone ends at 150, 90). + let b = d.extents(&Space::Model); + assert!(b.max.x >= 181.0 && b.max.y >= 121.0, "{b:?}"); +} + +#[test] +fn a_proxy_is_written_back_unchanged_and_draws_again() { + let d = read_dxf(file().as_bytes()).expect("read"); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + let graphics = |d: &cadcraft_doc::Drawing| { + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some((u.proxy_graphics_bytes(), u.graphics.len())), + _ => None, + }) + }; + assert_eq!(graphics(&again), graphics(&d)); + assert_eq!(graphics(&d).map(|g| g.1), Some(3)); + // The saved LAYER table keeps the file's order, so index 1 is still BALLOONS (CADCraft's + // Defpoints comes after it) and the reopened graphics stay on that layer. + let layers = |d: &cadcraft_doc::Drawing| -> Vec { + d.model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some(u.graphics.iter().map(|g| g.common.layer.clone()).collect()), + _ => None, + }) + .unwrap_or_default() + }; + assert_eq!(layers(&again), ["BALLOONS"; 3]); + let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["0", "BALLOONS", "Defpoints"]); +} + +/// A proxy text takes the first style on its font. With ISO and then Standard both on +/// isocp.shx, it is ISO, and stays ISO after a save: CADCraft's own Standard, which the file's +/// replaces, would otherwise come first in the saved STYLE table. +#[test] +fn a_proxy_text_keeps_its_style_after_a_save() { + let iso = "0\nSTYLE\n5\n12\n2\nISO\n3\nisocp.shx\n"; + let src = file().replacen(iso, &format!("{iso}0\nSTYLE\n5\n13\n2\nStandard\n3\nisocp.shx\n"), 1); + let style = |d: &cadcraft_doc::Drawing| { + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) => u.graphics.iter().find_map(|g| match &g.kind { + EntityKind::Text(t) => Some(t.style.clone()), + _ => None, + }), + _ => None, + }) + }; + let d = read_dxf(src.as_bytes()).expect("read"); + assert_eq!(style(&d).as_deref(), Some("ISO")); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert_eq!(style(&again).as_deref(), Some("ISO"), "after a save"); +} diff --git a/crates/io/tests/it/proxy_layers.rs b/crates/io/tests/it/proxy_layers.rs new file mode 100644 index 000000000..8ef23cc29 --- /dev/null +++ b/crates/io/tests/it/proxy_layers.rs @@ -0,0 +1,150 @@ +//! Proxy graphics name layers by their index in the file's LAYER table (#3094). AutoCAD keeps +//! layers that only proxy graphics use, but saves the graphics with their old indices after +//! PURGE removed a layer before them, which moves the graphics to other layers; CADCraft turns the +//! indices into the written table's on save. + +use cadcraft_doc::{EntityKind, Unknown}; +use cadcraft_io::{read_dxf, write_dxf}; + +/// A proxy graphics chunk of type `kind`, its data padded to four bytes. +fn chunk(kind: u32, data: &[u8]) -> Vec { + let mut d = data.to_vec(); + d.resize(d.len().div_ceil(4) * 4, 0); + let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec(); + out.extend(kind.to_le_bytes()); + out.extend(d); + out +} + +/// Four circles, each on the layer index given, in colour ByLayer. +fn graphics(indices: [u32; 4]) -> Vec { + let mut chunks = Vec::new(); + for (i, index) in indices.into_iter().enumerate() { + let mut circle: Vec = [25.0 + 50.0 * i as f64, 70.0, 0.0, 15.0, 0.0, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + circle.truncate(56); + chunks.push(chunk(16, &index.to_le_bytes())); + chunks.push(chunk(14, &256u32.to_le_bytes())); + chunks.push(chunk(2, &circle)); + } + let body = chunks.concat(); + let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + out.extend((chunks.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// The test drawing checked against AutoCAD: the LAYER table 0, Defpoints, A_LEER (unused), +/// B_NOTIZ, C_EXTRA, and a proxy on layer 0 drawing circles on indices 0, 3, 4 and 99 (past the +/// table). `a_leer_handle: false` leaves A_LEER's handle out. +fn file(a_leer_handle: bool) -> String { + let g = graphics([0, 3, 4, 99]); + let mut tags: Vec<(i32, String)> = Vec::new(); + let mut push = |list: &[(i32, &str)]| tags.extend(list.iter().map(|(c, v)| (*c, v.to_string()))); + push(&[(0, "SECTION"), (2, "CLASSES"), (0, "CLASS"), (1, "SYNLAYERTEST"), (2, "SynLayerTest"), (3, "SyntheticProxyApp")]); + push(&[(90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC"), (0, "SECTION"), (2, "TABLES"), (0, "TABLE"), (2, "LAYER")]); + for (handle, name, color) in [("10", "0", "7"), ("11", "Defpoints", "7"), ("12", "A_LEER", "1"), ("13", "B_NOTIZ", "3"), ("14", "C_EXTRA", "5")] { + push(&[(0, "LAYER")]); + if a_leer_handle || name != "A_LEER" { + push(&[(5, handle)]); + } + push(&[(2, name), (62, color)]); + } + push(&[(0, "ENDTAB"), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "ACAD_PROXY_ENTITY"), (5, "21"), (100, "AcDbEntity"), (8, "0")]); + push(&[(100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (95, "0"), (70, "0")]); + tags.push((92, g.len().to_string())); + tags.extend(g.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect()))); + tags.extend([(93, "0".to_string()), (94, "0".to_string()), (0, "ENDSEC".to_string()), (0, "EOF".to_string())]); + tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +fn proxy(d: &cadcraft_doc::Drawing) -> &Unknown { + d.model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some(u), + _ => None, + }) + .expect("proxy") +} + +/// The layers the four circles draw on. +fn circle_layers(d: &cadcraft_doc::Drawing) -> Vec { + proxy(d).graphics.iter().map(|g| g.common.layer.clone()).collect() +} + +/// The layer indices in the proxy's graphics bytes. +fn indices(d: &cadcraft_doc::Drawing) -> Vec { + let b = proxy(d).proxy_graphics_bytes(); + let mut at = 8; + let mut out = Vec::new(); + while at + 8 <= b.len() { + let size = u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + if u32::from_le_bytes(b[at + 4..at + 8].try_into().unwrap()) == 16 { + out.push(u32::from_le_bytes(b[at + 8..at + 12].try_into().unwrap())); + } + at += size; + } + out +} + +#[test] +fn indices_resolve_in_the_files_table_and_one_past_it_keeps_the_layer() { + let d = read_dxf(file(true).as_bytes()).expect("read"); + // As AutoCAD draws it: index 99 keeps the layer before it. + assert_eq!(circle_layers(&d), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]); + // Saved unchanged when the table is. + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert_eq!((indices(&again), circle_layers(&again)), (vec![0, 3, 4, 99], circle_layers(&d))); +} + +/// AutoCAD's PURGE removes A_LEER and Defpoints and keeps the two layers the graphics use; saved +/// as AutoCAD saves it, indices 3 and 4 would point past the three-entry table. CADCraft writes +/// them as 1 and 2. +#[test] +fn removing_a_layer_before_the_ones_the_graphics_use_keeps_them_on_save() { + let mut d = read_dxf(file(true).as_bytes()).expect("read"); + d.layers.retain(|l| l.name != "A_LEER" && l.name != "Defpoints"); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).take(3).collect(); + assert_eq!(names, ["0", "B_NOTIZ", "C_EXTRA"]); + assert_eq!(circle_layers(&again), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]); + // 99 stays past the table. + assert_eq!(indices(&again), [0, 1, 2, 99]); +} + +/// Renaming a layer the graphics use moves them with it at once, and saving keeps them there. +#[test] +fn renaming_a_layer_the_graphics_use_keeps_them_on_it() { + let mut d = read_dxf(file(true).as_bytes()).expect("read"); + d.layer_mut("B_NOTIZ").expect("layer").name = "B_NEU".into(); + d.rename_proxy_layer("B_NOTIZ", "B_NEU"); + assert_eq!(circle_layers(&d), ["0", "B_NEU", "C_EXTRA", "C_EXTRA"]); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert_eq!(circle_layers(&again), ["0", "B_NEU", "C_EXTRA", "C_EXTRA"]); +} + +/// A LAYER record without a handle (AutoCAD rejects such a file) still counts in the index +/// list: the layers after it don't move up by one. +#[test] +fn a_layer_record_without_a_handle_keeps_its_place_in_the_index() { + let d = read_dxf(file(false).as_bytes()).expect("read"); + assert_eq!(circle_layers(&d), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]); +} + +/// A proxy copied into a drawing whose LAYER table has another order keeps the layers it shows: +/// its indices are named by its own graphics, not by the other file's table. +#[test] +fn a_proxy_copied_from_another_drawing_keeps_its_layers() { + let source = read_dxf(file(true).as_bytes()).expect("read"); + let proxy = source.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy").as_ref().clone(); + // The target: the same layers in another order (C_EXTRA, B_NOTIZ before A_LEER), read from a + // file so it has a table of its own. + let mut target = read_dxf(file(true).as_bytes()).expect("read"); + target.model = Default::default(); + target.proxy_layers = vec!["0".into(), "C_EXTRA".into(), "B_NOTIZ".into(), "Defpoints".into(), "A_LEER".into()]; + let order = ["0", "C_EXTRA", "B_NOTIZ", "Defpoints", "A_LEER"]; + target.layers.sort_by_key(|l| order.iter().position(|n| *n == l.name).unwrap_or(99)); + target.add(&cadcraft_doc::Space::Model, proxy.common.clone(), proxy.kind.clone()).expect("add"); + let again = read_dxf(write_dxf(&target).as_bytes()).expect("reopen"); + assert_eq!(circle_layers(&again), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]); +} diff --git a/crates/io/tests/it/region_roundtrip.rs b/crates/io/tests/it/region_roundtrip.rs index 384443d62..d75255f6f 100644 --- a/crates/io/tests/it/region_roundtrip.rs +++ b/crates/io/tests/it/region_roundtrip.rs @@ -19,7 +19,7 @@ fn regions(d: &Drawing) -> Vec { fn square(x: f64, y: f64, s: f64, outer: bool) -> HatchLoop { let v = |a: f64, b: f64| PolyVertex::new(Vec2::new(a, b)); - HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, sources: Vec::new() } + HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, boundary_flags: None, sources: Vec::new() } } #[test] @@ -29,6 +29,7 @@ fn region_with_islands_survives_save_and_reopen() { let hole = HatchLoop { vertices: vec![PolyVertex::with_bulge(Vec2::new(3.0, 5.0), 1.0), PolyVertex::with_bulge(Vec2::new(7.0, 5.0), 1.0)], outer: false, + boundary_flags: None, sources: Vec::new(), }; let r = Region { loops: vec![square(0.0, 0.0, 10.0, true), hole, square(4.5, 4.5, 1.0, true), square(20.0, 0.0, 2.0, true)] }; diff --git a/crates/io/tests/it/roundtrip/cases/geometry.rs b/crates/io/tests/it/roundtrip/cases/geometry.rs index 35a2cc9dc..e8168c183 100644 --- a/crates/io/tests/it/roundtrip/cases/geometry.rs +++ b/crates/io/tests/it/roundtrip/cases/geometry.rs @@ -226,7 +226,7 @@ pub(crate) fn hatches() -> Vec { EntityKind::Hatch(Hatch { pattern: "SOLID".into(), solid: true, - loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }], + loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }], scale: 1.0, angle: 0.0, associative: false, diff --git a/crates/io/tests/it/roundtrip/collections.rs b/crates/io/tests/it/roundtrip/collections.rs index 95acb6328..00006d922 100644 --- a/crates/io/tests/it/roundtrip/collections.rs +++ b/crates/io/tests/it/roundtrip/collections.rs @@ -257,8 +257,13 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) { let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive"); assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name); // The groups 44, 45 and 73 the file stored are provenance, not a setting. - let setting = - |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..p.clone() }; + let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { + file_plot_settings: None, + file_paper: None, + file_plot_flags: None, + file_standard_scale: None, + ..p.clone() + }; assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name); assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name); compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name)); diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index e263f47f8..70768d3b0 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -373,3 +373,53 @@ fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() { assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err()); } } + +/// Authored two-point text saves the dimensions of its measured span. Expectations come from +/// shaping and geometry, independently of the save fitting helper; all field assertions remain. +pub(super) fn authored_text_dimensions(d: &Drawing) -> Drawing { + fn fit(d: &Drawing, t: &mut Text) { + use cadcraft_doc::HAlign; + if !matches!(t.halign, HAlign::Aligned | HAlign::Fit) { + return; + } + let Some(second) = t.align_pt else { return }; + let distance = t.insert.xy().dist(second.xy()); + if !distance.is_finite() || distance <= 1e-12 { + return; + } + t.rotation = t.insert.xy().angle_to(second.xy()); + let style = d.text_style(&t.style).cloned().unwrap_or_default(); + let font = cadcraft_render::style_font(&style); + let width = cadcraft_fonts::shape_line_dir(&font, &t.value, t.height, t.width_factor, t.oblique, Some(false)).width; + if width.is_finite() && width > 1e-12 { + if t.halign == HAlign::Aligned { + t.height *= distance / width; + } else { + t.width_factor *= distance / width; + } + } + } + fn store(d: &Drawing, entities: &mut EntityStore) { + for h in entities.handles() { + // Read-time measurements already have their own preservation contract. + if d.foreign.text_fits.contains_key(&h) { + continue; + } + entities.modify(h, |e| match &mut e.kind { + EntityKind::Text(t) => fit(d, t), + EntityKind::AttDef(a) => fit(d, &mut a.text), + EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fit(d, &mut a.text)), + _ => {} + }); + } + } + let mut expected = d.clone(); + store(d, &mut expected.model); + for layout in &mut expected.layouts { + store(d, &mut layout.entities); + } + for block in expected.blocks.values_mut() { + store(d, &mut std::sync::Arc::make_mut(block).entities); + } + expected +} diff --git a/crates/io/tests/it/roundtrip/dwg/mod.rs b/crates/io/tests/it/roundtrip/dwg/mod.rs index 9a42879f8..ff91807fa 100644 --- a/crates/io/tests/it/roundtrip/dwg/mod.rs +++ b/crates/io/tests/it/roundtrip/dwg/mod.rs @@ -57,6 +57,8 @@ fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, versio } fn check_version_using(case: &str, original: &Drawing, expected: &Drawing, version: Version, verify: impl Fn(&Drawing, &Drawing, &str)) { + let expected_dimensions = compare::authored_text_dimensions(expected); + let expected = &expected_dimensions; cadcraft_io::dwg_worker::allow_in_process(); let options = SaveOptions { version: Some(version), binary: false }; let mut current = original.clone(); diff --git a/crates/io/tests/it/roundtrip/dxf/mod.rs b/crates/io/tests/it/roundtrip/dxf/mod.rs index 0c89d453f..9427a66b3 100644 --- a/crates/io/tests/it/roundtrip/dxf/mod.rs +++ b/crates/io/tests/it/roundtrip/dxf/mod.rs @@ -33,6 +33,8 @@ fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Ve } fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) { + let expected_dimensions = compare::authored_text_dimensions(expected); + let expected = &expected_dimensions; for binary in [false, true] { let options = SaveOptions { version: Some(version), binary }; let mut current = original.clone(); diff --git a/crates/io/tests/it/roundtrip/unknown.rs b/crates/io/tests/it/roundtrip/unknown.rs index e4d327e4b..b1b2b37d0 100644 --- a/crates/io/tests/it/roundtrip/unknown.rs +++ b/crates/io/tests/it/roundtrip/unknown.rs @@ -27,7 +27,7 @@ fn drawing() -> Drawing { RawTag { code: 30, value: "3.75".into() }, RawTag { code: 330, value: target.hex() }, ]; - d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags }))); + d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() }))); d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) }))); d } diff --git a/crates/io/tests/it/table_cellstyle_roundtrip.rs b/crates/io/tests/it/table_cellstyle_roundtrip.rs index 54735b731..a4eda079b 100644 --- a/crates/io/tests/it/table_cellstyle_roundtrip.rs +++ b/crates/io/tests/it/table_cellstyle_roundtrip.rs @@ -4,6 +4,194 @@ use cadcraft_color::{Color, Rgb}; use cadcraft_doc::*; use cadcraft_geom::Vec3; +use cadcraft_io::SaveOptions; +use craft_dxf::Version; + +#[test] +fn modern_table_cell_values_have_reference_groups() { + for (rows, cols, merged) in [(3, 2, false), (4, 3, true)] { + let mut d = Drawing::new_imperial(); + let mut cells: Vec> = (0..rows) + .map(|row| (0..cols).map(|col| TableCell { text: format!("{}{}", (b'A' + col as u8) as char, row + 1), ..Default::default() }).collect()) + .collect(); + if merged { + cells[0][0].text = "Title".into(); + cells[0][0].merged = Some((1, cols as u32)); + cells[0][1].text = "CoveredText".repeat(30); + } + let table = Table { col_widths: vec![2.0; cols], row_heights: vec![0.5; rows], cells, title: merged, ..Table::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Table(table.clone())).unwrap(); + if !merged { + let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap(); + assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, table.cells); + } + for version in [Version::R2007, Version::R2010, Version::R2013, Version::R2018] { + let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + let lines: Vec<_> = text.lines().map(str::trim).collect(); + let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect(); + let start = pairs.iter().position(|p| *p == ("0", "ACAD_TABLE")).unwrap(); + let end = start + 1 + pairs[start + 1..].iter().position(|p| p.0 == "0").unwrap(); + let values: Vec<_> = pairs[start..end].iter().filter(|p| p.0 == "302").map(|p| p.1).collect(); + let expected: Vec<_> = table + .cells + .iter() + .enumerate() + .flat_map(|(row, cells)| { + cells.iter().enumerate().map(move |(col, cell)| if merged && row == 0 && col > 0 { "" } else { cell.text.as_str() }) + }) + .collect(); + assert_eq!(values, expected); + assert_eq!(pairs[start..end].iter().filter(|p| **p == ("301", "CELL_VALUE")).count(), rows * cols); + assert_eq!(pairs[start..end].iter().filter(|p| **p == ("304", "ACVALUE_END")).count(), rows * cols); + let value_start = start + pairs[start..end].iter().position(|p| *p == ("301", "CELL_VALUE")).unwrap(); + let value_end = value_start + pairs[value_start..end].iter().position(|p| *p == ("304", "ACVALUE_END")).unwrap(); + let cell_start = start + pairs[start..end].iter().position(|p| *p == ("171", "1")).unwrap(); + assert!(pairs[cell_start..value_start].contains(&("92", "0"))); + let first_text = if merged { "Title" } else { "A1" }; + assert_eq!( + &pairs[value_start..=value_end], + &[ + ("301", "CELL_VALUE"), + ("93", "4"), + ("90", "4"), + ("1", first_text), + ("94", "0"), + ("300", ""), + ("302", first_text), + ("304", "ACVALUE_END") + ] + ); + if merged { + assert_eq!( + &pairs[cell_start..=value_end], + &[ + ("171", "1"), + ("172", "0"), + ("173", "0"), + ("174", "0"), + ("175", "3"), + ("176", "1"), + ("91", "0"), + ("92", "0"), + ("178", "0"), + ("145", "0.0"), + ("301", "CELL_VALUE"), + ("93", "4"), + ("90", "4"), + ("1", "Title"), + ("94", "0"), + ("300", ""), + ("302", "Title"), + ("304", "ACVALUE_END") + ] + ); + let covered_start = cell_start + 1 + pairs[cell_start + 1..end].iter().position(|pair| *pair == ("171", "1")).unwrap(); + let covered_end = covered_start + pairs[covered_start..end].iter().position(|pair| *pair == ("304", "ACVALUE_END")).unwrap(); + assert_eq!( + &pairs[covered_start..=covered_end], + &[ + ("171", "1"), + ("172", "0"), + ("173", "1"), + ("174", "0"), + ("175", "0"), + ("176", "0"), + ("91", "0"), + ("92", "0"), + ("178", "0"), + ("145", "0.0"), + ("301", "CELL_VALUE"), + ("93", "4"), + ("90", "4"), + ("1", ""), + ("94", "0"), + ("300", ""), + ("302", ""), + ("304", "ACVALUE_END") + ] + ); + } + let mut expected_cells = table.cells.clone(); + if merged { + for cell in &mut expected_cells[0][1..] { + cell.text.clear(); + } + } + assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, expected_cells); + } + if merged { + let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(Version::R2004), binary: false }).unwrap(); + let text = String::from_utf8(bytes).unwrap(); + let lines: Vec<_> = text.lines().map(str::trim).collect(); + let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|pair| (pair[0], pair[1])).collect(); + let start = pairs.iter().position(|pair| *pair == ("0", "ACAD_TABLE")).unwrap(); + let end = start + 1 + pairs[start + 1..].iter().position(|pair| pair.0 == "0").unwrap(); + let mut values = Vec::new(); + let mut value = String::new(); + let cell_start = start + pairs[start..end].iter().position(|pair| *pair == ("171", "1")).unwrap(); + for &(code, chunk) in &pairs[cell_start..end] { + if code == "2" || code == "1" { + value.push_str(chunk); + if code == "1" { + values.push(std::mem::take(&mut value)); + } + } + } + assert_eq!(values, table.cells.iter().flatten().map(|cell| cell.text.clone()).collect::>()); + } + } +} + +#[test] +fn formatted_cell_text_reads_without_typed_text() { + // Synthetic DXF with one complete value and one value split across chunks. + let dxf = "0\nSECTION\n2\nENTITIES\n0\nACAD_TABLE\n100\nAcDbTable\n91\n1\n92\n2\n171\n1\n301\nCELL_VALUE\n302\nSingle\n304\nACVALUE_END\n171\n1\n301\nCELL_VALUE\n303\nFirst \n302\nsecond\n304\nACVALUE_END\n0\nENDSEC\n0\nEOF\n"; + let table = first_table(&cadcraft_io::read(dxf.as_bytes(), "table.dxf").unwrap()); + assert_eq!(table.cells[0][0].text, "Single"); + assert_eq!(table.cells[0][1].text, "First second"); +} + +#[test] +fn legacy_table_cell_text_stays_in_legacy_groups() { + let (drawing, table) = sample(); + for version in [Version::R2000, Version::R2004] { + let bytes = cadcraft_io::write_with(&drawing, "t.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + let lines: Vec<_> = text.lines().map(str::trim).collect(); + let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|pair| (pair[0], pair[1])).collect(); + let start = pairs.iter().position(|pair| *pair == ("0", "ACAD_TABLE")).unwrap(); + let end = start + 1 + pairs[start + 1..].iter().position(|pair| pair.0 == "0").unwrap(); + assert!(!pairs[start..end].iter().any(|pair| matches!(pair.0, "301" | "302" | "303" | "304"))); + let values: Vec<_> = pairs[start..end].iter().filter(|pair| pair.0 == "1").map(|pair| pair.1).collect(); + assert_eq!(values, table.cells.iter().flatten().map(|cell| cell.text.as_str()).collect::>()); + assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, table.cells); + } +} + +#[test] +fn long_modern_cell_text_roundtrips() { + let mut d = Drawing::new_imperial(); + let value = "éabc".repeat(140); + let table = Table { + col_widths: vec![2.0], + row_heights: vec![0.5], + cells: vec![vec![TableCell { text: value.clone(), ..Default::default() }]], + ..Table::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Table(table)).unwrap(); + for version in [Version::R2007, Version::R2018] { + let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + let lines: Vec<_> = text.lines().collect(); + let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|pair| (pair[0].trim(), pair[1])).collect(); + let start = pairs.iter().position(|pair| *pair == ("301", "CELL_VALUE")).unwrap(); + let end = start + pairs[start..].iter().position(|pair| *pair == ("304", "ACVALUE_END")).unwrap(); + let formatted: String = pairs[start..end].iter().filter(|pair| matches!(pair.0, "302" | "303")).map(|pair| pair.1).collect(); + assert_eq!(formatted, value); + assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells[0][0].text, value); + } +} fn sample() -> (Drawing, Table) { let mut d = Drawing::new_imperial(); @@ -122,5 +310,9 @@ fn breaks_and_data_links_roundtrip_and_the_block_draws_the_parts() { assert_eq!(first_table(&back), t); // Two parts: the block repeats the header row (Item / Cost). let text = String::from_utf8(bytes).unwrap(); - assert_eq!(text.lines().filter(|l| l.trim() == "Item").count(), 3, "two in the block, one in the table cells"); + let lines: Vec<_> = text.lines().map(str::trim).collect(); + let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|pair| (pair[0], pair[1])).collect(); + let start = pairs.iter().position(|pair| *pair == ("2", "BLOCKS")).unwrap(); + let end = start + pairs[start..].iter().position(|pair| *pair == ("0", "ENDSEC")).unwrap(); + assert_eq!(pairs[start..end].iter().filter(|pair| **pair == ("1", "Item")).count(), 2, "one header per table part in the block"); } diff --git a/crates/io/tests/it/tables_objects_roundtrip.rs b/crates/io/tests/it/tables_objects_roundtrip.rs index 502aafa3d..380aa797d 100644 --- a/crates/io/tests/it/tables_objects_roundtrip.rs +++ b/crates/io/tests/it/tables_objects_roundtrip.rs @@ -112,7 +112,13 @@ fn layout_page_setup_and_paper_view_round_trip() { for (a, b) in d.layouts.iter().zip(&r.layouts) { assert_eq!(a.name, b.name); // The groups 44, 45 and 73 the file stored are provenance, not a setting. - let read = cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..b.page.clone() }; + let read = cadcraft_doc::PageSetup { + file_plot_settings: None, + file_paper: None, + file_plot_flags: None, + file_standard_scale: None, + ..b.page.clone() + }; assert_eq!(a.page, read, "{}", a.name); assert_eq!(a.view, b.view, "{}", a.name); } diff --git a/crates/io/tests/it/user_lin_pat_roundtrip.rs b/crates/io/tests/it/user_lin_pat_roundtrip.rs index 6ab6df491..100ba96b2 100644 --- a/crates/io/tests/it/user_lin_pat_roundtrip.rs +++ b/crates/io/tests/it/user_lin_pat_roundtrip.rs @@ -19,7 +19,7 @@ fn user_linetypes_and_patterns_survive_dxf() { let h = Hatch { pattern: steps.name.clone(), solid: false, - loops: vec![HatchLoop { vertices: square, outer: true, sources: Vec::new() }], + loops: vec![HatchLoop { vertices: square, outer: true, boundary_flags: None, sources: Vec::new() }], scale: 1.0, angle: 0.0, associative: false, diff --git a/crates/io/tests/it/visualstyle_dwg.rs b/crates/io/tests/it/visualstyle_dwg.rs new file mode 100644 index 000000000..949bdd899 --- /dev/null +++ b/crates/io/tests/it/visualstyle_dwg.rs @@ -0,0 +1,95 @@ +//! Original synthetic geometry, style values and xdata, licensed with the repository. +//! The fixed fields follow Autodesk's 2010 DXF Reference, VISUALSTYLE, pp. 208-210: +//! https://images.autodesk.com/adsk/files/acad_dxf1.pdf + +use cadcraft_doc::EntityKind; +use cadcraft_io::{SaveOptions, Version}; + +fn source(version: &str) -> String { + let mut text = format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\ + 0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nAPPID\n5\n10\n100\nAcDbSymbolTable\n70\n1\n\ + 0\nAPPID\n5\n11\n330\n10\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n2\nACAD\n70\n0\n0\nENDTAB\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\ + 0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic0\n350\n21\n3\nSynthetic1\n350\n22\n" + ); + for index in 0..2 { + text.push_str(&format!( + "0\nVISUALSTYLE\n5\n{:X}\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic{index}\n\ + 70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\ + 74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n\ + 76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n\ + 1001\nACAD\n1000\nAcRTDxfName\n1000\nVISUALSTYLE\n", + 0x21 + index + )); + } + text.push_str("0\nENDSEC\n0\nEOF\n"); + text +} + +#[test] +fn legacy_visualstyles_are_reported_and_left_out_of_2007_dwg_only() { + cadcraft_io::dwg_worker::allow_in_process(); + for from in ["AC1021", "AC1024"] { + let drawing = cadcraft_io::read_dxf(source(from).as_bytes()).unwrap(); + let styles = || drawing.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count(); + assert_eq!(styles(), 2); + for version in [Version::R2007, Version::R2013] { + let options = SaveOptions { version: Some(version), binary: false }; + let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap(); + let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap(); + assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_)))); + let retained = back + .foreign + .objects + .iter() + .any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic"))); + if version == Version::R2007 { + assert_eq!(report.get("VISUALSTYLE"), Some(&styles())); + assert!(!retained); + } else { + assert!(!report.contains_key("VISUALSTYLE")); + assert!(retained); + } + let (dxf, report) = cadcraft_io::write_noted(&drawing, "styles.dxf", &options).unwrap(); + assert!(report.is_empty()); + let back = cadcraft_io::read_dxf(&dxf).unwrap(); + assert_eq!(back.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count(), styles()); + } + assert_eq!(styles(), 2); + } +} + +#[test] +fn orphaned_legacy_visualstyles_are_not_reported_as_compatibility_omissions() { + cadcraft_io::dwg_worker::allow_in_process(); + let mut drawing = cadcraft_io::read_dxf(source("AC1021").as_bytes()).unwrap(); + let foreign = std::sync::Arc::make_mut(&mut drawing.foreign); + let orphan = foreign.objects.iter_mut().find(|object| object.kind == "VISUALSTYLE").unwrap(); + orphan.tags.iter_mut().find(|tag| tag.code == 330).unwrap().value = "FF".into(); + let options = SaveOptions { version: Some(Version::R2007), binary: false }; + let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap(); + let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap(); + assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_)))); + assert_eq!(report.get("VISUALSTYLE"), Some(&1)); +} + +#[test] +fn newer_visualstyle_properties_are_kept_in_2007_dwg() { + cadcraft_io::dwg_worker::allow_in_process(); + let document = acadrust::DxfReader::from_reader(std::io::Cursor::new(source("AC1027").into_bytes())).unwrap().read().unwrap(); + let modern = acadrust::DxfWriter::new(&document).write_to_vec().unwrap(); + let drawing = cadcraft_io::read_dxf(&modern).unwrap(); + assert!(drawing.foreign.objects.iter().any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 176))); + let options = SaveOptions { version: Some(Version::R2007), binary: false }; + let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap(); + assert!(!report.contains_key("VISUALSTYLE")); + let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap(); + assert!( + back.foreign + .objects + .iter() + .any(|object| { object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")) }) + ); +} diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index 29f1022d4..434d222f3 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -26,30 +26,31 @@ mod sfnt; /// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds /// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset. fn test_font(fs_type: u16, metrics: usize) -> Vec { - sfnt::bytes(&sfnt::Sfnt { - // "A" is a triangle and "B" a square: one contour each. - glyphs: &[ - sfnt::notdef(), - sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]), - sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]), - ], - cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2 - advance: 600, - lsb: 50, - metrics, - fs_type, - ink_box: [0, 0, 600, 700], - }) + font_of(fs_type, metrics, &['A', 'B']) } -/// Register the test fonts once: an embeddable one, one with a restricted licence, and one -/// the PDF writer accepts but can't subset (its `hmtx` is short). +/// [`test_font`] with a glyph for each of `chars` (BMP characters, ascending), alternately a +/// triangle and a square: one contour each. +fn font_of(fs_type: u16, metrics: usize, chars: &[char]) -> Vec { + let shapes = [vec![(50, 0), (550, 0), (300, 700)], vec![(50, 0), (550, 0), (550, 700), (50, 700)]]; + let glyphs: Vec = std::iter::once(sfnt::notdef()).chain((0..chars.len()).map(|i| sfnt::glyph(&[shapes[i % 2].clone()]))).collect(); + // One segment per character: chars[i] → glyph i + 1. + let cmap: Vec<(u16, u16, i16)> = chars.iter().zip(1u16..).map(|(c, g)| (*c as u16, *c as u16, g.wrapping_sub(*c as u16) as i16)).collect(); + sfnt::bytes(&sfnt::Sfnt { glyphs: &glyphs, cmap: &cmap, advance: 600, lsb: 50, metrics, fs_type, ink_box: [0, 0, 600, 700] }) +} + +/// The characters of the Thai test font: no, sara aa, sara am, mai tho and nikhahit. +const THAI: [char; 5] = ['\u{0E19}', '\u{0E32}', '\u{0E33}', '\u{0E49}', '\u{0E4D}']; + +/// Register the test fonts once: an embeddable one, one with a restricted licence, one +/// the PDF writer accepts but can't subset (its `hmtx` is short), and one with Thai letters. fn fonts() { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { cadcraft_fonts::ttf::register("cadcraft-pdf-test.ttf", test_font(0, 3)); cadcraft_fonts::ttf::register("cadcraft-pdf-restricted.ttf", test_font(0x0002, 3)); cadcraft_fonts::ttf::register("cadcraft-pdf-short-hmtx.ttf", test_font(0, 1)); + cadcraft_fonts::ttf::register("cadcraft-pdf-thai.ttf", font_of(0, THAI.len() + 1, &THAI)); }); } @@ -81,6 +82,7 @@ fn drawing() -> Drawing { style(&mut d, "Real", "cadcraft-pdf-test.ttf"); style(&mut d, "Locked", "cadcraft-pdf-restricted.ttf"); style(&mut d, "Short", "cadcraft-pdf-short-hmtx.ttf"); + style(&mut d, "Thai", "cadcraft-pdf-thai.ttf"); d } @@ -279,3 +281,52 @@ fn hostile_text_never_panics() { pdf(&d, &Space::Model, json!({})); pdf(&d, &Space::Model, json!({"compress": true})); } + +/// The text layer reads as typed (issue #2899): the shaper splits sara am into nikhahit and +/// sara aa and draws the nikhahit before the tone mark, so in น้ำ the sara aa carries ำ, after +/// the tone mark, and the nikhahit is drawn as an outline. Every glyph is still drawn. +#[test] +fn thai_text_reads_in_typed_order() { + let mut d = drawing(); + text(&mut d, &Space::Model, "Thai", (0.0, 0.0), "น้ำ", (0.0, 1.0, 0.0)); + let doc = pdf(&d, &Space::Model, json!({})); + let f = &doc.pages[0].fonts[0]; + let map = pdf_read::to_unicode_map(f.to_unicode.as_deref().unwrap()); + let read: String = codes(&doc).iter().map(|c| map.iter().find(|(k, _)| k == c).map_or("?", |(_, s)| s.as_str())).collect(); + assert_eq!(read, "น้ำ", "{map:?}"); + assert_eq!(pdf_read::count(doc.content(), "Tj") + fills(&doc), 4, "no, nikhahit, mai tho and sara aa: {}", doc.content()); +} + +/// The text the page reads as, glyph by glyph in content order: a glyph's `/ActualText` when it +/// has one, else its code through the font's `ToUnicode` map. +fn read_text(doc: &Doc) -> String { + let map = pdf_read::to_unicode_map(doc.pages[0].fonts[0].to_unicode.as_deref().unwrap()); + let mut out = String::new(); + for text in doc.content().split("BT").skip(1) { + if let Some((_, rest)) = text.split_once("/ActualText<") { + let hex = rest.split('>').next().unwrap(); + let units: Vec = hex.as_bytes().chunks(4).map(|u| u16::from_str_radix(std::str::from_utf8(u).unwrap(), 16).unwrap()).collect(); + out.extend(char::decode_utf16(units.into_iter().skip_while(|u| *u == 0xFEFF)).map(Result::unwrap)); + continue; + } + for s in pdf_read::shown(text.as_bytes()) { + for c in s.chunks(2).map(|c| u32::from(c[0]) << 8 | u32::from(c[1])) { + out.push_str(map.iter().find(|(k, _)| *k == c).map_or("?", |(_, s)| s.as_str())); + } + } + } + out +} + +/// One glyph shows sara am in น้ำ and sara aa in นา: whichever comes second gets its own +/// `/ActualText`, so both read right whichever comes first. +#[test] +fn a_glyph_shared_by_two_characters_reads_right_in_both() { + for words in [["นา", "น้ำ"], ["น้ำ", "นา"]] { + let mut d = drawing(); + text(&mut d, &Space::Model, "Thai", (0.0, 50.0), words[0], (0.0, 1.0, 0.0)); + text(&mut d, &Space::Model, "Thai", (0.0, 0.0), words[1], (0.0, 1.0, 0.0)); + let doc = pdf(&d, &Space::Model, json!({})); + assert_eq!(read_text(&doc), words.concat(), "{}", doc.content()); + } +} diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 69a226cf2..9fcfc51d1 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -40,6 +40,23 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> { } } +/// A proxy entity draws its proxy graphics as AutoCAD does with PROXYSHOW 1, like block contents: +/// layer 0 and ByBlock in the picture stand for the proxy's own layer and properties. Other +/// unknown records draw nothing. `own` is the proxy's transparency without its locked-layer fade, +/// as for a block reference. +pub(crate) fn proxy(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, own: u8) { + if u.graphics.is_empty() || ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH { + return; + } + let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::IDENTITY) }; + for g in &u.graphics { + if !b.expand() { + break; + } + entity(b, &sub, g); + } +} + /// `own` is the reference's resolved transparency without its locked-layer fade: what ByBlock /// children inherit (a child fades only for its own layer). pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink, own: u8) { diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 934a033f6..22e194744 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -1,4 +1,4 @@ -use super::blocks::{insert, sub_ctx}; +use super::blocks::{insert, proxy, sub_ctx}; use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks}; use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT}; use super::props::{resolve, transparency}; @@ -240,12 +240,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { b.polyline(ctx, rgb, lw, l); } } - // An OLE object's content is not drawn; its frame, from its two corner points, is. - EntityKind::Unknown(u) if u.is_ole_frame() => { - if let Some(q) = cadcraft_doc::ole_frame(&u.tags) { - b.polyline(ctx, rgb, lw, &q); - } - } + EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => draw_unknown(b, ctx, e, u, rgb, lw, own), kind => { for prim in kind.prims() { match prim { @@ -302,6 +297,17 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade } } +/// A record kept as read that draws something: a proxy its proxy graphics, and an OLE object its +/// frame, from its two corner points (its content is not drawn). `own`: the proxy's transparency +/// without its locked-layer fade, for its graphics. +fn draw_unknown(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, rgb: Ink, lw: f32, own: u8) { + if !u.graphics.is_empty() { + proxy(b, ctx, e, u, own); + } else if let Some(q) = cadcraft_doc::ole_frame(&u.tags) { + b.polyline(ctx, rgb, lw, &q); + } +} + fn draw_image(b: &mut Builder, ctx: &Ctx, i: &cadcraft_doc::Image, rgb: Ink, lw: f32) { let o = i.insert.xy(); let u = i.u.xy() * i.size.x; diff --git a/crates/render/src/fill.rs b/crates/render/src/fill.rs index a659547ca..a6e56e550 100644 --- a/crates/render/src/fill.rs +++ b/crates/render/src/fill.rs @@ -3,6 +3,8 @@ use cadcraft_doc::LwPolyline; use cadcraft_geom::{MAX_TESSELLATED_POINTS, Polyline, Segment, Vec2}; +use crate::pen::MITER_LIMIT; + /// Triangulate an even-odd region bounded by closed loops (holes allowed) by cutting it into /// horizontal slabs at every vertex y and emitting trapezoids. Two edges that cross inside a slab /// (a bowtie, two loops crossing each other) swap order there, so such a slab is cut again at the @@ -141,6 +143,7 @@ pub fn wide_polyline(p: &LwPolyline, tol: f64) -> Vec { fn wide_polyline_within(p: &LwPolyline, tol: f64, budget: &mut usize) -> Vec { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; let mut out = Vec::new(); + let mut ends: Vec<(BandEnd, BandEnd)> = Vec::new(); let n = p.vertices.len(); for (i, seg) in pl.segments().iter().enumerate() { let v = p.vertices.get(i % n.max(1)).copied().unwrap_or_default(); @@ -151,7 +154,7 @@ fn wide_polyline_within(p: &LwPolyline, tol: f64, budget: &mut usize) -> Vec = None; + let mut edges = Vec::with_capacity(m); for (k, q) in pts.iter().enumerate() { let t = k as f64 / (m - 1) as f64; let w = (w0 + (w1 - w0) * t) / 2.0; @@ -160,15 +163,70 @@ fn wide_polyline_within(p: &LwPolyline, tol: f64, budget: &mut usize) -> Vec cadcraft_geom::EPS).then_some(())?; + Some(BandEnd { centre, toward, edge: *edges.get(c)?, inner_edge: *edges.get(inner)?, hw: w / 2.0 }) + }; + if let (Some(start), Some(finish)) = (end(0, 1, w0), end(m - 1, m - 2, w1)) { + ends.push((start, finish)); } } + // The corner at each vertex where one segment's band ends and the next one's starts. + for pair in ends.windows(2) { + if let [(_, arriving), (leaving, _)] = pair { + corner(&mut out, arriving, leaving); + } + } + if p.closed + && ends.len() > 1 + && let (Some(last), Some(first)) = (ends.last(), ends.first()) + { + corner(&mut out, &last.1, &first.0); + } out } +/// One end of a segment's band: its centre point and the sample next to it inside the segment, +/// with the band's edge points (left, right of the centre line) at both. +struct BandEnd { + centre: Vec2, + toward: Vec2, + edge: (Vec2, Vec2), + inner_edge: (Vec2, Vec2), + hw: f64, +} + +/// Fill the corner between the band arriving at `a` and the one leaving from `b`: their outer +/// edges are extended until they meet (a miter), or joined straight across (a bevel) when they +/// would meet further out than [`MITER_LIMIT`] half widths. Each edge keeps its own direction, +/// so tapered segments meet where their edges do. +fn corner(out: &mut Vec, a: &BandEnd, b: &BandEnd) { + let c = a.centre; + let (d0, d1) = ((a.centre - a.toward).normalized(), (b.toward - b.centre).normalized()); + let scale = a.hw.max(b.hw); + let turn = d0.cross(d1); + if scale <= 0.0 || turn.abs() <= 1e-12 { + return; // no width, or straight on (or straight back) + } + // The outer side of the turn: right of a left turn, left of a right turn. + let pick = |e: (Vec2, Vec2)| if turn > 0.0 { e.1 } else { e.0 }; + let (a0, a1, b0, b1) = (pick(a.inner_edge), pick(a.edge), pick(b.edge), pick(b.inner_edge)); + let miter = cadcraft_geom::line_line_infinite(a0, a1, b1, b0) + .filter(|&(tip, t, u)| t >= 1.0 - 1e-9 && u >= 1.0 - 1e-9 && tip.dist(c) <= MITER_LIMIT * scale); + match miter { + Some((tip, ..)) => out.extend_from_slice(&[c, a1, tip, c, tip, b0]), + None => out.extend_from_slice(&[c, a1, b0]), + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -310,6 +368,56 @@ pub(crate) mod tests { assert!(!tris.is_empty() && tris.len() <= 6 * (1000 + 4096 + 2 * 100), "{}", tris.len()); } + fn wide(points: &[(f64, f64)], closed: bool, width: f64) -> LwPolyline { + let vertices = points.iter().map(|&(x, y)| cadcraft_geom::PolyVertex::new(Vec2::new(x, y))).collect(); + LwPolyline { vertices, closed, const_width: width, elevation: 0.0, plinegen: false } + } + + /// Two segments of a wide polyline meet in a mitred corner: the outer corner of the bend is + /// filled, not left as a notch between the two segments (#3443). + #[test] + fn wide_polyline_corners_are_mitred() { + let tris = wide_polyline(&wide(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], false, 2.0), 0.01); + assert!(cover(&tris, Vec2::new(10.9, -0.9)) > 0); + // A closed polyline's corner at its first vertex is mitred too. + let tris = wide_polyline(&wide(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)], true, 2.0), 0.01); + assert!(cover(&tris, Vec2::new(-0.9, -0.9)) > 0); + // A repeated vertex (common in imported drawings) doesn't stop the corner. + let tris = wide_polyline(&wide(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)], false, 2.0), 0.01); + assert!(cover(&tris, Vec2::new(10.9, -0.9)) > 0); + } + + /// A tapered segment meets the next one along its own edges: the corner between a segment + /// ending 4 wide and one starting 2 wide is filled out to where those edges meet. + #[test] + fn tapered_corners_follow_the_segment_edges() { + let mut p = wide(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], false, 0.0); + for (v, w) in p.vertices.iter_mut().zip([4.0, 2.0]) { + (v.start_width, v.end_width) = (w, w); + } + let tris = wide_polyline(&p, 0.01); + // The first segment's outer edge is y = -2 and the second's x = 11: they meet at (11, -2). + assert!(cover(&tris, Vec2::new(10.9, -1.9)) > 0); + assert!(cover(&tris, Vec2::new(11.1, -1.9)) == 0); + } + + /// A corner sharper than the miter limit is bevelled instead of growing a long spike out past + /// the vertex. + #[test] + fn sharp_corners_are_bevelled() { + let tris = wide_polyline(&wide(&[(0.0, 0.0), (10.0, 0.0), (0.0, 0.5)], false, 2.0), 0.01); + let reach = tris.iter().map(|p| p.x).fold(f64::MIN, f64::max); + assert!(reach < 10.0 + MITER_LIMIT, "{reach}"); + } + + /// Straight on, no corner is added: the band covers each point once, so a translucent + /// polyline doesn't darken where its segments meet. + #[test] + fn straight_runs_add_no_corner() { + let tris = wide_polyline(&wide(&[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)], false, 2.0), 0.01); + assert!((area(&tris) - 20.0).abs() < 1e-9, "{}", area(&tris)); + } + #[test] fn degenerate_input() { assert!(triangulate_evenodd(&[vec![Vec2::ZERO, Vec2::X]]).is_empty()); diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs index d178cd5b9..b96180a23 100644 --- a/crates/render/src/hatch.rs +++ b/crates/render/src/hatch.rs @@ -684,6 +684,7 @@ mod tests { PolyVertex::new(Vec2::new(0.0, 10.0)), ], outer: true, + boundary_flags: None, sources: vec![], }; let loop2 = loop1.clone(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1adaaddd5..407b77b4a 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -438,7 +438,7 @@ pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, pub use pipeline::{Options, build, build_entities, build_plot}; use props::{default_lineweight, resolve_common}; use text_entity::text_style; -pub use text_entity::{layout_mtext_entity, place_text_entity, style_font, text_align}; +pub use text_entity::{fitted_text_entity, layout_mtext_entity, place_text_entity, style_font, text_align}; use viewports::{Clip, append_clipped_keep}; pub use viewports::{clip_list, viewport_clip, viewport_content}; diff --git a/crates/render/src/pen.rs b/crates/render/src/pen.rs index b639d0b73..f3b83af1b 100644 --- a/crates/render/src/pen.rs +++ b/crates/render/src/pen.rs @@ -59,7 +59,7 @@ pub const PATTERN_MM: f64 = 1.0; pub const MAX_PATTERN_CELLS: usize = 2_000_000; /// Miters longer than this many half widths are drawn bevelled (as PDF's default miter limit). -const MITER_LIMIT: f64 = 10.0; +pub(crate) const MITER_LIMIT: f64 = 10.0; /// Segments of a half circle (round ends and joins). const ROUND_STEPS: usize = 12; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 03c03459a..05fa53fa1 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -82,7 +82,7 @@ fn hatch_pattern_and_solid() { let h = Hatch { pattern: "ANSI31".into(), solid: false, - loops: vec![HatchLoop { vertices: sq.clone(), outer: true, sources: Vec::new() }], + loops: vec![HatchLoop { vertices: sq.clone(), outer: true, boundary_flags: None, sources: Vec::new() }], scale: 1.0, angle: 0.0, associative: false, @@ -514,7 +514,7 @@ fn pattern_hatch(pattern: &str, scale: f64, (x0, y0, x1, y1): (f64, f64, f64, f6 Hatch { pattern: pattern.into(), solid: false, - loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, sources: Vec::new() }], + loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, boundary_flags: None, sources: Vec::new() }], scale, angle: 0.0, associative: false, @@ -1299,7 +1299,8 @@ fn raster_hatch_pattern_matches_one_by_one() { #[test] fn ole_frame_draws_its_outline() { let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() }; - let frame = |tags: Vec| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let frame = + |tags: Vec| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() }); let mut d = Drawing::new_imperial(); 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, "1"), tag(20, "2")])).unwrap(); @@ -1333,6 +1334,51 @@ fn without_linetypes_every_line_is_drawn_whole() { assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len()); } +/// A proxy draws its proxy graphics like block contents: layer 0 and ByBlock in the picture are +/// the proxy's own, and the proxy's layer hides all of it. +#[test] +fn proxy_graphics_draw_like_block_contents() { + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "Notes".into(), color: Color::Index(3), ..Default::default() }); + let byblock = Common { color: Color::ByBlock, ..Default::default() }; + let graphics = vec![ + block_entity(7, byblock, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })), + block_entity( + 7, + Common { color: Color::Index(1), ..Default::default() }, + EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(15.0, 0.0, 0.0), radius: 5.0 }), + ), + ]; + let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics }); + d.add(&Space::Model, Common { layer: "Notes".into(), ..Default::default() }, proxy).unwrap(); + let l = build(&d, &Space::Model, &Options::default()); + assert_eq!(l.prims.iter().map(|p| p.color).collect::>(), [Rgb(0, 255, 0), Rgb(255, 0, 0)]); + let b = d.extents(&Space::Model); + assert!((b.min.x, b.max.x, b.max.y) == (0.0, 20.0, 5.0), "{b:?}"); + d.layer_mut("Notes").unwrap().frozen = true; + assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty()); +} + +/// On a locked layer, a proxy's graphics fade like a block's contents: layer 0 in the picture takes +/// the proxy's fade, a ByBlock part on an unlocked layer only the proxy's own transparency. +#[test] +fn proxy_graphics_on_a_locked_layer_fade_like_block_contents() { + use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent}; + for (own, want) in [(ByLayer, 0), (Percent(20), 20)] { + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() }); + d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() }); + let line = |x: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(x, 0.0, 0.0), b: Vec3::new(x + 1.0, 0.0, 0.0) }); + let graphics = vec![ + block_entity(7, Common::default(), line(0.0)), + block_entity(7, Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() }, line(2.0)), + ]; + let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics }); + d.add(&Space::Model, Common { layer: "Locked".into(), transparency: own, ..Default::default() }, proxy).unwrap(); + assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![50.max(want), want], "{own:?}"); + } +} + /// A broken table whose parts, with their repeated labels, together hold more cells than a table may /// lay out is drawn as its outline, though the table's own cells are within the limit. #[test] @@ -1371,7 +1417,7 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() { } } v.rotate_left(rot); - HatchLoop { vertices: v, outer: true, sources: Vec::new() } + HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() } }; let mut h = pattern_hatch("SOLID", 1.0, (0.0, 0.0, 1.0, 1.0)); h.loops = vec![ring(0, false), ring(2, false), ring(1, true), ring(3, true)]; @@ -1380,6 +1426,7 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() { h.loops.push(HatchLoop { vertices: ring(0, false).vertices.into_iter().map(|q| PolyVertex { bulge: 0.0, ..q }).collect(), outer: true, + boundary_flags: None, sources: Vec::new(), }); assert_eq!(loops_of(&h).len(), 2); diff --git a/crates/render/src/text_entity.rs b/crates/render/src/text_entity.rs index bcff8d4d8..417c1682d 100644 --- a/crates/render/src/text_entity.rs +++ b/crates/render/src/text_entity.rs @@ -13,6 +13,18 @@ pub fn style_font(ts: &cadcraft_doc::TextStyle) -> cadcraft_fonts::TextFont { /// Shape a TEXT / ATTRIB / ATTDEF with its style's font and generation flags. pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (cadcraft_fonts::Shaped, Bounds2) { + let (font, params) = text_params(d, t); + cadcraft_fonts::place(&font, value, ¶ms) +} + +/// The dimensions used to display a two-point TEXT, ATTRIB or ATTDEF, for file writers. +pub fn fitted_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> cadcraft_doc::Text { + let (font, params) = text_params(d, t); + let fitted = cadcraft_fonts::fit_params(&font, value, ¶ms); + cadcraft_doc::Text { height: fitted.height, rotation: fitted.rotation, width_factor: fitted.width_factor, ..t.clone() } +} + +fn text_params(d: &Drawing, t: &cadcraft_doc::Text) -> (cadcraft_fonts::TextFont, cadcraft_fonts::TextParams) { let ts = text_style(d, &t.style); let font = style_font(&ts); let (h, v) = align(t.halign, t.valign); @@ -28,7 +40,7 @@ pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (c backwards: ts.backwards, upside_down: ts.upside_down, }; - cadcraft_fonts::place(&font, value, &p) + (font, p) } /// Lay out an MTEXT with its style's font. diff --git a/crates/render/tests/it/hatch_fill.rs b/crates/render/tests/it/hatch_fill.rs index 894eb720b..1550e44b7 100644 --- a/crates/render/tests/it/hatch_fill.rs +++ b/crates/render/tests/it/hatch_fill.rs @@ -9,7 +9,7 @@ use cadcraft_render::{DisplayList, Kind, Options, build}; fn square(lo: f64, hi: f64) -> HatchLoop { let v = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(); - HatchLoop { vertices: v, outer: lo == 0.0, sources: Vec::new() } + HatchLoop { vertices: v, outer: lo == 0.0, boundary_flags: None, sources: Vec::new() } } fn hatch(pattern: &str, loops: Vec) -> Hatch { diff --git a/crates/ui-egui/src/attentry.rs b/crates/ui-egui/src/attentry.rs new file mode 100644 index 000000000..126227487 --- /dev/null +++ b/crates/ui-egui/src/attentry.rs @@ -0,0 +1,150 @@ +//! Edit Attributes: INSERT asks for its attribute values in one dialog when ATTDIA is 1 +//! ([`cadcraft_engine::Session::attribute_entry`]). OK answers INSERT's prompts in turn, Cancel +//! cancels the command; values typed at the command line still work, and the dialog goes away +//! after the first one. The draft, the window and its fields belong to the drawing and command +//! that asked for them, so an INSERT started after a cancel starts again from its own defaults +//! and takes no confirmation meant for the dialog it replaced. + +use egui::{RichText, vec2}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The values being edited, for the drawing and command that asked for them. +#[derive(Clone)] +struct State { + /// The drawing and the command instance ([`cadcraft_engine::AttribEntry`]): a draft made for + /// one command is never used by another, even for the same block. + drawing: u64, + command: u64, + block: String, + values: Vec, + /// The first field has had the keyboard focus once. + focused: bool, + /// When this owner's dialog appeared ([`egui::InputState::time`]): it takes no answer before + /// it has been drawn once, so a click or key meant for the dialog it replaced cannot confirm + /// values nobody has seen. + shown_at: f64, +} + +impl State { + /// Whether this draft is the one `entry` asks for. + fn owns(&self, entry: &cadcraft_engine::AttribEntry) -> bool { + self.drawing == entry.drawing && self.command == entry.command && self.block == entry.block && self.values.len() == entry.rows.len() + } +} + +fn state_id() -> egui::Id { + egui::Id::unique("attentry_state") +} + +/// The dialog's window id, with the drawing and command it belongs to: the window and every +/// widget in it are new for a replacement command, so a press on the old dialog's OK never ends +/// on the new one, and no focus, keyboard or scroll state carries over. +fn window_id(entry: &cadcraft_engine::AttribEntry) -> egui::Id { + egui::Id::unique(("Edit Attributes", entry.drawing, entry.command)) +} + +enum Done { + No, + Ok, + Cancel, +} + +/// Show the dialog while INSERT waits for attribute values with ATTDIA 1. +pub fn show(app: &mut CadApp, ctx: &egui::Context) { + let Some(entry) = app.session.attribute_entry() else { + ctx.data_mut(|d| d.remove::(state_id())); + return; + }; + let t = Tokens::get(); + let now = ctx.input(|i| i.time); + let mut st = match ctx.data_mut(|d| d.get_temp::(state_id())).filter(|s| s.owns(&entry)) { + Some(st) => st, + None => { + // A command (or drawing) replaced the dialog between frames. Nothing queued for the old + // one — a click or key waiting in the app's synthetic input — is the replacement's: its + // dialog has not been drawn yet, and its own defaults are what OK submits. + app.synthetic.clear(); + State { + drawing: entry.drawing, + command: entry.command, + block: entry.block.clone(), + values: entry.rows.iter().map(|r| r.default.clone()).collect(), + focused: false, + shown_at: now, + } + } + }; + // No answer before the dialog has been drawn for this owner: whatever was confirmed was + // confirmed at the dialog this one replaced. + let fresh = st.shown_at == now; + let mut done = Done::No; + let st_focused = st.focused; + st.focused = true; + egui::Window::new(crate::tl!("Edit Attributes")) + .id(window_id(&entry)) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Block name:")); + ui.label(RichText::new(&entry.block).strong()); + }); + ui.separator(); + egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| { + egui::Grid::new("attentry_grid").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { + for (i, (row, value)) in entry.rows.iter().zip(st.values.iter_mut()).enumerate() { + let shown = if row.prompt.is_empty() { row.tag.as_str() } else { row.prompt.as_str() }; + let label = ui.label(shown).on_hover_text(crate::tf!("Tag: {tag}", tag = row.tag)); + let field = egui::TextEdit::singleline(value) + .id(egui::Id::unique(("attentry_value", entry.drawing, entry.command, i))) + .desired_width(220.0); + let resp = ui.add(field).labelled_by(label.id); + if i == 0 && !st_focused { + resp.request_focus(); + } + // Enter in a field is OK, the dialog's default button. + if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + done = Done::Ok; + } + ui.end_row(); + } + }); + }); + ui.separator(); + ui.horizontal(|ui| { + if ui.button(crate::tl!("OK")).clicked() { + done = Done::Ok; + } + if ui.button(crate::tl!("Cancel")).clicked() { + done = Done::Cancel; + } + ui.label(RichText::new(crate::tl!("Values typed at the command line work too")).small().color(t.text_dim)); + }); + }); + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + done = Done::Cancel; + } + if fresh { + done = Done::No; + } + match done { + Done::No => { + ctx.data_mut(|d| d.insert_temp(state_id(), st)); + } + Done::Ok => { + ctx.data_mut(|d| d.remove::(state_id())); + for a in entry.answers(&st.values) { + if app.session.input(cadcraft_engine::Input::Text(a)).is_err() { + break; + } + } + } + Done::Cancel => { + ctx.data_mut(|d| d.remove::(state_id())); + app.session.cancel(); + } + } +} diff --git a/crates/ui-egui/src/blocks_palette.rs b/crates/ui-egui/src/blocks_palette.rs index 3cb43a61c..ec9796d74 100644 --- a/crates/ui-egui/src/blocks_palette.rs +++ b/crates/ui-egui/src/blocks_palette.rs @@ -1562,7 +1562,7 @@ mod tests { let d = Drawing::new_metric(); assert!(too_much(&d, EntityKind::Wipeout(Wipeout { boundary: points.clone() }))); assert!(too_much(&d, EntityKind::MLine(MLine::new(&MLineStyle::default(), &points, false, MLineJust::default(), 1.0)))); - let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }] }; + let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: None, sources: Vec::new() }] }; assert!(too_much(&d, EntityKind::Region(region))); // An object with nothing in it still takes a visit, for each cell of an array. let mut empty = Block::new("EMPTY"); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8aa940ea0..51f494d22 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -557,8 +557,12 @@ fn paint_pointer_overlay(frame: &mut CanvasPaint<'_>, paper_rect: Option, draw_viewcube(app, ui, rect); } viewport_label(painter, rect); - // Typing and Escape reach the command line even when its overlay is hidden. - crate::cmdline::keyboard(app, ui.ctx()); + // Typing and Escape reach the command line even when its overlay is hidden, unless the + // inline constraint editor already handled this frame's keys (Enter would otherwise repeat + // `last_command`, e.g. immediately undoing the edit after Cmd+Z). + if !crate::parametric::take_keyboard(app) { + crate::cmdline::keyboard(app, ui.ctx()); + } // Command line overlay. if app.ui.show_command_line { crate::cmdline::show(app, ui, full); @@ -1201,6 +1205,8 @@ fn paint_canvas(frame: CanvasPaint<'_>) { }; let p = painter.with_clip_rect(clip); crate::parametric::draw_overlay(app, ui, &p, &xf); + } else { + crate::parametric::dismiss_inline(app, ui.ctx()); } // Grips on selected objects (when idle or editing grips). let grip_edit = app.session.running.as_ref().is_some_and(|r| r.id == "grip"); diff --git a/crates/ui-egui/src/canvas/dyn_boxes.rs b/crates/ui-egui/src/canvas/dyn_boxes.rs index b0bcfb9e2..783cfce7b 100644 --- a/crates/ui-egui/src/canvas/dyn_boxes.rs +++ b/crates/ui-egui/src/canvas/dyn_boxes.rs @@ -19,6 +19,19 @@ pub(super) fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2, fi // DYNPROMPT = 0: no prompt beside the cursor (the value boxes stay). let show_prompt = app.session.settings.dynprompt; let options = show_prompt && !prompt.keywords.is_empty(); + // An angle about the base (a rotation grip): one angle box, as AutoCAD shows it. + if !fields + && prompt.angle + && crate::cmdline::dyn_frame(app).is_some() + && let Some(c) = app.canvas.cursor + { + let message = if show_prompt { crate::i18n::t(&prompt.message) } else { "" }; + let typed = !app.cmd.buffer.is_empty(); + let value = if typed { app.cmd.buffer.clone() } else { app.session.live_value(c).unwrap_or_default() }; + let r = angle_box(p, at, message, &value, typed, options); + options_menu(app, p, r, hover); + return; + } if !fields && let Some(f) = crate::cmdline::dyn_frame(app) && let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f) @@ -119,6 +132,37 @@ fn tooltip_frame(p: &egui::Painter, at: Pos2, size: egui::Vec2) -> Rect { r } +/// The Dynamic Input tooltip for an angle: the prompt and one box, holding what was typed (full +/// text colour, with the caret) or the live value (dimmed). +fn angle_box(p: &egui::Painter, at: Pos2, message: &str, value: &str, typed: bool, options: bool) -> Rect { + let t = Tokens::get(); + let font = crate::theme::small(); + let msg = p.layout_no_wrap(message.to_owned(), font.clone(), t.text_dim); + let val = p.layout_no_wrap(value.to_owned(), font, if typed { t.text } else { t.text_faint }); + let (pad, gap) = (6.0, 6.0); + let box_h = msg.size().y + 6.0; + let bw = (val.size().x + 10.0).max(48.0); + let hint = if options { OPTIONS_HINT_W } else { 0.0 }; + let r = tooltip_frame(p, at, vec2(pad + msg.size().x + gap + bw + pad + hint, box_h + 2.0 * pad - 2.0)); + if options { + options_hint(p, r); + } + let cy = r.center().y; + let x = r.left() + pad; + let msg_w = msg.size().x; + p.galley(pos2(x, cy - msg.size().y / 2.0), msg, t.text_dim); + let b = Rect::from_min_size(pos2(x + msg_w + gap, cy - box_h / 2.0), vec2(bw, box_h)); + p.rect_filled(b, 2.0, t.chrome_dark); + p.rect_stroke(b, 2.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + let vw = val.size().x; + p.galley(pos2(b.left() + 5.0, cy - val.size().y / 2.0), val, t.text); + if typed { + let cx = b.left() + 6.0 + vw; + p.line_segment([pos2(cx, b.top() + 3.0), pos2(cx, b.bottom() - 3.0)], Stroke::new(1.0, t.text)); + } + r +} + /// The Dynamic Input value boxes: X and Y, or distance and angle. Typed values show in full /// text colour, a locked value (a separator typed after it) gets a lock, the active box gets the /// accent outline, and open boxes show the cursor's live value, dimmed. Values measured from the diff --git a/crates/ui-egui/src/canvas/press.rs b/crates/ui-egui/src/canvas/press.rs index 0cffb8cb8..731bffd41 100644 --- a/crates/ui-egui/src/canvas/press.rs +++ b/crates/ui-egui/src/canvas/press.rs @@ -2,10 +2,11 @@ //! the spot where it went down, however fast the mouse is moving. Where the pointer goes while the //! button is held only decides whether the press also becomes a drag: //! -//! - holding still, or staying within [`TOLERANCE`] of the press, never makes a drag; +//! - holding still, or staying within the press tolerance, never makes a drag; //! - once the pointer leaves the tolerance a timer starts; a button still down [`DRAG_DELAY`] //! later is a drag (a selection window the press opened closes where the button comes up); -//! - a button that comes up sooner was a click (the window waits for the next press). +//! - returning within the selection-window tolerance resets the timer; a button that comes up +//! there or before the delay was a click (the window waits for the next press). //! //! The timer starts on leaving the tolerance, not on the press: pressing, holding still and then //! moving and letting go quickly is still a click, as in AutoCAD. @@ -18,15 +19,16 @@ use egui::{Modifiers, Pos2}; /// How far (points) the pointer may wander from the press before the timer starts. pub(crate) const TOLERANCE: f32 = 6.0; -/// How long (seconds) the button must stay down after the pointer left [`TOLERANCE`] for the -/// press to be a drag. +/// Extra room to click the first corner of a window without committing it by accident. +const WINDOW_TOLERANCE: f32 = 12.0; +/// How long (seconds) the button must stay down outside the tolerance for the press to be a drag. pub(crate) const DRAG_DELAY: f64 = 0.25; /// A primary-button press being held. #[derive(Clone, Copy, Debug)] pub(crate) struct Press { origin: Pos2, - /// When the pointer first went further than [`TOLERANCE`] from `origin` (seconds). + /// When the pointer went outside the press tolerance (seconds). left_at: Option, /// The press opened a selection window (set its first corner). pub(crate) opened_window: bool, @@ -60,8 +62,11 @@ impl Press { /// The pointer is at `pos` at time `now`. pub(crate) fn moved(&mut self, pos: Pos2, now: f64) { - if self.left_at.is_none() && pos.distance(self.origin) > TOLERANCE { - self.left_at = Some(now); + let tolerance = if self.opened_window { WINDOW_TOLERANCE } else { TOLERANCE }; + if pos.distance(self.origin) > tolerance { + self.left_at.get_or_insert(now); + } else if self.opened_window { + self.left_at = None; } } @@ -109,7 +114,7 @@ mod tests { #[test] fn letting_go_soon_after_leaving_the_tolerance_is_a_click() { let mut p = Press::new(pos2(100.0, 100.0), true); - p.moved(pos2(112.0, 100.0), 1.0); + p.moved(pos2(115.0, 100.0), 1.0); assert!(!p.released_as_drag(pos2(130.0, 100.0), 1.0 + DRAG_DELAY / 2.0)); } @@ -124,7 +129,7 @@ mod tests { #[test] fn a_button_still_down_after_the_delay_is_a_drag() { let mut p = Press::new(pos2(100.0, 100.0), true); - p.moved(pos2(110.0, 100.0), 1.0); + p.moved(pos2(115.0, 100.0), 1.0); p.moved(pos2(200.0, 150.0), 1.1); assert!(p.released_as_drag(pos2(250.0, 160.0), 1.0 + DRAG_DELAY)); } diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index fa7c61808..77b333105 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -536,7 +536,13 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) { let left = Rect::from_min_size(r.min, vec2(300.0, r.height())); p.rect_filled(left, 0.0, t.chrome_dark); p.rect_filled(Rect::from_min_max(pos2(left.right(), r.top()), r.max), 0.0, t.chrome); - p.text(pos2(left.left() + 34.0, left.top() + 70.0), egui::Align2::LEFT_CENTER, crate::tl!("CADCraft"), egui::FontId::proportional(28.0), t.text); + p.text( + pos2(left.left() + 34.0, left.top() + 70.0), + egui::Align2::LEFT_CENTER, + crate::os_window::drawn_name(), + egui::FontId::proportional(28.0), + t.text, + ); p.text( pos2(left.left() + 34.0, left.top() + 98.0), egui::Align2::LEFT_CENTER, diff --git a/crates/ui-egui/src/clipboard.rs b/crates/ui-egui/src/clipboard.rs index 69070f4fb..4f775567d 100644 --- a/crates/ui-egui/src/clipboard.rs +++ b/crates/ui-egui/src/clipboard.rs @@ -8,6 +8,7 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use cadcraft_engine::cmd::clipboard; +use cadcraft_engine::{CommandSpec, Session}; use crate::CadApp; @@ -53,14 +54,187 @@ pub fn shortcut_commands(app: &mut CadApp, ctx: &egui::Context) -> Vec<&'static egui::Event::Copy => out.push(if shift { "copybase" } else { "copyclip" }), egui::Event::Cut => out.push("cutclip"), egui::Event::Paste(text) => { + // The oldest request sent in an earlier frame and still unanswered gets this + // `Paste`. It completes the held command only if the command asked for that + // request; otherwise it answers one whose command is gone and pastes nothing. With + // no such request it is an ordinary Ctrl+V. + let answered = app.paste.sent.first().filter(|r| r.frame < app.paste.frame).map(|r| r.id); + if answered.is_some() { + app.paste.sent.remove(0); + } + let mine = app.paste.wait.as_ref().is_some_and(|(_, id, _)| answered == Some(*id)); + let held = if mine { app.paste.wait.take().map(|(p, _, _)| p) } else { None }; + // The text is the system clipboard's either way, so a stale answer still counts. let h = hash(&text); if ctx.data(|d| d.get_temp::(text_id())) != Some(h) && clipboard::load_system_text(&mut app.session, &text) { ctx.data_mut(|d| d.insert_temp(text_id(), h)); } - out.push(if shift { "pasteblock" } else { "pasteclip" }); + if held.is_none() && answered.is_some() { + continue; + } + // A paste asked for from a menu or the command line is the command that was held. + match held { + Some(p) if p.line.is_some() => run_now(app, p), + Some(p) => out.push(p.id), + None => out.push(if shift { "pasteblock" } else { "pasteclip" }), + } } _ => {} } } out } + +/// How long a menu, context menu or typed paste waits for the window to deliver the system +/// clipboard before it pastes what this window already holds (the clipboard holds no text, or an +/// image, and then no `Paste` ever arrives). +const WAIT_SECS: f64 = 0.5; + +/// How long the Wayland backend may take to answer a `RequestPaste`. Its read starts after the +/// frame that queued the request has been painted and is given 3 s from then (`DELIVERY_BUDGET`, +/// egui-winit `clipboard_bridge.rs`, counted from `begin_regular`); an answer later than that +/// never comes. The 2 s of margin over the budget cover that painting and the frame that +/// delivers the answer, which are not bounded. +const ANSWER_SECS: f64 = 5.0; + +/// Whether this build can ask the window for the system clipboard on demand. The web build gets +/// a `Paste` only from the browser's own paste gesture, so it keeps pasting what the window holds. +const ON_DEMAND: bool = cfg!(not(target_arch = "wasm32")); + +/// A paste command asked for outside the keyboard, held until the system clipboard has been read. +struct Pending { + id: &'static str, + /// The command line text it was typed as, when it was. + line: Option, +} + +/// Paste commands waiting for the system clipboard ([`defer`], [`pump`]). +pub struct Paste { + /// Asked for this frame; the window has not been asked for the clipboard yet. + request: Option, + /// Asked for the clipboard; its `Paste` event, or the time to give up. + /// The held command, the request it asked for ([`Sent::id`]), and the time to give up. + wait: Option<(Pending, u64, f64)>, + /// A held command is being run now, and must not be held again. + pub(crate) running: bool, + /// The `RequestPaste`s that may still be answered, oldest first. A `Paste` answers the oldest, + /// so one that arrives after its command was escaped or gave up is not taken for a paste of + /// its own, nor for the answer to a newer request. + sent: Vec, + next_id: u64, + /// Frames pumped so far. + frame: u64, + /// Whether the window may answer later than the next frame (native Wayland), see + /// [`Self::set_late_answers`]. + late: bool, +} + +/// A `RequestPaste` that may still be answered. +struct Sent { + id: u64, + /// The frame it was sent in; its answer is in a later frame's input. + frame: u64, + /// When it stops being answerable on a window that answers late. + until: f64, +} + +impl Default for Paste { + fn default() -> Self { + Paste { request: None, wait: None, running: false, sent: Vec::new(), next_id: 0, frame: 0, late: true } + } +} + +impl Paste { + /// Say whether the window may answer a request later than the next frame. egui-winit reads + /// the clipboard when it handles the command, right after the frame that sent it is painted, + /// and the text is in the next frame's input (`request_paste`, `begin_regular_clipboard_paste` + /// and `take_egui_input`), or nothing comes when there is no text; only its Wayland backend + /// reads asynchronously. A request is then answerable for one frame, not for seconds, so a + /// Ctrl+V after it is never taken for its answer. On Wayland that Ctrl+V within + /// [`ANSWER_SECS`] of a request that got no answer is, once, taken for it. + pub fn set_late_answers(&mut self, late: bool) { + self.late = late; + } + + /// Drop a held paste (Escape, or another command started). A request already sent to the + /// window stays in `sent`, so its answer, if it comes, pastes nothing. + pub fn cancel(&mut self) { + self.request = None; + self.wait = None; + } +} + +pub(crate) fn paste_id(id: &str) -> Option<&'static str> { + ["pasteclip", "pasteblock", "pasteorig"].into_iter().find(|p| *p == id) +} + +/// Whether the menus offer `spec`. The paste commands count as available while a drawing is open +/// and nothing was copied in this window, since the system clipboard may hold DXF text +/// copied in another one; they report an empty clipboard when they run and it does not. +pub fn offered(session: &Session, spec: &CommandSpec) -> bool { + (spec.enabled)(session).is_ok() || (ON_DEMAND && paste_id(spec.id).is_some() && session.clipboard.is_empty() && session.doc().is_ok()) +} + +/// Hold the paste command `id` (typed as `line`, if it was) until the system clipboard has been +/// read, so the newest of this window's clipboard and the system's is pasted. `false` when the +/// command runs right away: not a paste, a build that cannot ask, or already read. +pub fn defer(app: &mut CadApp, id: &str, line: Option<&str>) -> bool { + let Some(id) = paste_id(id).filter(|_| ON_DEMAND && !app.paste.running) else { return false }; + app.paste.cancel(); + app.paste.request = Some(Pending { id, line: line.map(str::to_string) }); + true +} + +/// Run a held command, or `id` from a `Paste` event, without holding it again. +fn run_now(app: &mut CadApp, p: Pending) { + app.paste.running = true; + match p.line { + Some(line) => { + app.cmdline(&line); + } + None => { + app.cmd.buffer.clear(); + app.start(p.id); + } + } + app.paste.running = false; +} + +/// Run `id`, a paste command whose `Paste` event has been read. +pub fn run_read(app: &mut CadApp, id: &'static str) { + run_now(app, Pending { id, line: None }); +} + +/// Once per frame: ask the window for the system clipboard for a newly held paste, and give up on +/// one it never delivered. The text arrives as a `Paste` event ([`shortcut_commands`]). +pub fn pump(app: &mut CadApp, ctx: &egui::Context) { + let (now, pasted) = ctx.input(|i| (i.time, i.events.iter().any(|e| matches!(e, egui::Event::Paste(_))))); + if ctx.current_pass_index() == 0 { + app.paste.frame += 1; + } + let (frame, late) = (app.paste.frame, app.paste.late); + app.paste.sent.retain(|r| if late { r.until > now } else { r.frame + 1 >= frame }); + if let Some(p) = app.paste.request.take() { + // A focused text field would take the `Paste` itself. + if ctx.egui_wants_keyboard_input() { + run_now(app, p); + } else { + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste); + let id = app.paste.next_id; + app.paste.next_id += 1; + app.paste.sent.push(Sent { id, frame, until: now + ANSWER_SECS }); + ctx.request_repaint_after_secs(WAIT_SECS as f32); + app.paste.wait = Some((p, id, now + WAIT_SECS)); + } + } + // A request that can no longer be answered, or the time to give up, ends the wait; a `Paste` + // in this frame completes the held command first ([`shortcut_commands`]). + let gone = |app: &CadApp| app.paste.wait.as_ref().is_some_and(|(_, id, _)| !app.paste.sent.iter().any(|r| r.id == *id)); + if (gone(app) || (!pasted && app.paste.wait.as_ref().is_some_and(|(_, _, deadline)| now >= *deadline))) + && let Some((p, _, _)) = app.paste.wait.take() + { + run_now(app, p); + } else if app.paste.wait.is_some() && !late { + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 53a15a784..1059f2756 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -425,6 +425,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { /// What Escape does, and the right-click or menu "Cancel" that stand for it: what was typed so far /// goes, and so does the running command. pub fn escape(app: &mut CadApp) { + app.paste.cancel(); app.cmd.buffer.clear(); app.cmd.preedit.clear(); app.session.cancel(); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 62aedc1a6..7f49e75b5 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -71,7 +71,7 @@ fn item(app: &CadApp, id: &str, label: Option<&str>) -> Option { label: label.unwrap_or(spec.label).to_string(), id: id.to_string(), shortcut: spec.shortcut.map(str::to_string), - enabled: (spec.enabled)(&app.session).is_ok(), + enabled: crate::clipboard::offered(&app.session, spec), }) } @@ -97,14 +97,19 @@ pub fn entries(app: &CadApp) -> Vec> { let mut first = Vec::new(); if let Some(last) = app.session.last_command.as_deref().and_then(find_command) { let label = crate::tf!("Repeat {command}", command = last.id.to_ascii_uppercase()); - first.push(Entry::Item { label, id: last.id.to_string(), shortcut: None, enabled: (last.enabled)(&app.session).is_ok() }); + first.push(Entry::Item { label, id: last.id.to_string(), shortcut: None, enabled: crate::clipboard::offered(&app.session, last) }); } let recent: Vec = app .session .recent_commands(RECENT) .iter() .filter_map(|id| find_command(id)) - .map(|c| Entry::Item { label: c.id.to_ascii_uppercase(), id: c.id.to_string(), shortcut: None, enabled: (c.enabled)(&app.session).is_ok() }) + .map(|c| Entry::Item { + label: c.id.to_ascii_uppercase(), + id: c.id.to_string(), + shortcut: None, + enabled: crate::clipboard::offered(&app.session, c), + }) .collect(); first.extend(sub("Recent Commands", recent)); push(&mut groups, first); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 052b6e17d..d89dd33c8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -358,6 +358,7 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) - let before = app.session.log.len(); let error = match s("key").unwrap_or("enter").to_ascii_lowercase().as_str() { "escape" | "esc" => { + app.paste.cancel(); app.session.cancel(); None } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 127e786c0..f7c1c8eba 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -10,6 +10,7 @@ use crate::theme::Tokens; pub fn show(app: &mut CadApp, ctx: &egui::Context) { crate::mtext_editor::show(app, ctx); + crate::attentry::show(app, ctx); crate::line_editor::show(app, ctx); crate::quick::quick_properties(app, ctx); let Some(d) = app.ui.dialog.clone() else { return }; @@ -32,6 +33,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "commands" => commands(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), + "wblock" => crate::wblock::dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), o if o == "options" || o.starts_with("options:") => crate::options::dialog(app, ctx, o, &mut open), o if o.starts_with("textedit:") => crate::textdlg::dialog(app, ctx, o, &mut open), @@ -353,7 +355,8 @@ fn about(ctx: &egui::Context, open: &mut bool) { 1 => crate::credits::contributors_ui(ui), 2 => crate::credits::models_ui(ui), _ => { - ui.heading(crate::tl!("CADCraft")); + // The channel name, so a Nightly bug report names the channel it came from. + ui.heading(crate::os_window::drawn_name()); ui.label(crate::tf!("Version {version}", version = env!("CARGO_PKG_VERSION"))); ui.label(crate::tl!("Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust.")); ui.add_space(6.0); diff --git a/crates/ui-egui/src/dyngrips.rs b/crates/ui-egui/src/dyngrips.rs index b00335126..62d8015b4 100644 --- a/crates/ui-egui/src/dyngrips.rs +++ b/crates/ui-egui/src/dyngrips.rs @@ -1,7 +1,9 @@ //! Dynamic block grips on the canvas, as AutoCAD shows them on a selected dynamic block //! reference: an arrow at a distance's end (drag it to change the distance), a square at a -//! position (drag it to move it) and a down-pointing triangle for a list (click it for the -//! visibility states or lookup values). Dragging runs the engine's dynamic grip edit +//! position (drag it to move it), a circle at an angle's end (drag it to turn), an arrow across a +//! reflection line (click it to flip), a down-pointing triangle for a list (click it for the +//! visibility states or lookup values) and a pentagon at an alignment's base point (drag it next to +//! an object to align the reference with it). Dragging runs the engine's dynamic grip edit //! ([`cadcraft_engine::Session::start_dyn_grip`]); a list choice runs `blocks.reference.set`. use std::sync::Arc; @@ -64,6 +66,37 @@ fn outline(xf: &Xf, g: &DynGrip, gs: f32) -> Vec { let w = gs * 1.3; vec![c + vec2(-w, -w * 0.6), c + vec2(w, -w * 0.6), c + vec2(0.0, w * 0.9)] } + GripShape::Rotation => (0..16) + .map(|i| { + let a = std::f32::consts::TAU * i as f32 / 16.0; + c + vec2(a.cos(), a.sin()) * (gs * 1.1) + }) + .collect(), + // An arrow pointing across the reflection line, the way it flips. + GripShape::Flip => { + let ahead = xf.to_screen(g.at + g.dir) - c; + let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) }; + let n = vec2(-u.y, u.x); + // A block arrow, as AutoCAD draws it: a short shaft and a head about as wide as a + // square grip. Tail, shaft's end and head's back on one side, the tip, then back. + let (tail, neck, tip, shaft, head) = (gs * 1.4, gs * 0.2, gs * 1.4, gs * 0.5, gs * 1.4); + vec![ + c - u * tail + n * shaft, + c - u * neck + n * shaft, + c - u * neck + n * head, + c + u * tip, + c - u * neck - n * head, + c - u * neck - n * shaft, + c - u * tail - n * shaft, + ] + } + // A square with a point on the side the grip points to (across the alignment direction). + GripShape::Alignment => { + let ahead = xf.to_screen(g.at + g.dir) - c; + let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) }; + let n = vec2(-u.y, u.x); + vec![c - u * gs - n * gs, c + u * (gs * 0.2) - n * gs, c + u * (gs * 1.4), c + u * (gs * 0.2) + n * gs, c - u * gs + n * gs] + } } } @@ -93,7 +126,18 @@ pub(crate) fn draw(app: &mut CadApp, painter: &Painter, xf: &Xf, rect: Rect, hov } else { t.grip_dyn }; - painter.add(Shape::convex_polygon(pts, fill, Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)))); + let stroke = Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)); + match (g.shape, pts.as_slice()) { + // The flip arrow isn't convex: its shaft and head are filled apart, then outlined. + (GripShape::Flip, [t0, n0, h0, tip, h1, n1, t1]) => { + painter.add(Shape::convex_polygon(vec![*t0, *n0, *n1, *t1], fill, Stroke::NONE)); + painter.add(Shape::convex_polygon(vec![*h0, *tip, *h1], fill, Stroke::NONE)); + painter.add(Shape::closed_line(pts.clone(), stroke)); + } + _ => { + painter.add(Shape::convex_polygon(pts, fill, stroke)); + } + } } } @@ -106,6 +150,22 @@ pub(crate) fn at(app: &mut CadApp, xf: &Xf, hover: Option) -> Option<(Hand /// A click on dynamic grip `g` of reference `h`: drag it, or open its list. pub(crate) fn click(app: &mut CadApp, (h, g): (Handle, DynGrip)) { + // A flip grip flips at once: the state that isn't the current one. + if g.shape == GripShape::Flip { + let current = app + .session + .state() + .ok() + .and_then(|st| cadcraft_engine::doc::dynblock::custom_properties(&st.doc, h)) + .and_then(|(_, ps)| ps.into_iter().find(|p| p.name.eq_ignore_ascii_case(&g.property))) + .map(|p| p.value) + .unwrap_or_default(); + let Some(next) = g.choices.iter().find(|c| !c.eq_ignore_ascii_case(¤t)).cloned() else { return }; + if let Err(e) = app.run("blocks.reference.set", json!({ "handle": h.hex(), "name": g.property, "value": next })) { + app.session.echo(e); + } + return; + } if g.shape == GripShape::List { app.canvas.dyn_menu = Some((h, g)); app.canvas.dyn_menu_fresh = true; diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 0f0362482..10caa9069 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -406,7 +406,7 @@ Grip Option خيار المقبض Grip Rotate تدوير بالمقبض Grip Scale تحجيم بالمقبض - Grip Stretch تمديد بالمقبض + Grip Stretch تمطيط بالمقبض Grip size حجم المقبض Group تجميع Group Edit تحرير المجموعة @@ -703,7 +703,7 @@ Plotter Manager مدير الطابعات Plotter Manager... مدير الطابعات... Plus/minus زائد/ناقص - Point تأشير + Point نقطة Point Filters مرشحات النقطة Point Style... نمط النقطة... Polar (distance < angle) قطبي (المسافة < الزاوية) @@ -872,15 +872,15 @@ Select object حدد كائناً Select object to dimension حدد كائناً لتأشيره Select object to divide حدد كائناً لتقسيمه - Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للقص + Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للتشذيب Select object to measure حدد كائناً لقياسه Select object to offset حدد كائناً لإزاحته - Select object to trim or shift-select to extend حدد كائناً لقصه أو حدد مع Shift للتمديد + Select object to trim or shift-select to extend حدد كائناً لتشذيبه أو حدد مع Shift للتمديد Select objects حدد كائنات Select objects (crossing window first corner) حدد كائنات (الزاوية الأولى لنافذة التقاطع) Select objects first, then choose a command حدد الكائنات أولاً ثم اختر أمراً Select objects to array. حدد كائنات لتكوين مصفوفة. - Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمديدها بنافذة التقاطع أو مضلع التقاطع... + Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمطيطها بنافذة التقاطع أو مضلع التقاطع... Select objects: حدد كائنات: Select one polyline (Multiple is available through the JSON form). حدد متعدد خطوط واحداً (يتوفر الوضع المتعدد عبر نموذج JSON). Select path curve حدد منحنى المسار @@ -1084,8 +1084,8 @@ Start, End, Radius بداية، نهاية، نصف قطر Status الحالة Status Bar شريط الحالة - Stretch تمديد - Stretch Vertex تمديد رأس + Stretch تمطيط + Stretch Vertex تمطيط رأس Style: Standard النمط: Standard Subtract طرح Sweep كنس @@ -1134,7 +1134,7 @@ Track orthogonally only تعقب متعامد فقط Track using all polar angle settings تعقب باستخدام كل إعدادات الزوايا القطبية Transparency شفافية - Trim حدود التشذيب + Trim تشذيب True Color لون حقيقي Turn All Layers On تشغيل كل الطبقات Turn Off Layer إيقاف طبقة diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 23836de6d..f5484818e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1,4 +1,4 @@ -# CADCraft French interface catalog — original translations by @pechnikov2026-star. +# CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81. # License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE). # Written from CADCraft's English strings; no proprietary translations were copied. # UTF-8: contextEnglish sourceFrench translation. @@ -160,7 +160,7 @@ Delete Supprimer Delete Column Supprimer la colonne Delete Constraints Supprimer les contraintes - Delete Dimension Style Supprimer le style de cotation + Delete Dimension Style Supprimer le style de cote Delete Duplicate Objects Supprimer les objets en double Delete Layer Supprimer le calque Delete Layer State Supprimer l'état des calques @@ -172,17 +172,17 @@ Description Description Deselect All Désélectionner tout Diameter Diamètre - Dim style Style de cotation + Dim style Style de cote Dimension Cotation - Dimension Space Espace entre cotations - Dimension Style Override Substitution de style de cotation - Dimension Style... Style de cotation... - Dimension Text Edit Modifier le texte de cotation - Dimension style Style de cotation + Dimension Space Espacer les cotes + Dimension Style Override Remplacement de style de cote + Dimension Style... Style de cote... + Dimension Text Edit Modifier le texte de cote + Dimension style Style de cote Dimensional Constraint Contrainte dimensionnelle Dimensional Constraint Parameters Paramètres de contraintes dimensionnelles Dimensional Constraints Contraintes dimensionnelles - Disassociate Dimensions Dissocier les cotations + Disassociate Dimensions Dissocier les cotes Display name Nom d'affichage Distance Distance Divide Diviser @@ -200,7 +200,7 @@ Drawing Limits Limites du dessin Drawing Utilities Utilitaires de dessin Drawings (DWG, DXF) Dessins (DWG, DXF) - Dynamic Dimensions Cotations dynamiques + Dynamic Dimensions Cotes dynamiques Dynamic Input Saisie dynamique Dynamic Input (F12) Saisie dynamique (F12) E Est @@ -233,9 +233,9 @@ Enter degree of spline Entrez le degré de la spline Enter delta angle Entrez l'écart d'angle Enter delta length Entrez l'écart de longueur - Enter dimension text Entrez le texte de cotation - Enter dimension text (<> = measurement) Entrez le texte de cotation (<> = mesure) - Enter dimension value or [name=expression] Entrez la valeur de cotation ou [name=expression] + Enter dimension text Entrez le texte de cote + Enter dimension text (<> = measurement) Entrez le texte de cote (<> = mesure) + Enter dimension value or [name=expression] Entrez la valeur de cote ou [name=expression] Enter dimension variable name to override Entrez le nom de la variable de cotation à substituer Enter justification type Entrez le type de justification Enter leader text Entrez le texte du repère @@ -254,10 +254,10 @@ Enter rectangle length Entrez la longueur du rectangle Enter rectangle width Entrez la largeur du rectangle Enter scale factor Entrez le facteur d'échelle - Enter text Entrer le texte - Enter text (use \P for new paragraphs) Entrer le texte (utilisez \P pour les nouveaux paragraphes) - Enter the number of segments Entrer le nombre de segments - Enter twist direction of helix Entrer le sens de vrillage de l'hélice + Enter text Entrez le texte + Enter text (use \P for new paragraphs) Entrez le texte (utilisez \P pour les nouveaux paragraphes) + Enter the number of segments Entrez le nombre de segments + Enter twist direction of helix Entrez le sens de vrillage de l'hélice Entire drawing Tout le dessin Equal Égalité Erase Effacer @@ -482,8 +482,8 @@ Object Snap Accrochage aux objets Object Snap (F3) Accrochage aux objets (F3) Object Snap On (F3) Activer l'accrochage aux objets (F3) - Object Snap Tracking Suivi de l'accrochage aux objets - Object Snap Tracking (F11) Suivi de l'accrochage aux objets (F11) + Object Snap Tracking Repérage d'accrochage aux objets + Object Snap Tracking (F11) Repérage d'accrochage aux objets (F11) Object type: Type d'objet : Off Désactivé Offset Décalage @@ -539,7 +539,7 @@ New STB Nouvelle STB New style Nouveau style Reset Panel Layout Réinitialiser la disposition des panneaux - Use for this layout Utiliser pour cet espace + Use for this layout Utiliser pour cette présentation Display plot styles Afficher les styles de tracé No plot style tables. Aucune table de styles de tracé. A built-in table: editing it keeps an edited copy in the drawing. Table intégrée : sa modification conserve une copie modifiée dans le dessin. @@ -560,9 +560,9 @@ Point Filters Filtres de points Point Style... Style de point... Polar Array Réseau polaire - Polar Tracking Recherche polaire - Polar Tracking (F10) Recherche polaire (F10) - Polar Tracking On (F10) Activer la recherche polaire (F10) + Polar Tracking Repérage polaire + Polar Tracking (F10) Repérage polaire (F10) + Polar Tracking On (F10) Activer le repérage polaire (F10) Polar: {distance} < {angle}° Polaire : {distance} < {angle}° Polygon Polygone Polygonal Polygonal @@ -645,77 +645,77 @@ Search for parameter Rechercher un paramètre Second and next points: Deuxième point et points suivants : Select Sélectionner - Select 2D polyline Sélectionner une polyligne 2D + Select 2D polyline Sélectionnez une polyligne 2D Select All Sélectionner tout Select Objects Sélectionner les objets - Select a 2D polyline. Sélectionner une polyligne 2D. - Select a block reference. Sélectionner une référence de bloc. - Select a circle or arc. Sélectionner un cercle ou un arc. - Select a closed polyline Sélectionner une polyligne fermée - Select a closed polyline, circle, ellipse or closed spline. Sélectionner une polyligne fermée, un cercle, une ellipse ou une spline fermée. - Select a closed polyline. Sélectionner une polyligne fermée. - Select a curve as the path. Sélectionner une courbe comme trajectoire. - Select a dimension constraint type Sélectionner un type de contrainte dimensionnelle - Select a line object Sélectionner une ligne - Select a line object. Sélectionner une ligne. - Select a line or an arc. Sélectionner une ligne ou un arc. - Select a line or polyline segment Sélectionner une ligne ou un segment de polyligne - Select a line, arc or open polyline. Sélectionner une ligne, un arc ou une polyligne ouverte. - Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionner une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire. - Select a line, circle, arc or polyline segment. Sélectionner une ligne, un cercle, un arc ou un segment de polyligne. - Select a line. Sélectionner une ligne. + Select a 2D polyline. Sélectionnez une polyligne 2D. + Select a block reference. Sélectionnez une référence de bloc. + Select a circle or arc. Sélectionnez un cercle ou un arc. + Select a closed polyline Sélectionnez une polyligne fermée + Select a closed polyline, circle, ellipse or closed spline. Sélectionnez une polyligne fermée, un cercle, une ellipse ou une spline fermée. + Select a closed polyline. Sélectionnez une polyligne fermée. + Select a curve as the path. Sélectionnez une courbe comme trajectoire. + Select a dimension constraint type Sélectionnez un type de contrainte dimensionnelle + Select a line object Sélectionnez une ligne + Select a line object. Sélectionnez une ligne. + Select a line or an arc. Sélectionnez une ligne ou un arc. + Select a line or polyline segment Sélectionnez une ligne ou un segment de polyligne + Select a line, arc or open polyline. Sélectionnez une ligne, un arc ou une polyligne ouverte. + Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionnez une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire. + Select a line, circle, arc or polyline segment. Sélectionnez une ligne, un cercle, un arc ou un segment de polyligne. + Select a line. Sélectionnez une ligne. Add to Working Set Ajouter au jeu de travail Edit Reference In-Place Modifier la référence sur place Save Reference Edits Enregistrer les modifications de la référence Working Set Jeu de travail Xref and Block In-place Editing Édition sur place des xrefs et des blocs - Select a polyline. Sélectionner une polyligne. - Select a text, mtext, attribute definition or dimension. Sélectionner un texte, un texte multiligne, une définition d'attribut ou une cote. - Select an annotation object Sélectionner un objet d'annotation - Select an arc or circle Sélectionner un arc ou un cercle - Select an arc. Sélectionner un arc. - Select an object Sélectionner un objet - Select an object to change Sélectionner un objet à modifier - Select an object to measure Sélectionner un objet à mesurer - Select an object. Sélectionner un objet. - Select an open curve. Sélectionner une courbe ouverte. - Select an open line, arc, polyline, ellipse arc or spline. Sélectionner une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts. - Select arc or circle Sélectionner un arc ou un cercle - Select arc or polyline arc segment Sélectionner un arc ou un segment d'arc de polyligne - Select arc style Sélectionner un style d'arc - Select arc, circle, line Sélectionner un arc, un cercle, une ligne - Select at least two objects to join. Sélectionner au moins deux objets à joindre. - Select circle or arc to add center mark Sélectionner un cercle ou un arc pour ajouter une marque de centre - Select closed objects (regions, closed polylines, circles). Sélectionner des objets fermés (régions, polylignes fermées, cercles). - Select first line Sélectionner la première ligne - Select first line or arc Sélectionner la première ligne ou le premier arc - Select first object Sélectionner le premier objet - Select first point Sélectionner le premier point - Select nested objects to copy Sélectionner des objets imbriqués à copier - Select object Sélectionner un objet - Select object to dimension Sélectionner un objet à coter - Select object to divide Sélectionner un objet à diviser - Select object to extend or shift-select to trim Sélectionner un objet à prolonger ou sélectionner avec Maj pour rogner - Select object to measure Sélectionner un objet à mesurer - Select object to offset Sélectionner un objet à décaler - Select object to trim or shift-select to extend Sélectionner un objet à rogner ou sélectionner avec Maj pour prolonger - Select objects Sélectionner les objets - Select objects (crossing window first corner) Sélectionner les objets (premier coin de la fenêtre de capture) - Select objects to array. Sélectionner les objets à répartir en réseau. - Select objects to stretch by crossing-window or crossing-polygon... Sélectionner les objets à étirer par fenêtre de capture ou polygone de capture... - Select objects: Sélectionner les objets : - Select one polyline (Multiple is available through the JSON form). Sélectionner une polyligne (l'option Multiple est disponible via le formulaire JSON). - Select path curve Sélectionner la courbe de trajectoire - Select point or object Sélectionner un point ou un objet - Select polyline Sélectionner une polyligne - Select second line Sélectionner la deuxième ligne - Select second line or shift-select to apply corner Sélectionner la deuxième ligne ou sélectionner avec Maj pour former le coin - Select second object Sélectionner le deuxième objet - Select second object or shift-select to apply corner Sélectionner le deuxième objet ou sélectionner avec Maj pour former le coin - Select second point Sélectionner le deuxième point - Select spline Sélectionner une spline - Select symmetry line Sélectionner l'axe de symétrie - Select two points Sélectionner deux points + Select a polyline. Sélectionnez une polyligne. + Select a text, mtext, attribute definition or dimension. Sélectionnez un texte, un texte multiligne, une définition d'attribut ou une cote. + Select an annotation object Sélectionnez un objet d'annotation + Select an arc or circle Sélectionnez un arc ou un cercle + Select an arc. Sélectionnez un arc. + Select an object Sélectionnez un objet + Select an object to change Sélectionnez un objet à modifier + Select an object to measure Sélectionnez un objet à mesurer + Select an object. Sélectionnez un objet. + Select an open curve. Sélectionnez une courbe ouverte. + Select an open line, arc, polyline, ellipse arc or spline. Sélectionnez une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts. + Select arc or circle Sélectionnez un arc ou un cercle + Select arc or polyline arc segment Sélectionnez un arc ou un segment d'arc de polyligne + Select arc style Sélectionnez un style d'arc + Select arc, circle, line Sélectionnez un arc, un cercle, une ligne + Select at least two objects to join. Sélectionnez au moins deux objets à joindre. + Select circle or arc to add center mark Sélectionnez un cercle ou un arc pour ajouter une marque de centre + Select closed objects (regions, closed polylines, circles). Sélectionnez des objets fermés (régions, polylignes fermées, cercles). + Select first line Sélectionnez la première ligne + Select first line or arc Sélectionnez la première ligne ou le premier arc + Select first object Sélectionnez le premier objet + Select first point Sélectionnez le premier point + Select nested objects to copy Sélectionnez des objets imbriqués à copier + Select object Sélectionnez un objet + Select object to dimension Sélectionnez un objet à coter + Select object to divide Sélectionnez un objet à diviser + Select object to extend or shift-select to trim Sélectionnez un objet à prolonger ou sélectionnez avec Maj pour rogner + Select object to measure Sélectionnez un objet à mesurer + Select object to offset Sélectionnez un objet à décaler + Select object to trim or shift-select to extend Sélectionnez un objet à rogner ou sélectionnez avec Maj pour prolonger + Select objects Sélectionnez les objets + Select objects (crossing window first corner) Sélectionnez les objets (premier coin de la fenêtre de capture) + Select objects to array. Sélectionnez les objets à répartir en réseau. + Select objects to stretch by crossing-window or crossing-polygon... Sélectionnez les objets à étirer par fenêtre de capture ou polygone de capture... + Select objects: Sélectionnez les objets : + Select one polyline (Multiple is available through the JSON form). Sélectionnez une polyligne (l'option Multiple est disponible via le formulaire JSON). + Select path curve Sélectionnez la courbe de trajectoire + Select point or object Sélectionnez un point ou un objet + Select polyline Sélectionnez une polyligne + Select second line Sélectionnez la deuxième ligne + Select second line or shift-select to apply corner Sélectionnez la deuxième ligne ou sélectionnez avec Maj pour former le coin + Select second object Sélectionnez le deuxième objet + Select second object or shift-select to apply corner Sélectionnez le deuxième objet ou sélectionnez avec Maj pour former le coin + Select second point Sélectionnez le deuxième point + Select spline Sélectionnez une spline + Select symmetry line Sélectionnez l'axe de symétrie + Select two points Sélectionnez deux points Selection Cycling Cycle de sélection Send to Back Envoyer à l'arrière-plan Set Current Définir comme courant @@ -747,18 +747,18 @@ Snap and Grid Accrochage et grille Solid Solide Sort Trier - Specify a point Spécifier un point - Specify a scale for the hatch pattern Spécifier une échelle pour le motif de hachures - Specify a second extension line origin Spécifier l'origine de la deuxième ligne d'attache - Specify an angle for the hatch pattern Spécifier un angle pour le motif de hachures - Specify angle end point Spécifier le point final de l'angle - Specify angle of dimension line Spécifier l'angle de la ligne de cote - Specify angle of dimension text Spécifier l'angle du texte de cote - Specify angle start point Spécifier le point de départ de l'angle - Specify angle vertex Spécifier le sommet de l'angle - Specify angle vertex point Spécifier le point du sommet de l'angle - Specify arc length dimension location Spécifier l'emplacement de la cote de longueur d'arc - Specify axis endpoint of ellipse Spécifier l'extrémité de l'axe de l'ellipse + Specify a point Spécifiez un point + Specify a scale for the hatch pattern Spécifiez une échelle pour le motif de hachures + Specify a second extension line origin Spécifiez l'origine de la deuxième ligne d'attache + Specify an angle for the hatch pattern Spécifiez un angle pour le motif de hachures + Specify angle end point Spécifiez le point final de l'angle + Specify angle of dimension line Spécifiez l'angle de la ligne de cote + Specify angle of dimension text Spécifiez l'angle du texte de cote + Specify angle start point Spécifiez le point de départ de l'angle + Specify angle vertex Spécifiez le sommet de l'angle + Specify angle vertex point Spécifiez le point du sommet de l'angle + Specify arc length dimension location Spécifiez l'emplacement de la cote de longueur d'arc + Specify axis endpoint of ellipse Spécifiez l'extrémité de l'axe de l'ellipse Specify base diameter Spécifiez le diamètre de la base Specify base point Spécifiez le point de base Specify base point or displacement (drag with the middle mouse button for realtime pan) Spécifiez le point de base ou le déplacement (faites glisser avec le bouton central de la souris pour un panoramique en temps réel) @@ -768,7 +768,7 @@ Specify center of polygon Spécifiez le centre du polygone Specify center point for circle Spécifiez le point central du cercle Specify center point of arc Spécifiez le point central de l'arc - Specify center point of array Spécifiez le point central de la matrice + Specify center point of array Spécifiez le point central du réseau Specify center point of base Spécifiez le point central de la base Specify corner of viewport Spécifiez le coin de la fenêtre Specify corner of window, enter a scale factor (nX or nXP) Spécifiez le coin de la fenêtre, entrez un facteur d'échelle (nX ou nXP) @@ -894,7 +894,7 @@ Sweep Balayage Switch Drawing Changer de dessin Switch Layout Changer de présentation - Switch between model space in a viewport and paper space Basculer entre l'espace modèle dans une fenêtre et l'espace papier + Switch between model space in a viewport and paper space Basculer entre l'espace objet dans une fenêtre et l'espace papier Symmetric Symétrie Synchronize Attributes Synchroniser les attributs Toggle PICKADD (off: each pick replaces the selection) Basculer PICKADD (désactivé : chaque sélection remplace la sélection existante) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 43635e2b1..177022c88 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1426,6 +1426,12 @@ menu Modify Edita ENTER INVIO Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni + Check for updates when CADCraft starts Controlla gli aggiornamenti all'avvio di CADCraft + Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Se disattivato, CADCraft non propone mai un aggiornamento da solo; Aiuto ▸ Verifica aggiornamenti… continua a controllare. # ArtCraft feature naming Additional Tools Strumenti aggiuntivi + Edit Attributes Modifica attributi + Block name: Nome blocco: + Tag: {tag} Etichetta: {tag} + Values typed at the command line work too Anche i valori digitati nella riga di comando vengono accettati diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6adf8f444..2f51d3223 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -340,7 +340,7 @@ Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა Explode დაშლა Explode Attributes to Text ატრიბუტების ტექსტად დაშლა - Export ექსპორტი + Export ექსპორტირება Export Table ცხრილის ექსპორტი Export to PDF... PDF-ად ექსპორტი... Express Tools Express Tools @@ -707,8 +707,8 @@ Previous Change წინა ცვლილება Previous Layer წინა შრე Primitives პრიმიტივები - Print დაბეჭდვა - Print... დაბეჭდვა... + Print ბეჭდვა + Print... ბეჭდვა... Properties თვისებები Properties Inspector თვისებების ინსპექტორი Properties: თვისებები: @@ -1242,7 +1242,7 @@ Animation effects ანიმაციის ეფექტები Interface scale ინტერფეისის მასშტაბი Import... იმპორტი... - Export... ექსპორტი... + Export... ექსპორტირება... Batch Publish... პაკეტური გამოქვეყნება... Scale List... მასშტაბების სია... Annotative Object Scale ანოტაციური ობიექტის მასშტაბი @@ -1472,6 +1472,26 @@ menu View ხედი Text to find მოსაძებნი ტექსტი Whole words მთლიანი სიტყვები Nothing found ვერაფერი მოიძებნა + Multiple Insert მრავალჯერადი ჩასმა + Ctrl+Enter to apply გამოსაყენებლად: Ctrl+Enter + Edit Text ტექსტის რედაქტირება + The drawing changed. Close the window and open it again. ნახაზი შეიცვალა. დახურეთ ფანჯარა და ხელახლა გახსენით. + DView დინამიკური ხედი + Raster Image Reference... რასტრული გამოსახულების მიმართვა... + Raster Images რასტრული გამოსახულებები + Clip Xref გარე მიმართვის მოჭრა + Xref გარე მიმართვა + Xref Clip Frame გარე მიმართვის მოჭრის ჩარჩო + Backup copies are off, so the current file will be replaced. სარეზერვო ასლები გამორთულია, ამიტომ მიმდინარე ფაილი ჩანაცვლდება. + DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 და უფრო ძველი ვერსიები მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. + DXF keeps them. Use Save As to keep them in the drawing. DXF მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. + Save Anyway მაინც შენახვა + Save cancelled: {path} was not changed. შენახვა გაუქმდა: {path} არ შეცვლილა. + Saving {name} will remove content ფაილში {name} შენახვისას შიგთავსის ნაწილი წაიშლება + The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. მიმდინარე ფაილი არასრული ჩანს, ამიტომ {name} უცვლელი რჩება, მიმდინარე ფაილი კი ჩანაცვლდება. + The current file is kept as {name} until the next save. მიმდინარე ფაილი შემდეგ შენახვამდე შენარჩუნდება სახელით {name}. + This format can't keep these objects yet: {objects}. ეს ფორმატი ამ ობიექტებს ჯერ ვერ ინახავს: {objects}. + {count} more types კიდევ {count} ტიპი Add a drawing file as a block library ნახაზის ფაილის დამატება ბლოკების ბიბლიოთეკად Add a folder of drawings or a drawing file to use its blocks. დაამატეთ ნახაზების საქაღალდე ან ნახაზის ფაილი მისი ბლოკების გამოსაყენებლად. Block Libraries ბლოკების ბიბლიოთეკები @@ -1502,3 +1522,38 @@ menu View ხედი # ArtCraft feature naming Additional Tools დამატებითი ხელსაწყოები + +# Keyboard Shortcuts, Right-Click Customization, alias import + Keyboard Shortcuts... კლავიატურის მალსახმობები... + Keyboard Shortcuts კლავიატურის მალსახმობები + Replaces the shortcut of {commands} ჩაანაცვლებს ამ ბრძანებების მალსახმობს: {commands} + Needs Ctrl, Alt or a function key საჭიროა Ctrl, Alt ან ფუნქციური კლავიში + Press the keys დააჭირეთ კლავიშებს + Back to CADCraft's shortcut CADCraft-ის მალსახმობზე დაბრუნება + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. თქვენ მიერ მინიჭებულ მალსახმობს უპირატესობა აქვს CADCraft-ის საკუთარზე. ცვლილებები მაშინვე მოქმედებს და შემდეგი ჯერისთვისაც ინახება. + Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება იმას აკეთებს, რაც „მარჯვენა დაწკაპების მორგებაში“ ბრძანების რეჟიმისთვის არის არჩეული. + Right-Click Customization... მარჯვენა დაწკაპების მორგება... + Right-Click Customization მარჯვენა დაწკაპების მორგება + Turn on time-sensitive right-click დროზე დამოკიდებული მარჯვენა დაწკაპების ჩართვა + Longer click duration: გრძელი დაწკაპების ხანგრძლივობა: + milliseconds მილიწამი + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. ბრძანების შესრულების დროს მოკლე დაწკაპება Enter-ია, გრძელი დაწკაპება კი კონტექსტურ მენიუს ხსნის. + Default Mode ნაგულისხმევი რეჟიმი + No objects selected and no command running: არაფერია მონიშნული და არცერთი ბრძანება არ სრულდება: + Edit Mode რედაქტირების რეჟიმი + Objects selected and no command running: ობიექტები მონიშნულია და არცერთი ბრძანება არ სრულდება: + Repeat last command ბოლო ბრძანების გამეორება + Shortcut Menu კონტექსტური მენიუ + Command Mode ბრძანების რეჟიმი + While a command runs: ბრძანების შესრულების დროს: + ENTER ENTER + Shortcut Menu: always enabled კონტექსტური მენიუ: ყოველთვის ჩართული + Shortcut Menu: enabled when command options are present კონტექსტური მენიუ: ჩართული, როცა ბრძანებას ვარიანტები აქვს + Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. იმპორტი: აქ ფაილის არჩევის დიალოგი არ არის; გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს. + Aliases are saved in your CADCraft profile and survive restarts. ფსევდონიმები თქვენს CADCraft-ის პროფილში ინახება და გადატვირთვის შემდეგაც რჩება. + Import… იმპორტი… + Run ALIASEDIT with the file's contents using its text parameter. გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს. + Importing a file replaces your {n} aliases, and any changes not applied yet. ფაილის იმპორტი ჩაანაცვლებს თქვენს ფსევდონიმებს ({n}) და ჯერ გამოუყენებელ ცვლილებებს. + Import and replace იმპორტი და ჩანაცვლება + Keep my aliases ჩემი ფსევდონიმების შენარჩუნება + {n} more warnings; see the command line. კიდევ {n} გაფრთხილება; იხილეთ ბრძანების სტრიქონი. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8b4e40216..a39eb55f5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -15,6 +15,7 @@ 2 Points 2 punkty 2 Viewports 2 rzutnie 2D Solid Bryła 2D + 3 Point 3 punkty 3 Points 3 punkty 3 Viewports 3 rzutnie 3D Face Ściana 3D @@ -23,20 +24,42 @@ 4 Viewports 4 rzutnie < Less than < Mniejsze niż <> Not Equal <> Różne +