diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 01b258e23c..b80d10d34c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -69,8 +69,8 @@ workflows: '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - '.github/workflows/nightly.yml': - - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly.yml': [] + '.github/workflows/pbr.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index 6f5b34e892..2be123b233 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -3,7 +3,7 @@ name: AI model on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml'] pull_request: paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml'] diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index b8bcc8b8ea..6afdafc290 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -3,7 +3,7 @@ name: Atomic file writes on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml'] pull_request: paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml'] diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 6063c4e4dc..5fd971c629 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -2,7 +2,7 @@ name: Shared audio on: push: - branches: [main, next] + branches: [main] paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml index b13dd82d14..c1737392da 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -3,7 +3,7 @@ name: Colour management on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] pull_request: paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 3e9b430d67..10e5b7ccf7 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -2,7 +2,7 @@ name: Shared CRW on: push: - branches: [main, next] + branches: [main] paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"] pull_request: paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"] @@ -52,7 +52,7 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - # Pull requests restore the entry main or next saved and never write their own: the same + # Pull requests restore the entry main saved and never write their own: the same # files saved once per pull request took a share of the 10 GB cache budget. - name: Restore the CC0 sample files id: samples diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index f9ab8fe56e..23def9feb0 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -3,7 +3,7 @@ name: Dialogs on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml'] pull_request: paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml'] diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index 00b8336db1..6275433817 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -3,7 +3,7 @@ name: Craft documents on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml'] pull_request: paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml'] diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fc51a0da51..cb54dbf119 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -6,7 +6,7 @@ name: Docs on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] pull_request: paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index bec96fed5c..048c897b3c 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -3,7 +3,7 @@ name: EffectCraft project format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml'] pull_request: paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml'] diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index fd599d207c..e655697b3d 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -3,7 +3,7 @@ name: Font store on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml'] pull_request: paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml'] diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index 22d90712e8..2ee6fc6281 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -2,7 +2,7 @@ name: Shared format crates on: push: - branches: [main, next] + branches: [main] paths: - "crates/xml/**" - "crates/mime/**" diff --git a/.github/workflows/full-validation.yml b/.github/workflows/full-validation.yml index 85ad96f2fe..652e2b1f13 100644 --- a/.github/workflows/full-validation.yml +++ b/.github/workflows/full-validation.yml @@ -32,7 +32,9 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 - env: CRAFT_PRINT_REQUIRE_QUEUE=0 + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=1 setup-command: bash scripts/ci-test-inputs.sh command: | python scripts/test-full-validation.py diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml index 7ee967c65b..de64ad3ee4 100644 --- a/.github/workflows/house-rules.yml +++ b/.github/workflows/house-rules.yml @@ -2,7 +2,7 @@ name: House rules on: push: - branches: [main, next] + branches: [main] paths: - AGENTS.md - CLAUDE.md diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index ebb27bafde..495af8b232 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -2,7 +2,7 @@ name: Shared JPEG on: push: - branches: [main, next] + branches: [main] paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"] pull_request: paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"] diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index bfce473788..47a5576499 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -2,7 +2,7 @@ name: Keymap on: push: - branches: [main, next] + branches: [main] paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] pull_request: paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 090ad84da9..f4c4e6689b 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -2,7 +2,7 @@ name: Shared media on: push: - branches: [main, next] + branches: [main] paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 80b6678cd3..b12c8bcc6a 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -2,7 +2,7 @@ name: Menu on: push: - branches: [main, next] + branches: [main] paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] pull_request: paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 5cc8032668..e5108dfa5a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,7 +1,7 @@ name: Nightly full tests # The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep -# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The +# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The # rest of the workspace's tests run with them, on Linux, with the gate's setup. on: schedule: @@ -26,37 +26,12 @@ jobs: packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan - env: CRAFT_PRINT_REQUIRE_QUEUE=0 + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=1 setup-command: bash scripts/ci-test-inputs.sh cache-paths: .test-inputs/photocraft/corpus cache-key: photocraft-corpus cache-key-files: scripts/ci-test-inputs.sh # The gate's build (the same targets and profile overrides), with every test at its full count. command: bash scripts/ci-workspace-tests.sh full - - # The scheduled run is main's; this starts the full tests above on next too, where the gate - # runs the same fractions. It also starts one Workspace run on next a day that nothing cancels - # (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's - # macOS and Windows legs then run in full at least once a day, and its Linux leg builds from - # source and saves next's own workspace-crates cache entry, which pull requests into next - # restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with - # `actions: write`; it checks out and runs nothing from the repository. - workspace-next: - name: Workspace on next - if: github.event_name == 'schedule' - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - actions: write - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - name: Start the Workspace workflow and these full tests on next - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - run: | - gh workflow run workspace.yml --repo "$REPO" --ref next - gh workflow run nightly.yml --repo "$REPO" --ref next diff --git a/.github/workflows/pbr.yml b/.github/workflows/pbr.yml new file mode 100644 index 0000000000..51c3a62daa --- /dev/null +++ b/.github/workflows/pbr.yml @@ -0,0 +1,29 @@ +name: PBR feature tests + +on: + workflow_dispatch: + push: + branches: [main, next] + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + pull_request: + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + +permissions: + contents: read + +jobs: + features: + name: PBR ${{ matrix.mode }} tests + strategy: + fail-fast: false + matrix: + include: + - { mode: serial, arguments: '' } + - { mode: parallel, arguments: '--features parallel' } + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + craft-fonts-ref: '' + require-craft-fonts: false + timeout-minutes: 30 + command: cargo test -p craft-pbr --locked ${{ matrix.arguments }} diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index cefa5360c4..0e4feabc92 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -3,7 +3,7 @@ name: PhotoCraft format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml'] pull_request: paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml'] diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index 1550512ac5..0269fdc7ea 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -2,7 +2,7 @@ name: Shared PDF on: push: - branches: [main, next] + branches: [main] paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] pull_request: paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 0f5b869a4a..ea5edb8a56 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -2,7 +2,7 @@ name: Proofing on: push: - branches: [main, next] + branches: [main] paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"] pull_request: paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"] diff --git a/.github/workflows/theme.yml b/.github/workflows/theme.yml index 213a74b147..f0bb32a466 100644 --- a/.github/workflows/theme.yml +++ b/.github/workflows/theme.yml @@ -3,7 +3,7 @@ name: Suite themes on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml'] pull_request: paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml'] diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 0ea3b8c1bb..e5e3e71d15 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -3,7 +3,7 @@ name: App updates on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml'] pull_request: paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml'] diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index 0ca15636df..cd66615a50 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -3,7 +3,7 @@ name: VectorCraft format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml'] pull_request: paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml'] diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 03b59cc427..20afe0d700 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -2,7 +2,7 @@ name: Shared video on: push: - branches: [main, next] + branches: [main] paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 0ad01e28fd..f0f8e22da7 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -3,7 +3,7 @@ name: Web API (page command API) on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml'] pull_request: paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml'] diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index 055303bc26..dc0254850a 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -2,7 +2,7 @@ name: Shared web host on: push: - branches: [main, next] + branches: [main] paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"] pull_request: paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"] diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index a534393fdc..5f05883d14 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -3,7 +3,7 @@ name: Window decorations on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] pull_request: paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 5c802e799e..b1a0ee2ffd 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -2,7 +2,7 @@ name: Workspace on: push: - branches: [main, next] + branches: [main] tags: ["v*"] pull_request: workflow_dispatch: @@ -16,13 +16,12 @@ permissions: contents: read concurrency: - # A pull request, main and next each have one group, so a newer push cancels the run it - # supersedes; the newest push's run still tests everything before it. Every other run (a release - # tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is - # neither cancelled nor replaced while queued: a release run always finishes, the scheduled run - # saves the caches, and next gets one complete macOS and Windows run a day. - group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }} + # A pull request and main each have one group, so a newer push cancels the run it supersedes; the + # newest push's run still tests everything before it. Every other run (a release tag, a manual + # run, the scheduled run) gets a group of its own and is neither cancelled nor replaced while + # queued: a release run always finishes, and the scheduled run saves the caches. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} jobs: # Whether this run needs the macOS and Windows legs, and which tests every leg runs @@ -71,7 +70,7 @@ jobs: # The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the # settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every # other override names a workspace crate (scripts/test-workspace-tests.py), so changing one - # keeps those entries, and next's runs restore main's. + # keeps those entries. - uses: actions/checkout@v7.0.1 if: github.event_name != 'pull_request' with: @@ -104,13 +103,10 @@ jobs: # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo # rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight - # scheduled run builds from source (`cold-build`) and starts the entry afresh. next has an entry - # of its own, since main's is built from different code and lockfile and a pull request into next - # rebuilt nearly everything from it (15.5 minutes): nightly.yml's daily manual run on next builds - # from source and saves it (`cache-save-on-dispatch`), and pull requests into next restore it - # before main's. The macOS and Windows legs keep a dependency-only entry: their workspace crates - # would not fit the 10 GB cache budget beside Linux's. The lint legs keep no cache - # (`lint-cache: false`) for the same reason; a cold lint leg is still shorter than its gate leg. + # scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and + # Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache + # budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a + # cold lint leg is still shorter than its gate leg. native: name: Workspace needs: platforms @@ -118,9 +114,8 @@ jobs: with: os: '["ubuntu-latest"]' cache-workspace-crates: true - cache-save-on-dispatch: true cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} - cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} + cold-build: ${{ github.event.schedule == '17 0 * * *' }} lint-cache: false # The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a # workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them. @@ -182,7 +177,7 @@ jobs: # The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux # leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on - # every push to main and next, on main's scheduled runs and on nightly.yml's daily run on next. + # every push to main and on main's scheduled runs. # A pull request that needs them before it merges gets the full-ci label. native-platforms: name: Workspace @@ -192,7 +187,7 @@ jobs: with: os: '["windows-latest","macos-latest"]' lint-cache: false - # Named by the dependency settings alone (`deps-profile`), so next restores main's entries. + # Named by the dependency settings alone (`deps-profile`). cache-version: v2-${{ needs.platforms.outputs.deps-profile }} timeout-minutes: *timeout tools: *tools @@ -212,15 +207,14 @@ jobs: lint-command: *lint command: *command - # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as - # does the daily manual run on next, and every run restores only the newest. This deletes the - # older ones of the run's branch as soon as the Linux leg is done, instead of leaving them to the - # 10 GB budget's eviction, which would evict other entries too. The only job with - # `actions: write`; it checks out and runs nothing from the repository. + # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and + # every run restores only the newest. This deletes the older ones as soon as the Linux leg is + # done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries + # too. The only job with `actions: write`; it checks out and runs nothing from the repository. cache-prune: name: cache prune needs: native - if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }} + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -234,11 +228,10 @@ jobs: env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} - REF: ${{ github.ref }} run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 112bfe4e93..55ff91d455 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -174,6 +174,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. +## GPU device selection + +`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. + ## Dalvik DEX inspection `crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/Cargo.lock b/Cargo.lock index d090f1f595..858d8604d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1819,6 +1819,7 @@ dependencies = [ "craft-geom", "craft-gif", "craft-gpu", + "craft-gpu-device", "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", @@ -1905,10 +1906,12 @@ dependencies = [ "craft-review", "craft-rtf", "craft-sbs", + "craft-scopes", "craft-score", "craft-scraft-format", "craft-settings", "craft-sf2", + "craft-shared-vec", "craft-sheet", "craft-shx", "craft-silhouette-studio", @@ -2047,6 +2050,7 @@ name = "craft-appkit" version = "0.1.0" dependencies = [ "block2 0.6.2", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", ] @@ -2280,8 +2284,8 @@ dependencies = [ "craft-atomic", "craft-control-protocol", "craft-flags", + "craft-platform", "dirs", - "getrandom 0.3.4", "log", "proptest", "serde", @@ -2294,6 +2298,7 @@ dependencies = [ name = "craft-control-protocol" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -2419,6 +2424,7 @@ name = "craft-dialogs" version = "0.1.0" dependencies = [ "block2 0.6.2", + "craft-appkit", "craft-atomic", "craft-behavior", "craft-browse", @@ -2498,6 +2504,7 @@ dependencies = [ "chrono", "craft-cfb", "craft-drawingml", + "craft-flow", "craft-math", "craft-offcrypto", "craft-opc", @@ -2916,6 +2923,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gpu-null" version = "0.1.0" @@ -3576,7 +3595,6 @@ version = "0.1.0" name = "craft-pbr" version = "0.1.0" dependencies = [ - "craft-pbr", "craft-texture", "glam 0.30.10", "naga", @@ -4037,6 +4055,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-scopes" +version = "0.1.0" +dependencies = [ + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-score" version = "0.1.0" @@ -4086,6 +4113,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-shared-vec" +version = "0.1.0" +dependencies = [ + "craft-shared-vec", + "proptest", + "serde", + "serde_json", +] + [[package]] name = "craft-sheet" version = "0.1.0" @@ -4205,6 +4242,7 @@ dependencies = [ name = "craft-suite-account" version = "0.1.0" dependencies = [ + "craft-platform", "dirs", "keyring", "keyring-core", @@ -4662,11 +4700,13 @@ dependencies = [ name = "craft-update" version = "0.1.0" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek 2.2.0", "egui", "flate2", "image", @@ -4679,6 +4719,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -4919,6 +4960,7 @@ dependencies = [ "libc", "serde_json", "tempfile", + "toml_edit", ] [[package]] @@ -5644,7 +5686,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", @@ -5700,7 +5742,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5735,7 +5777,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -5754,7 +5796,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5773,7 +5815,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5793,7 +5835,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -5806,7 +5848,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "eframe", "egui", @@ -5883,7 +5925,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", ] @@ -5956,7 +5998,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5982,7 +6024,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equator" @@ -15305,19 +15347,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index 0782449467..ea77bf6c48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,10 +32,12 @@ craft-ssip = { path = "crates/ssip" } craft-ber = { path = "crates/ber" } craft-proto = { path = "crates/proto" } craft-render-parity = { path = "crates/render-parity" } +craft-shared-vec = { path = "crates/shared-vec" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } @@ -81,6 +83,7 @@ craft-cloud = { path = "crates/cloud" } craft-cloud-local = { path = "crates/cloud-local" } craft-cloud-ui = { path = "crates/cloud-ui" } craft-color = { path = "crates/color" } +craft-scopes = { path = "crates/scopes" } craft-color-ui = { path = "crates/color-ui" } craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } @@ -320,20 +323,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/NOTICE b/NOTICE index a2cbbb811e..4a2d1084e4 100644 --- a/NOTICE +++ b/NOTICE @@ -289,8 +289,8 @@ linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, -src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names -Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its +manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out. diff --git a/README.md b/README.md index 5d6829c08d..af82eafac8 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto, + low power, a named adapter that survives a reordered list and a driver update, or software; + corrections for drivers that crash; the next adapter and then a software one when a device fails + to open; a capability report; device-loss and error recording without panics; and what to reopen + after a loss. Settings pages and the window stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. @@ -377,8 +382,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item means stays in each app. -- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional - app menu. Unsaved-document decisions and save prompts stay in each app. +- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved + documents, the Quit menu item id and the unsaved-changes question one document at a time + (`CloseGuard`). The prompt and the saving stay in each app. - [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages (`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer for a small neutral model (paragraphs, character formatting, outline levels, tables). @@ -388,6 +394,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui` feature). - [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md). +- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`. - [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies. - [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft. - [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused. diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml index ad602e383a..5d451b3975 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-appkit" -description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." version.workspace = true edition.workspace = true license.workspace = true @@ -8,11 +8,12 @@ rust-version.workspace = true repository.workspace = true # `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through -# `NSNotificationCenter` with a block. +# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } +objc2 = { version = "0.6.4", default-features = false, features = ["std"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] } # The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 78dd786b15..70ed01f92d 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,5 @@ -//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS -//! only; the crate is empty elsewhere. +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the +//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound. @@ -14,6 +14,8 @@ use block2::RcBlock; use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; use objc2_foundation::{NSNotification, NSNotificationCenter}; +pub mod save_panel; + /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` /// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once /// for the process; a later call replaces nothing and does nothing. diff --git a/crates/appkit/src/save_panel.rs b/crates/appkit/src/save_panel.rs new file mode 100644 index 0000000000..979be8f96d --- /dev/null +++ b/crates/appkit/src/save_panel.rs @@ -0,0 +1,64 @@ +//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action. + +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; +use objc2_app_kit::{NSPopUpButton, NSSavePanel}; +use objc2_foundation::{NSObject, NSObjectProtocol}; + +/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems +/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it. +pub fn new_save_panel(mtm: MainThreadMarker) -> Option> { + // SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as + // `Option`, so nil is `None`. + let panel: Option> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] }; + if panel.is_some() { + return panel; + } + // SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`. + unsafe { msg_send![NSSavePanel::class(), savePanel] } +} + +/// The closure a [`PopUpChoice`] calls. +pub struct Ivars { + on_choose: Box, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[ivars = Ivars] + #[name = "CraftPopUpChoice"] + /// The target of a pop-up menu's action; see [`on_choose`]. + pub struct PopUpChoice; + + // SAFETY: NSObjectProtocol has no additional requirements. + unsafe impl NSObjectProtocol for PopUpChoice {} + + impl PopUpChoice { + // SAFETY: NSControl's target-action sends the pop-up button as the one object argument. + #[unsafe(method(choose:))] + fn choose(&self, sender: &NSPopUpButton) { + if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) { + (self.ivars().on_choose)(index); + } + } + } +); + +/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target, +/// so the caller keeps the returned object for as long as `popup` can send its action. +pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained { + let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) }); + // SAFETY: NSObject's designated initializer, called once on the allocated subclass. + let target: Retained = unsafe { msg_send![super(this), init] }; + let object: &AnyObject = ⌖ + // SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps + // `target` alive while `popup` can send it (the documentation above). + unsafe { + popup.setTarget(Some(object)); + popup.setAction(Some(sel!(choose:))); + } + target +} diff --git a/crates/atomic/README.md b/crates/atomic/README.md index e43d1c58f7..6ef4429a89 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee ## Core Guarantees: Atomicity vs. Durability -1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted. +1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted. 2. **Durability & Ordering Boundaries**: - **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback). - **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced. @@ -63,6 +63,27 @@ let path = Path::new("export.png"); write_new(path, b"png bytes...").expect("exclusive write"); ``` +### Removing Orphaned Staging Files + +```rust +use std::path::Path; +use std::time::Duration; +use craft_atomic::sweep_temp_files; + +// Removes staging files in scenes/ that were last modified an hour or more ago. +// Returns how many were removed. +let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0); +``` + +`sweep_temp_files` removes only regular files whose names have the staging form, never follows +a symbolic link, and does not search subfolders. A save updates its staging file's modification +time only while it writes bytes, not while it flushes or renames, and removing the staging file +makes that save fail. Choose a minimum age longer than the longest time any save into the folder, +by any process including the calling one, may go without writing, counting the final flush and +rename. On Windows, a write may not update the modification time until the staging file's handle +closes, so choose a minimum age longer than the longest whole save, from the staging file's +creation through the rename. Entries that cannot be removed are left in place. + ### Document Permissions and Private Data The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 5aa3c75cd4..104f859368 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -14,9 +14,9 @@ //! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs //! during staging or rename, the target remains unmodified and the staging file is removed in user space. //! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and -//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the -//! consuming application; the library does not perform background sweeping. The destination file itself is -//! never corrupted. +//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming +//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging +//! files. The destination file itself is never corrupted. //! - **Durability & Ordering Boundaries**: //! Data persistence across power failures involves two sync points: //! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage @@ -818,6 +818,57 @@ pub fn temp_name(file: &str) -> String { format!(".{stem}.{pid}-{n}.craft_tmp") } +/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed. +/// +/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a +/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process +/// id in the name is not used to decide, since the system reuses process ids. A save updates its +/// staging file's modification time only while it writes bytes, not while it flushes or renames, +/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest +/// time any save into `dir`, by any process including the calling one, may go without writing, +/// counting the final flush and rename. On Windows, a write may not update the modification time +/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save, +/// from the staging file's creation through the rename. Entries that cannot be read or removed are +/// left in place. Subfolders are not searched. +/// On `wasm32` this returns an `Unsupported` error. +pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result { + #[cfg(target_arch = "wasm32")] + { + let _ = (dir, min_age); + Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform")) + } + #[cfg(not(target_arch = "wasm32"))] + { + let now = std::time::SystemTime::now(); + let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?; + let mut removed = 0; + for entry in entries.flatten() { + if !entry.file_name().to_str().is_some_and(is_temp_name) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age); + if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() { + removed += 1; + } + } + Ok(removed) + } +} + +/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem +/// of at most [`TEMP_STEM_BYTES`] bytes. +#[cfg(not(target_arch = "wasm32"))] +fn is_temp_name(name: &str) -> bool { + // Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed. + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0')); + let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else { + return false; + }; + let Some((pid, n)) = tail.split_once('-') else { return false }; + stem.len() <= TEMP_STEM_BYTES && digits(pid) && digits(n) && pid.parse::().is_ok() && n.parse::().is_ok() +} + /// The end of an error message: whether an original file was left as it was. fn unchanged(existed: bool) -> &'static str { if existed { "; the original file was not changed" } else { "" } diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs index 78cc37ae16..132fd5a0a6 100644 --- a/crates/atomic/src/tests.rs +++ b/crates/atomic/src/tests.rs @@ -582,3 +582,79 @@ fn wasm_atomic_write_returns_unsupported() { let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::Unsupported); } + +#[cfg(target_arch = "wasm32")] +#[test] +fn wasm_sweep_temp_files_returns_unsupported() { + let err = sweep_temp_files(Path::new("scenes"), std::time::Duration::ZERO).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::Unsupported); +} + +/// Writes the file `name` in `dir` and dates its modification time `age` in the past. +#[cfg(not(target_arch = "wasm32"))] +fn leftover(dir: &Path, name: &str, age: std::time::Duration) -> io::Result { + let p = dir.join(name); + std::fs::write(&p, b"interrupted save")?; + File::options().write(true).open(&p)?.set_modified(std::time::SystemTime::now() - age)?; + Ok(p) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn sweep_removes_only_old_staging_files() -> io::Result<()> { + let d = TempDir::new("sweep_old"); + let other = std::process::id().wrapping_add(1); + let hour = std::time::Duration::from_secs(3600); + let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?; + // A process id the system reused for this process does not protect an old orphan. + let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?; + let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), std::time::Duration::ZERO)?; + let document = leftover(&d.0, "scene.json", 2 * hour)?; + + assert_eq!(sweep_temp_files(&d.0, hour)?, 2); + assert!(!orphan.exists() && !same_pid.exists()); + assert!(recent.exists() && document.exists()); + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> { + let d = TempDir::new("sweep_lookalike"); + let other = std::process::id().wrapping_add(1); + let old = std::time::Duration::from_secs(7200); + let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?; + let kept = [ + leftover(&d.0, "notes.craft_tmp", old)?, + leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?, + leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?, + leftover(&d.0, ".scene.json.-3.craft_tmp", old)?, + leftover(&d.0, ".12-3.craft_tmp", old)?, + leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?, + leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?, + // temp_name writes the process id and the counter without leading zeros. + leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?, + leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?, + // temp_name keeps at most TEMP_STEM_BYTES bytes of the destination's name. + leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(TEMP_STEM_BYTES + 1)), old)?, + ]; + // The longest stem temp_name writes, in ASCII and in two-byte characters. + let longest = leftover(&d.0, &temp_name(&"s".repeat(200)), old)?; + let longest_wide = leftover(&d.0, &temp_name(&"é".repeat(100)), old)?; + let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp")); + std::fs::create_dir(&folder)?; + + assert_eq!(sweep_temp_files(&d.0, std::time::Duration::ZERO)?, 3); + assert!(!orphan.exists() && !longest.exists() && !longest_wide.exists()); + assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed"); + assert!(folder.is_dir()); + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn sweep_of_a_missing_folder_is_an_error() { + let d = TempDir::new("sweep_missing"); + let err = sweep_temp_files(&d.0.join("absent"), std::time::Duration::ZERO).err().map(|e| e.kind()); + assert_eq!(err, Some(io::ErrorKind::NotFound)); +} diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index ce6724bb8e..886bd9fa64 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,8 +12,11 @@ and contains no `unsafe` code. (compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors), delays and reverbs (including convolution and surround), modulation, restoration (denoise, dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion, - dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms - of latency. + dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of + latency, and a formant shifter for a live voice with 10.7 ms of latency at 48 kHz (its size + depends on the sample rate; `latency()` reports it in samples). The pitch shifter's Keep + Formants switch adds the formant shifter's latency, and `latency()` reports it while the switch + is on. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 42ec2261ce..f5707b1e0f 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -36,7 +36,7 @@ pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; pub(crate) use time::{Delay, Reverb}; -pub use voice::VoicePitch; +pub use voice::{VoiceFormant, VoicePitch}; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -127,6 +127,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("denoise", "DeNoise", Restoration, DeNoise), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), + entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 662046f75c..85cd36208b 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() { f }; let lat0 = (e.create)(SR, 2).latency(); + // Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency. + let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 }; let mut a = mk(); let mut b = mk(); - assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id); + assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id); let ya = run(a.as_mut(), &l, &r); let yb = run(b.as_mut(), &l, &r); assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id); @@ -147,7 +149,13 @@ fn latency_is_where_the_impulse_lands() { // settings (FFT filter / convolution / existing STFT effects). The click remover repairs a // lone impulse in silence as a click, so its latency is checked on noise by // `neutral_settings_are_delayed_identity`. - for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] { + for (id, p) in [ + ("fft_filter", vec![]), + ("convolution_reverb", vec![("mix", 0.0)]), + ("voice_pitch", vec![]), + ("voice_pitch", vec![("formant_follow", 1.0)]), + ("voice_formant", vec![]), + ] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -977,6 +985,7 @@ fn direct_constructors_cap_the_channel_count() { filters::FullParametricEq, pitch::PitchShifter, voice::VoicePitch, + voice::VoiceFormant, ); } diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index af487cdbbb..a8a47dac59 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -1,5 +1,8 @@ -//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade -//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. +//! Effects for a live voice: a pitch shifter with 10 ms of latency and a formant shifter with +//! 10.7 ms of latency (at 48 kHz). +//! +//! The pitch shifter (`voice_pitch`) has two read taps that sweep through a short delay line and +//! crossfade (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. //! //! The taps sit half a sweep apart and are centered on the latency, so the delay of each one //! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and @@ -11,8 +14,21 @@ //! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift //! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting //! is a plain delay. +//! +//! The formant shifter (`voice_formant`) moves the spectral envelope of the voice up or down while +//! its harmonics stay where they are. It runs a short STFT (512 points at up to 50 kHz, hop 128). +//! For each frame it fits a linear predictor (one coefficient per kHz plus 2, at most 96) to the +//! last two frame lengths of input (1,024 samples at 48 kHz), which end with the frame and add no +//! latency, and takes the +//! envelope from the predictor. It then multiplies every bin by the envelope read at +//! `bin / ratio` over the envelope at the bin, with at most 24 dB of boost. Its latency is the +//! STFT size. `voice_pitch` uses the same stage for Keep Formants: the stage moves the shifted +//! voice's envelope back by the inverse of the pitch ratio, so the pitch changes and the formants +//! stay, and the latency grows by the STFT size. +use super::stft::{Spectral, StftChannel, fft_size}; use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::fft::Fft; use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::PI; @@ -33,6 +49,22 @@ const MARGIN: f64 = 2.0; const MAX_STEP: f64 = 0.45; /// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker. const TRACK_CLIP: f64 = 1.0e4; +/// Fewest and most predictor coefficients of the formant envelope (one per kHz plus 2 between). +const MIN_ORDER: usize = 8; +const MAX_ORDER: usize = 96; +/// Width of the Gaussian lag window, which widens each envelope peak to about this many hertz. +const LAG_HZ: f64 = 40.0; +/// White noise added to the autocorrelation (60 dB down), so a pure tone still gives a stable +/// predictor. +const WHITE: f64 = 1.0e-6; +/// Largest boost the envelope warp gives one bin: ln 16, about 24 dB. +const MAX_BOOST: f64 = 2.772_588_722_239_781; + +/// STFT size of the formant stage: 512 at up to 50 kHz (10.7 ms at 48 kHz), 1024 up to 100 kHz, +/// 2048 above. +fn formant_size(sample_rate: f32) -> usize { + fft_size(sample_rate) / 4 +} /// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a /// low-passed, decimated copy. Every buffer is sized at creation. @@ -229,10 +261,16 @@ struct Taps { delay_b: f64, } -/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). Keep Formants +/// (`formant_follow`) adds the formant stage's latency, 10.7 ms at 48 kHz, and `latency` reports +/// it while the switch is on. pub struct VoicePitch { pv: ParamValues, latency: usize, + /// Formant stage of Keep Formants, and the share of its output against the shifted voice. + follow: Stage, + follow_mix: f64, + follow_on: bool, /// Widest tap spacing that keeps both taps inside the line, in samples. max_spacing: f64, lines: Vec>, @@ -252,6 +290,7 @@ impl VoicePitch { pub const PARAMS: &'static [ParamSpec] = &[ ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones), ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None), + ParamSpec::new("formant_follow", "Keep Formants", 0.0, 1.0, 0.0, Unit::Toggle), ]; pub fn new(sample_rate: f32, channels: usize) -> Self { @@ -262,6 +301,9 @@ impl VoicePitch { let mut s = VoicePitch { pv: ParamValues::new(Self::PARAMS), latency, + follow: Stage::new(sample_rate, ch), + follow_mix: 0.0, + follow_on: false, max_spacing: latency as f64 - MARGIN, lines: vec![vec![0.0; len]; ch], mask: len - 1, @@ -280,11 +322,17 @@ impl VoicePitch { fn apply_params(&mut self, snap: bool) { let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0; self.ratio = 2f64.powf(shift / 12.0); + self.follow_on = self.pv.v("formant_follow") >= 0.5; if snap { self.wet = self.target_wet(); + self.follow_mix = self.follow_target(); } } + fn follow_target(&self) -> f64 { + if self.follow_on { 1.0 } else { 0.0 } + } + fn target_wet(&self) -> f64 { if self.ratio == 1.0 { 0.0 } else { 1.0 } } @@ -341,12 +389,13 @@ impl VoicePitch { impl AudioEffect for VoicePitch { param_plumbing!("voice_pitch"); fn latency(&self) -> usize { - self.latency + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn tail_samples(&self) -> usize { // A tap reads up to `latency + max_spacing` samples back and the cubic read two samples - // more, which is twice the latency in all. - self.latency + // more, which is twice the latency in all. Keep Formants spreads a frame over up to the + // formant stage's size more. A render drains `latency() + tail_samples()` samples. + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn reset(&mut self) { self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); @@ -355,23 +404,41 @@ impl AudioEffect for VoicePitch { self.phase = 0.5; self.spacing = self.max_spacing; self.wet = self.target_wet(); + self.follow.reset(); + self.follow_mix = self.follow_target(); } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); let ch = channels.len().min(self.lines.len()); let dry_at = self.mask + 1 - self.latency; + let follow_target = self.follow_target(); + // The formant stage moves the envelope by the inverse of the pitch ratio. + let back = (1.0 / self.ratio) as f32; for i in 0..len { let mut sum = 0.0f32; - for (line, io) in self.lines.iter_mut().zip(channels.iter()) { - // A non-finite sample is stored as silence, so it never reaches the output. - let x = flush32(io[i]); + for (c, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is stored as silence, so it never reaches the output. A + // channel the block leaves out is stored as silence too, so its line holds none + // of its earlier audio when it comes back. + let x = channels.get(c).map_or(0.0, |io| flush32(io[i])); line[self.pos] = x; sum += x; } let first = self.lines[0][self.pos]; self.tracker.push(sum / ch as f32, first); let t = self.advance(); - for (line, io) in self.lines.iter().zip(channels.iter_mut()) { + let mix = if self.follow_mix < follow_target { + (self.follow_mix + self.wet_step).min(follow_target) + } else { + (self.follow_mix - self.wet_step).max(follow_target) + }; + self.follow_mix = mix; + // While Keep Formants is off and faded out, the stage's frames copy the shifted voice, + // so switching it on crossfades from a delayed copy instead of from silence. + let warp = if mix > 0.0 { back } else { 1.0 }; + // A channel the block leaves out still reads its line into the formant stage, so the + // audio its line holds reaches the stage on time; only its output is dropped. + for (c, line) in self.lines.iter().enumerate() { let dry = line[(self.pos + dry_at) & self.mask] as f64; let y = if t.wet == 0.0 { dry @@ -380,13 +447,288 @@ impl AudioEffect for VoicePitch { t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b); t.wet * shifted + (1.0 - t.wet) * dry }; - io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + let y = y.clamp(-f32::MAX as f64, f32::MAX as f64); + let z = self.follow.tick(c, y as f32, warp); + // The stage's output is `n` samples later than `y`, so a switch fades one out + // before the other comes in instead of mixing them. + let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 }; + if let Some(io) = channels.get_mut(c) { + io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } } self.pos = (self.pos + 1) & self.mask; } } } +/// Spectral envelope of the recent input from linear prediction, and the warp that moves it. +/// Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Envelope { + fft: Fft, + /// Hann window over the analyzed history. + window: Vec, + /// Gaussian lag window, one value per autocorrelation lag (`order + 1`). + lags: Vec, + frame: Vec, + r: Vec, + /// Predictor coefficients, `a[0] = 1`. + a: Vec, + prev: Vec, + re: Vec, + im: Vec, + /// Natural log of the envelope's magnitude, bins 0..=n/2 of the STFT. + log: Vec, +} + +impl Envelope { + /// An envelope for STFT frames of `n` points, read from the last `2 n` samples. + fn new(n: usize, sample_rate: f32) -> Self { + let order = ((sample_rate / 1000.0).round() as usize + 2).clamp(MIN_ORDER, MAX_ORDER); + let w = 2 * n; + let window = (0..w).map(|i| 0.5 - 0.5 * (2.0 * PI * (i as f64 + 0.5) / w as f64).cos()).collect(); + let lags = (0..=order) + .map(|i| { + let x = 2.0 * PI * LAG_HZ * i as f64 / sample_rate as f64; + (-0.5 * x * x).exp() + }) + .collect(); + Envelope { + fft: Fft::new(n), + window, + lags, + frame: vec![0.0; w], + r: vec![0.0; order + 1], + a: vec![0.0; order + 1], + prev: vec![0.0; order + 1], + re: vec![0.0; n], + im: vec![0.0; n], + log: vec![0.0; n / 2 + 1], + } + } + + /// Reads the envelope of the newest `2 n` samples of `history`. Returns `false` for silence, + /// which has no envelope. + fn measure(&mut self, history: &History) -> bool { + let mask = history.ring.len() - 1; + for (i, (v, w)) in self.frame.iter_mut().zip(&self.window).enumerate() { + *v = history.ring[(history.pos + i) & mask] as f64 * w; + } + let len = self.frame.len(); + for (lag, (r, w)) in self.r.iter_mut().zip(&self.lags).enumerate() { + *r = dot(&self.frame[..len - lag], &self.frame[lag..]) * w; + } + if !(self.r[0] > 0.0 && self.r[0].is_finite()) { + return false; + } + self.r[0] *= 1.0 + WHITE; + levinson(&self.r, &mut self.a, &mut self.prev); + // The envelope is 1 / |A| on the bins of the STFT. + self.re.fill(0.0); + self.im.fill(0.0); + for (v, a) in self.re.iter_mut().zip(&self.a) { + *v = *a as f32; + } + self.fft.forward(&mut self.re, &mut self.im); + for (l, (re, im)) in self.log.iter_mut().zip(self.re.iter().zip(&self.im)) { + *l = (-0.5 * (*re as f64 * *re as f64 + *im as f64 * *im as f64 + 1e-30).ln()) as f32; + } + true + } + + /// Multiplies the half spectrum `re`/`im` (bins 0..=n/2) by the envelope read at `bin / + /// ratio` over the envelope at the bin, so the envelope moves up by `ratio` and the + /// harmonics stay. A frame with a non-finite bin is replaced with silence. + fn warp(&self, re: &mut [f32], im: &mut [f32], ratio: f32) { + let half = self.log.len(); + let (re, im) = (&mut re[..half], &mut im[..half]); + if !re.iter().chain(im.iter()).fold(true, |ok, v| ok & v.is_finite()) { + re.fill(0.0); + im.fill(0.0); + return; + } + let last = (half - 1) as f32; + for k in 0..half { + let src = (k as f32 / ratio).min(last); + let i = src as usize; + let e = match self.log.get(i + 1) { + Some(next) => self.log[i] + (src - i as f32) * (next - self.log[i]), + None => self.log[i], + }; + let g = ((e - self.log[k]) as f64).min(MAX_BOOST).exp() as f32; + re[k] *= g; + im[k] *= g; + } + } +} + +/// Dot product of two slices of the same length, in four running sums so it vectorizes. +fn dot(a: &[f64], b: &[f64]) -> f64 { + let mut sums = [0.0f64; 4]; + let ((ca, ra), (cb, rb)) = (a.as_chunks::<4>(), b.as_chunks::<4>()); + for (x, y) in ca.iter().zip(cb) { + for ((s, x), y) in sums.iter_mut().zip(x).zip(y) { + *s += x * y; + } + } + let rest: f64 = ra.iter().zip(rb).map(|(x, y)| x * y).sum(); + (sums[0] + sums[1]) + (sums[2] + sums[3]) + rest +} + +/// Levinson-Durbin recursion: the predictor `a` (`a[0] = 1`) of the autocorrelation `r`. It +/// stops at the first reflection coefficient that would make the predictor unstable. +fn levinson(r: &[f64], a: &mut [f64], prev: &mut [f64]) { + a.fill(0.0); + a[0] = 1.0; + let mut err = r[0]; + for i in 1..a.len() { + let acc = r[i] + (1..i).map(|j| a[j] * r[i - j]).sum::(); + let k = -acc / err; + // NaN (from a zero error) also stops the recursion. + if k.is_nan() || k.abs() >= 1.0 { + return; + } + prev[..i].copy_from_slice(&a[..i]); + for j in 1..i { + a[j] = prev[j] + k * prev[i - j]; + } + a[i] = k; + err *= 1.0 - k * k; + } +} + +/// The newest samples of one channel, for the envelope. +#[derive(Clone, Debug)] +struct History { + ring: Vec, + /// Where the next sample goes, which is also the oldest sample. + pos: usize, +} + +impl History { + fn push(&mut self, x: f32) { + self.ring[self.pos] = x; + self.pos = (self.pos + 1) & (self.ring.len() - 1); + } + + fn reset(&mut self) { + self.ring.fill(0.0); + self.pos = 0; + } +} + +/// STFT stage that moves each channel's envelope, fed one sample at a time: the formant +/// shifter, and the formant stage of `voice_pitch`'s Keep Formants. +#[derive(Clone, Debug)] +struct Stage { + n: usize, + hop: usize, + scale: f32, + spec: Spectral, + stft: Vec, + history: Vec, + env: Envelope, +} + +impl Stage { + fn new(sample_rate: f32, channels: usize) -> Self { + let n = formant_size(sample_rate); + Stage { + n, + hop: n / 4, + // √Hann on both sides is Hann, which sums to 2 at a hop of n/4; the inverse FFT is + // unscaled. + scale: 1.0 / (2 * n) as f32, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); channels], + history: vec![History { ring: vec![0.0; 2 * n], pos: 0 }; channels], + env: Envelope::new(n, sample_rate), + } + } + + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.history.iter_mut().for_each(History::reset); + } + + /// Pushes one sample of a channel and returns the stage's output for it, `n` samples later. + /// A frame moves the envelope by `ratio`, which can spread a sound over the frame, so the + /// output can go on for up to `n` samples more (the tail). At a ratio of 1, and for silence, a frame only + /// windows and adds its input, which needs no FFT. + fn tick(&mut self, channel: usize, x: f32, ratio: f32) -> f32 { + let Stage { n, hop, scale, spec, stft, history, env } = self; + let half = *n / 2 + 1; + history[channel].push(x); + let history = &history[channel]; + let z = stft[channel].tick(x, *hop, &mut |input, out| { + if ratio != 1.0 && env.measure(history) { + spec.analyze(input); + env.warp(&mut spec.re[..half], &mut spec.im[..half], ratio); + spec.synthesize_add(out, *scale); + } else { + for ((o, x), w) in out.iter_mut().zip(input).zip(&spec.window) { + *o += x * w * w * 0.5; + } + } + }); + // A huge finite input can overflow the inverse FFT. + flush32(z) + } +} + +/// Formant shifter for a live voice: moves the spectral envelope by -12 to +12 semitones (a ratio +/// of 0.5 to 2) and keeps the harmonics. Its latency is the STFT size, 512 samples (10.7 ms) at +/// 48 kHz. +pub struct VoiceFormant { + pv: ParamValues, + stage: Stage, + ratio: f32, +} + +impl VoiceFormant { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("semitones", "Formant Shift", -12.0, 12.0, 0.0, Unit::Semitones)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = VoiceFormant { pv: ParamValues::new(Self::PARAMS), stage: Stage::new(sample_rate, crate::sane_channels(channels)), ratio: 1.0 }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + self.ratio = 2f32.powf(self.pv.v("semitones") / 12.0); + } +} + +impl AudioEffect for VoiceFormant { + param_plumbing!("voice_formant"); + fn latency(&self) -> usize { + self.stage.n + } + fn tail_samples(&self) -> usize { + self.stage.n + } + fn reset(&mut self) { + self.stage.reset(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + for i in 0..len { + for c in 0..self.stage.stft.len() { + // A non-finite sample is taken as silence, so it never reaches the output. A + // channel the block leaves out is fed silence, so it holds none of its earlier + // audio when it comes back. + match channels.get_mut(c) { + Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio), + None => { + self.stage.tick(c, 0.0, self.ratio); + } + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -557,6 +899,288 @@ mod tests { assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); } + /// Two-pole resonance magnitude at `f`, 1 at `center`. + fn resonance(f: f64, center: f64, bandwidth: f64) -> f64 { + center * bandwidth / ((center * center - f * f).powi(2) + (f * bandwidth).powi(2)).sqrt() + } + + /// A vowel: harmonics of `f0` up to 6 kHz shaped by two formants (`f1` with an 80 Hz + /// bandwidth, `f2` with 120 Hz and half the level) over a floor 34 dB down. + fn vowel(f0: f64, f1: f64, f2: f64, sr: f64, n: usize) -> Vec { + let harmonics: Vec<(f64, f64)> = (1..) + .map(|k| k as f64 * f0) + .take_while(|f| *f < 6000.0) + .map(|f| (f, 0.02 + resonance(f, f1, 80.0) + 0.5 * resonance(f, f2, 120.0))) + .collect(); + (0..n) + .map(|i| { + let t = i as f64 / sr; + (0.08 * harmonics.iter().map(|(f, a)| a * (2.0 * std::f64::consts::PI * f * t).sin()).sum::()) as f32 + }) + .collect() + } + + /// The envelope peak of `y` between `lo` and `hi` Hz, read from the amplitudes of the + /// harmonics of `f0` with a parabola through the strongest one and its neighbors (in dB). + fn envelope_peak(y: &[f32], f0: f64, lo: f64, hi: f64, sr: f64) -> f64 { + let amp = |k: usize| tone_amplitude(y, k as f64 * f0, sr).max(1e-12).ln(); + let ks = (lo / f0).ceil() as usize..=(hi / f0).floor() as usize; + let k = ks.max_by(|a, b| amp(*a).total_cmp(&(*b))).unwrap_or(1); + let (a, b, c) = (amp(k - 1), amp(k), amp(k + 1)); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + (k as f64 + shift) * f0 + } + + /// The second of `y` after its first half second, at the rate `sr`. + fn settled_at(y: &[f32], sr: f64) -> &[f32] { + &y[sr as usize / 2..sr as usize * 3 / 2] + } + + /// The two formants of the vowel test signal (600 and 2000 Hz) in `y`, each looked for within + /// a window moved by `ratio`, with `y`'s harmonics at multiples of `f0`. + fn formants(y: &[f32], f0: f64, ratio: f64, sr: f64) -> (f64, f64) { + let tail = settled_at(y, sr); + (envelope_peak(tail, f0, 400.0 * ratio, 1000.0 * ratio, sr), envelope_peak(tail, f0, 1400.0 * ratio, 3000.0 * ratio, sr)) + } + + /// Level of everything off the harmonics of `f0` in `y`'s settled second, against the whole, + /// in dB. + fn off_harmonics_db(y: &[f32], f0: f64, sr: f64) -> f64 { + let tail = settled_at(y, sr); + let total = rms(tail).powi(2); + let on: f64 = (1..).map(|k| k as f64 * f0).take_while(|f| *f < sr / 2.0 - f0).map(|f| tone_amplitude(tail, f, sr).powi(2) / 2.0).sum(); + 10.0 * ((total - on).max(1e-30) / total).log10() + } + + /// A formant shift moves both formants of a vowel by the ratio, within a tenth of the move for + /// the first and 5% for the second, while every partial stays on the harmonics of the + /// unchanged fundamental. Checked at three voice pitches and three sample rates. + #[test] + fn a_formant_shift_moves_the_envelope_and_keeps_the_harmonics() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + for f0 in [110.0, 150.0, 220.0] { + let x = vowel(f0, 600.0, 2000.0, sr, sr as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for semis in [-4.0f32, 4.0] { + let mut f = VoiceFormant::new(sr as f32, 1); + assert!(f.set_param("semitones", semis)); + let mut y = x.clone(); + f.process(&mut [&mut y]); + let r = 2f64.powf(semis as f64 / 12.0); + let (q1, q2) = formants(&y, f0, r, sr); + let at = format!("{sr} Hz, f0 {f0}, {semis:+} st: formants {p1:.0} and {p2:.0} moved to {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * r) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * r) - 1.0).abs() < 0.05, "{at}"); + let off = off_harmonics_db(&y, f0, sr); + assert!(off < -30.0, "{at}: {off:.1} dB off the harmonics"); + } + } + } + } + + /// Keep Formants: the pitch moves up a fourth, and the formants of the vowel stay where they + /// were (where without it they move with the pitch). + #[test] + fn keep_formants_holds_the_envelope_while_the_pitch_moves() { + let (sr, f0) = (SR as f64, 150.0); + let x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + let r = 2f64.powf(5.0 / 12.0); + for keep in [false, true] { + let mut p = shifter(5.0, 0.0); + assert!(p.set_param("formant_follow", if keep { 1.0 } else { 0.0 })); + p.reset(); + let y = run(&mut p, &x); + let want = if keep { 1.0 } else { r }; + let (q1, q2) = formants(&y, f0 * r, want, sr); + let at = format!("keep {keep}: formants {p1:.0} and {p2:.0} read {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * want) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * want) - 1.0).abs() < 0.05, "{at}"); + assert!(cents(peak_hz(settled(&y), f0 * r * 0.98, f0 * r * 1.02), f0 * r).abs() < 2.0, "keep {keep}: pitch"); + } + } + + /// Keep Formants adds the formant shifter's latency to the pitch shifter's while it is on, at + /// each rate. + #[test] + fn the_latency_reports_the_formant_stage() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + let n = VoiceFormant::new(sr, 2).latency(); + assert!(n > 0, "{sr}"); + let mut p = VoicePitch::new(sr, 2); + let base = p.latency(); + assert!(p.set_param("formant_follow", 1.0)); + assert_eq!(p.latency(), base + n, "{sr}"); + assert!(p.set_param("formant_follow", 0.0)); + assert_eq!(p.latency(), base, "{sr}"); + } + } + + /// After a burst of noise ends, the formant shifter and the pitch shifter with Keep Formants + /// fall silent within `latency + tail_samples`, so an offline render that drains that long + /// keeps all of the output. + #[test] + fn formant_output_ends_within_the_reported_tail() { + let (n, at, len) = (12_000, 1_777, 1_000); + let mut rng = Rng::new(17); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let mut f = VoiceFormant::new(SR, 1); + assert!(f.set_param("semitones", 7.0)); + let mut p = shifter(-5.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let fxs: [&mut dyn AudioEffect; 2] = [&mut f, &mut p]; + for fx in fxs { + let mut y = x.clone(); + fx.process(&mut [&mut y]); + let end = at + len + fx.latency() + fx.tail_samples(); + assert!(y[end..].iter().all(|v| *v == 0.0), "{}: output after {end}", fx.id()); + } + } + + /// Switching Keep Formants on fades the shifter's own output out over 10 ms and then fades the + /// formant stage's output, 512 samples later, in over 10 ms: the two never sound together, + /// so their different delays cannot comb-filter the voice. Checked at a shift of 0, where the + /// stage passes the voice unchanged. + #[test] + fn switching_keep_formants_fades_through_silence() { + let x = vowel(170.0, 650.0, 1900.0, SR as f64, 12_000); + let at = 4_000; + let mut plain = shifter(0.0, 0.0); + let y = run(&mut plain, &x); + let mut p = shifter(0.0, 0.0); + let mut out = x.clone(); + p.process(&mut [&mut out[..at]]); + assert!(p.set_param("formant_follow", 1.0)); + p.process(&mut [&mut out[at..]]); + let n = p.follow.n; + let step = 1.0 / (SR as f64 * BYPASS_MS as f64 / 1000.0); + for i in at..x.len() { + let m = ((i - at + 1) as f64 * step).min(1.0); + let want = if m < 0.5 { (1.0 - 2.0 * m) * y[i] as f64 } else { (2.0 * m - 1.0) * y[i - n] as f64 }; + assert!((out[i] as f64 - want).abs() < 1e-4, "sample {i}: {} against {want}", out[i]); + } + } + + /// The formant shifter with a shift change part way, and the pitch shifter with Keep Formants + /// switched on and off part way, give the same output however the stream is cut into blocks. + #[test] + fn formant_output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x = vowel(130.0, 700.0, 1800.0, SR as f64, n); + let changes: [(usize, &str, f32); 3] = [(9_001, "semitones", 3.0), (17_321, "formant_follow", 1.0), (29_999, "formant_follow", 0.0)]; + let run_cut = |make: &dyn Fn() -> Box, sizes: &mut dyn FnMut() -> usize| { + let mut fx = make(); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + for (at, id, v) in changes { + if pos == at { + fx.set_param(id, v); + } + } + let next = changes.iter().map(|c| c.0).find(|at| *at > pos).unwrap_or(n); + let len = sizes().min(next - pos); + fx.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let makers: [&dyn Fn() -> Box; 2] = [ + &|| { + let mut f = VoiceFormant::new(SR, 1); + f.set_param("semitones", -5.0); + Box::new(f) + }, + &|| Box::new(shifter(-3.0, 0.0)), + ]; + for make in makers { + let whole = run_cut(make, &mut || usize::MAX); + let mut rng = Rng::new(13); + let cut = run_cut(make, &mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + assert!(whole.iter().any(|v| v.abs() > 0.05)); + } + } + + /// NaN, infinite and the largest finite samples in a vowel give finite output from the formant + /// shifter and from Keep Formants, and the formants are still moved afterwards. + #[test] + fn formant_stage_output_stays_finite() { + let (sr, f0) = (SR as f64, 150.0); + let mut x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, _) = formants(&x, f0, 1.0, sr); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let mut f = VoiceFormant::new(SR, 2); + assert!(f.set_param("semitones", 4.0)); + let (mut l, mut r) = (x.clone(), x.clone()); + f.process(&mut [&mut l, &mut r]); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); + let ratio = 2f64.powf(4.0 / 12.0); + let (q1, _) = formants(&l, f0, ratio, sr); + assert!((q1 / (p1 * ratio) - 1.0).abs() < 0.12, "{q1}"); + let mut p = shifter(-7.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + assert!(rms(settled(&y)) > 0.01); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset none of their earlier audio sounds. Checked for the formant shifter and for the + /// pitch shifter with and without Keep Formants. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let mut rng = Rng::new(19); + let noise: Vec = (0..4_000).map(|_| 0.5 * rng.uniform()).collect(); + let mut f = VoiceFormant::new(SR, 3); + assert!(f.set_param("semitones", 4.0)); + let mut plain = VoicePitch::new(SR, 3); + assert!(plain.set_param("semitones", 5.0)); + plain.reset(); + let mut keep = VoicePitch::new(SR, 3); + assert!(keep.set_param("semitones", 5.0) && keep.set_param("formant_follow", 1.0)); + keep.reset(); + let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep]; + for fx in fxs { + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + fx.process(&mut [&mut a, &mut b, &mut c]); + let mut a = noise.clone(); + fx.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + fx.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "{}: earlier audio came back", fx.id()); + } + } + + /// With Keep Formants on, a channel left out of a short block while its line still holds an + /// impulse passes that impulse to the formant stage, so after it comes back its output matches + /// a channel that was never left out. + #[test] + fn a_short_gap_keeps_the_formant_stage_fed() { + for semitones in [0.0, 5.0] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut a, mut b) = (vec![0.0f32; 480], vec![0.0f32; 480]); + a[0] = 1.0; + b[0] = 1.0; + p.process(&mut [&mut a, &mut b]); + // The impulse leaves the delay line during samples 480 to 735, while `b` is left out. + let mut a = vec![0.0f32; 256]; + p.process(&mut [&mut a]); + let (mut a, mut b) = (vec![0.0f32; 2_000], vec![0.0f32; 2_000]); + p.process(&mut [&mut a, &mut b]); + assert!(a.iter().any(|v| v.abs() > 0.01), "{semitones}: the impulse never came out"); + assert_eq!(a, b, "{semitones}: the left-out channel lost the impulse"); + } + } + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. #[test] fn the_tracker_reaches_70_hz() { diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 59bfaa1741..3b33639ca7 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -171,8 +171,10 @@ pub trait AudioEffect: Send { /// Parameter descriptions (same as the registry entry's). fn params(&self) -> &'static [ParamSpec]; /// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids. - /// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to - /// the new value smoothly; the crate documentation lists which other parameters change at once. + /// Updates the target immediately. Sample-based effects use the target from the next processed + /// sample. Frame-based effects may apply it at the next frame callback while earlier output + /// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the + /// crate documentation lists which other parameters change at once. fn set_param(&mut self, id: &str, value: f32) -> bool; /// Current (target) value of a parameter. fn param(&self, id: &str) -> Option; @@ -182,7 +184,11 @@ pub trait AudioEffect: Send { /// Process one block in place. All channel slices must have the same length (the shortest /// length is used otherwise). Zero-length blocks are allowed. fn process(&mut self, channels: &mut [&mut [f32]]); - /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. + /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does + /// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep + /// Formants), which adds the formant stage's latency while it is on. The value changes as + /// soon as the switch changes, while the output crossfades between the two delays over the + /// next 20 ms, so during that fade the output does not match the reported latency. fn latency(&self) -> usize { 0 } @@ -197,7 +203,9 @@ pub trait AudioEffect: Send { None } /// How long the output keeps sounding after the input stops, in samples (reverb and delay - /// tails), so an offline render can run past the end of its input. + /// tails), so an offline render can run past the end of its input. The count starts after + /// the latency: a render that keeps all of the output runs `latency() + tail_samples()` + /// samples past the end of its input. fn tail_samples(&self) -> usize { 0 } diff --git a/crates/audio/README.md b/crates/audio/README.md index 75f5694f66..3b868392a8 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | @@ -218,8 +218,10 @@ target, call `reset()`, decode from there, and drop the output before the target The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and `vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`, `opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and -`vorbis::layout(channels)` gives the speakers of the result. `ac3::Decoder` and `mpa::Decoder` -output WAV order. +`vorbis::layout(channels)` gives the speakers of the result. `opus::wav_order` applies only to +mapping family 1. Family 0 is mono or stereo, which is already in WAV order. For other families, +`TrackDecoder` assigns no conventional speaker mapping and leaves channels in stream order. +`ac3::Decoder` and `mpa::Decoder` output WAV order. ### Encode a file diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index d57baa6b59..6cc18ab901 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,9 +19,9 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A -//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, -//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature +//! gives [`wav_float_header`] and [`wav_float_header_with_bwf`]), FLAC (feature `flac-encode`), +//! AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams +//! (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. //! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, //! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, @@ -209,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; feature = "eac3-encode" ))] pub use write::FileEncoder; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -224,6 +222,8 @@ pub use write::wav_float_header; pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; +#[cfg(feature = "pcm-encode")] +pub use write::{wav_float_header, wav_float_header_with_bwf}; /// Errors from probing, decoding and encoding. #[non_exhaustive] diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index 205741c529..09f5d6a4c3 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -53,6 +53,9 @@ pub struct Header { impl Header { /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow. pub fn frame_bytes(&self) -> usize { + if !matches!(self.channels, 2 | 4 | 6 | 8) { + return 0; + } let pair_bytes = match self.bits { 16 => 5, 20 => 6, @@ -243,6 +246,17 @@ mod tests { assert_eq!(h.frame_bytes(), 0); } + #[test] + fn header_frame_bytes_rejects_unsupported_channels() { + for bits in [16, 20, 24] { + for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] { + let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 }; + assert!(Encoder::new(channels, bits).is_err()); + assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits"); + } + } + } + #[test] fn header_frame_bytes_rejects_unsupported_depth() { let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 }; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 18beab7872..25267e9a05 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -449,8 +449,32 @@ impl EncodeOptions { /// ``` #[cfg(feature = "pcm-encode")] pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result> { + float_header(sample_rate, channels, None, frames) +} + +/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length +/// still doesn't depend on `frames`, so the header is rewritten in place the same way. +/// +/// ``` +/// use craft_audio::{BwfInfo, wav_float_header_with_bwf}; +/// +/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600); +/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); +/// let samples = [0.25f32, -0.25, 0.5, -0.5]; +/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes())); +/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap(); +/// file[..header.len()].copy_from_slice(&header); +/// assert!(header.windows(4).any(|id| id == b"bext")); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result> { + float_header(sample_rate, channels, Some(bwf), frames) +} + +#[cfg(feature = "pcm-encode")] +fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result> { if channels == 0 || sample_rate == 0 { return Err(AudioError::Encode("a WAV needs channels and a sample rate".into())); } - wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) + wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false) } diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 2e58cd6332..dd7005fbfb 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -1,4 +1,7 @@ -use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe}; +use craft_audio::{ + AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header, + wav_float_header_with_bwf, +}; fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer { let mut b = AudioBuffer::new(sr, channels as u16, frames); @@ -64,3 +67,26 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } } + +#[test] +fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() { + let take = sine(48_000, 2, 1_000); + let bwf = BwfInfo::default() + .with_description("take 3") + .with_originator("recorder") + .with_origination("2026-11-20", "18:30:00") + .with_time_reference(48_000 * 66_600); + let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); + let len = file.len(); + assert!(len > wav_float_header(48_000, 2, 0).unwrap().len()); + file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes())); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap()); + let (info, decoded) = decode(&file, None).unwrap(); + assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600)); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap()); + let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()); + assert_eq!(file, encode(&take, &opts).unwrap()); + let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap(); + assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len)); + assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err()); +} diff --git a/crates/automation/README.md b/crates/automation/README.md index 2fdbf75be4..120e046f3e 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index 6296beea76..c240725742 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -16,7 +16,7 @@ use crate::security; use crate::server::{self, Listening}; /// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so -/// freeing a taken port is enough. +/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`]. pub const RETRY: Duration = Duration::from_secs(5); /// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence @@ -123,6 +123,10 @@ pub struct AgentLink { applied: Option>, retry_at: Option, retry: Duration, + /// The token a failed start already read and checked, for its retries with the same settings; + /// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms + /// on the UI thread, which every retry of a taken port would otherwise pay again. + checked_token: Option, status: AgentLinkStatus, } @@ -144,6 +148,7 @@ impl AgentLink { applied: None, retry_at: None, retry: RETRY, + checked_token: None, status: AgentLinkStatus::default(), } } @@ -166,7 +171,12 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` - /// equals the last call's and no retry of a failed start is due. + /// equals the last call's and no retry of a failed start is due. A token file refused as it is + /// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still + /// can't be used (a folder in its place, a folder that can't be written) schedules no retry: + /// that lasts until someone changes it, and on Windows each check blocks the UI thread for + /// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`] + /// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again. pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { let mut update = LinkUpdate::default(); if self.launch.is_some() { @@ -174,9 +184,15 @@ impl AgentLink { } let now = motion::now(); let retry_due = self.retry_at.is_some_and(|at| now >= at); - if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due { + let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want); + if unchanged && !retry_due { return update; } + // Only a retry with the same settings reuses the token its failed start checked: after a + // change (agents off and on again, another port) the file may hold another token by now. + if !unchanged { + self.checked_token = None; + } let before = (self.status.clone(), self.applied.clone().flatten()); self.applied = Some(want.cloned()); self.retry_at = None; @@ -218,6 +234,10 @@ impl AgentLink { update.requests = Some(requests); Ok(()) } + Err(problem @ LinkProblem::TokenFile(_)) => { + log::warn!("{problem}"); + Err(problem) + } Err(problem) => { log::warn!("{problem}"); self.retry_at = Some(motion::now() + self.retry); @@ -229,13 +249,21 @@ impl AgentLink { /// The token from the settings folder (created `0600` when missing), the server, then the /// connection file. Any failure leaves nothing running. - fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { + /// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]). + /// The token file is the link's own, so one refused as it is gets a new token (see + /// [`fresh_token`]). + fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { let token_file = dir.join(TOKEN_FILE); - let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?; + let token = match self.checked_token.clone() { + Some(token) => token, + None => fresh_token(&token_file)?, + }; + self.checked_token = Some(token.clone()); let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?; let running = Running { server, dir: dir.to_path_buf(), port_pref }; let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone()); write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?; + self.checked_token = None; Ok((running, requests)) } @@ -250,3 +278,22 @@ impl AgentLink { self.status.problem = Some(problem); } } + +/// The token in `token_file`, created when missing. A regular file the check refuses (one an +/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged +/// token) is replaced with a new token, once: the token is only this link's secret, and a client +/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted +/// the file. Anything else in the way (a folder, a link) is reported, not removed. +fn fresh_token(token_file: &Path) -> Result { + let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string())); + let problem = match read() { + Ok(token) => return Ok(token), + Err(problem) => problem, + }; + if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) { + return Err(problem); + } + log::warn!("{problem}; writing a new token file"); + std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?; + read() +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index b1c005dadf..2290c7c08f 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -5,8 +5,9 @@ //! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the //! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued //! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees -//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes -//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]). +//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's +//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through +//! [`crate::screenshot::Captures`]). //! //! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch //! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave @@ -15,6 +16,7 @@ use std::sync::mpsc::{Receiver, Sender}; +use craft_ui::dialog::{DialogHost, DialogId, HeldOk}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; @@ -133,6 +135,19 @@ pub enum Reply { /// A `ui.accessTree`: hold the reply until the window's settled access tree can be read /// ([`ControlChannel::poll_access_trees`]). AccessTree, + /// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the + /// app answers it ([`ControlChannel::poll_held`]). + #[non_exhaustive] + AfterHeldOk { + /// The dialog whose OK is held. + dialog: DialogId, + /// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog + /// is not the one the request confirmed. + open: u64, + /// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it: + /// the earlier confirms still held for this open are answered with it. + refused: Option, + }, } impl Reply { @@ -174,6 +189,7 @@ pub struct ControlChannel { input_waiters: Vec>, job_waiters: Vec<(JobId, Sender)>, tree_waiters: Vec>, + held_waiters: Vec<(DialogId, u64, Sender)>, /// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases. pub captures: Captures, } @@ -181,7 +197,14 @@ pub struct ControlChannel { impl ControlChannel { /// Attach a transport's receiver (TCP, stdin, tests). pub fn new(rx: Receiver) -> Self { - Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() } + Self { + rx, + input_waiters: Vec::new(), + job_waiters: Vec::new(), + tree_waiters: Vec::new(), + held_waiters: Vec::new(), + captures: Captures::default(), + } } /// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned @@ -200,8 +223,16 @@ impl ControlChannel { /// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the /// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time); - /// `document` the identity a screenshot is attributed to. + /// `document` the identity a screenshot is attributed to. A screenshot is admitted at + /// [`motion::now`]; [`Self::settle_at`] takes the time instead. pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64) { + self.settle_at(req, outcome, document, settle_ms, motion::now()); + } + + /// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its + /// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to + /// [`Captures::issue`] and [`Captures::drain`]. + pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64, now: Instant) { let reply = req.reply; match outcome { Reply::Done(v) => { @@ -210,9 +241,21 @@ impl ControlChannel { Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), Reply::AccessTree => self.tree_waiters.push(reply), + Reply::AfterHeldOk { dialog, open, refused } => { + if let Some(reason) = refused { + self.held_waiters.retain(|(earlier, earlier_open, tx)| { + let answered = (*earlier, *earlier_open) == (dialog, open); + if answered { + let _ = tx.send(json!({"ok": false, "error": reason})); + } + !answered + }); + } + self.held_waiters.push((dialog, open, reply)); + } Reply::Screenshot { token, path, region, viewport } => { let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms }; - if let Err((reply, e)) = self.captures.admit(request, motion::now()) { + if let Err((reply, e)) = self.captures.admit(request, now) { let _ = reply.send(json!({"ok": false, "error": e})); } } @@ -291,6 +334,29 @@ impl ControlChannel { } } + /// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success + /// once the app accepted the dialog's held OK; once it refused it, an error whose text is the + /// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed + /// while it waited, also when the same dialog opened again since. A request stays held while + /// the app has not answered. Call it in every pass after the app answered the held OKs it + /// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a + /// dialog the app accepted; calling it more than once in a pass is harmless. + pub fn poll_held(&mut self, host: &DialogHost) { + self.held_waiters.retain(|(dialog, open, reply)| { + let answer = match host.held_state(*dialog) { + _ if host.open_serial(*dialog) != Some(*open) => { + json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}) + } + Some(HeldOk::Waiting) => return true, + Some(HeldOk::Accepted) => json!({"ok": true, "result": null}), + Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}), + _ => json!({"ok": false, "error": "the app refused OK"}), + }; + let _ = reply.send(answer); + false + }); + } + /// Drops the host's queued input and the step in flight, and fails every /// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters /// remain (their input was already consumed). True when anything was pending or waiting. @@ -331,6 +397,6 @@ impl ControlChannel { /// Waiters of every kind, for `ui.inspect`'s `pending` count and tests. pub fn waiting(&self) -> usize { - self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending() + self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending() } } diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 398c917c57..749626cc61 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -1,7 +1,8 @@ //! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type. //! -//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s -//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its +//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits +//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the +//! `id` `inspect` lists, or `"top"` for the top one; its fields are its //! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and //! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a //! click's would. @@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt}; use egui::Context; use serde_json::{Value, json}; +use crate::control::Reply; use crate::protocol::Params; /// The most `fields` one `ui.dialog.set` call takes. @@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value { /// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field, /// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]). /// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field -/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it. +/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it; +/// a second confirm while that answer waits is refused. /// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape /// answer gives that answer, with its tag; any other dialog closes with its children with Cancel. pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { @@ -49,6 +52,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: Some(run(host, ctx, method, params, fields)) } +/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a +/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it +/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal +/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once. +pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option { + // The dialog is named before the call: a confirm that closes it may leave another dialog on top. + let named = dialog_id(host, params).ok(); + // A refusal this confirm replaces still answers the confirms it refused. + let refused = match named.and_then(|id| host.held_state(id)) { + Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()), + _ => None, + }; + let result = dialog_method(host, ctx, method, params)?; + let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting)); + Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) { + Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused }, + None => Reply::from_result(result), + }) +} + fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result { let params = Params(params).only(None, fields)?; let read = Params(¶ms); @@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field } }, "ui.dialog.confirm" => { + // A second OK while the first waits files nothing, as the disabled button shows. + if host.held_state(id) == Some(HeldOk::Waiting) { + return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned()); + } if let Some(choice) = params.get("choice") { host.set_json_field(ctx, id, "choice", choice.clone())?; } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 259d2f3cb2..8e75f07ecd 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -8,8 +8,11 @@ //! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept //! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it. +#[cfg(not(windows))] use std::fs::OpenOptions; -use std::io::{BufRead, Write}; +use std::io::BufRead; +#[cfg(not(windows))] +use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; @@ -319,30 +322,34 @@ fn read_token_file(path: &Path) -> Result { Ok(token) } -fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { +/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one +/// that caused it, with the path in its message. +fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> { + let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display())); if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?; + std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?; } - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token - // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + // On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's + // access list, and the token is written through the handle that created it. #[cfg(windows)] { use craft_platform::owner_only; - if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { - drop(file); - let _ = std::fs::remove_file(path); - return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + owner_only::current_user_sid() + .and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes())) + .map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) + } + #[cfg(not(windows))] + { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); } + let mut file = options.open(path).map_err(|e| at(path, e))?; + writeln!(file, "{token}").map_err(|e| at(path, e)) } - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } /// The server's token, lower-cased. Both given is @@ -355,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// file can be reached by others: ; restrict it to its owner`), and its trimmed content is /// validated. A missing one is created with a generated token (parent directories created, /// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a -/// newline); losing that create race to another process reads the winner's file instead. +/// newline); losing that create race to another process reads the winner's file instead. On +/// Windows a create that does not finish in time fails (`I/O: : cannot create the control +/// token file for its owner only: `), and a file it left at the path is not read as a winner's. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { + server_token_with(supplied, token_file, create_token_file) +} + +/// [`server_token`], with `create` making a missing token file. +fn server_token_with( + supplied: Option<&str>, + token_file: Option<&Path>, + create: impl FnOnce(&Path, &str) -> std::io::Result<()>, +) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); } @@ -370,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result }; match read_token_file(path) { Ok(existing) => Ok(existing.to_ascii_lowercase()), - Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) { + Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) { Ok(()) => Ok(token), - // Another process won the create-new race. - Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), - Err(e) => Err(e), + // Another process won the create-new race. A file left by a create that ran out of time is this one's. + Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), + Err(e) => Err(AutomationError::Io(e.to_string())), }, Err(e) => Err(e), } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index b5ba980c95..2716fc24c2 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -141,6 +141,12 @@ fn server_token_sources_and_validation() { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); } + #[cfg(windows)] + { + use craft_platform::owner_only; + let sddl = owner_only::sddl_of(&file).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); + } assert_eq!(server_token(None, Some(&file)).unwrap(), created); // An existing file's content is trimmed and lower-cased. @@ -163,3 +169,25 @@ fn server_token_sources_and_validation() { "bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE" ); } + +// A token file create that runs out of time fails with its own error, even when it left a file at +// the path: that file is not read as another process's. A create that another process beat to the +// path reads that process's token. +#[trial] +fn a_token_file_create_that_runs_out_of_time_is_an_error() { + let dir = scratch_dir("token-limit"); + let file = dir.join("token"); + let late = |p: &Path, _: &str| { + std::fs::write(p, "partial").unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display()))) + }; + let err = server_token_with(None, Some(&file), late).unwrap_err().to_string(); + assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}"); + std::fs::remove_file(&file).unwrap(); + let beaten = |p: &Path, _: &str| { + create_token_file(p, TOKEN).unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")) + }; + assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index bea9c8d5a5..31481f4cb1 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ //! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`, -//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. +//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -12,7 +12,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -22,8 +23,7 @@ //! //! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action //! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a -//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a -//! drag is `ui.click {hold}`, `ui.move` and `ui.release`. +//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. use std::path::PathBuf; @@ -43,6 +43,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -302,6 +308,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?, control?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are placed before anything is queued (a control point against the access tree the host kept for + /// `viewport`), so a point that cannot be placed leaves no press down. When the host withdraws the rest of the + /// gesture after its press ran, the button stays down until `ui.release`, as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.place(host, viewport, map)?, self.to.place(host, viewport, map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// The most notches one `ui.wheel` turn in lines may ask for, either way. pub const MAX_NOTCHES: f32 = 100.0; @@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V "ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)), "ui.drop" => drop_files(params, host, viewport, map), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 7ca7bb5f0c..9238151b96 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -3,8 +3,8 @@ use std::net::TcpListener; use std::path::PathBuf; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; use std::time::Duration; use craft_automation::agents::AgentLinkStatus; @@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage; use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; use craft_ui::contract::Role; use craft_ui::patterns::preferences::SettingsDraft; -use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::Fixture; use craft_ui::testing::trial; @@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = motion::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has +/// finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), } - std::thread::sleep(Duration::from_millis(5)); + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() } - true } /// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. @@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and -/// its thread ends once the last clone is dropped. +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll, +/// and its thread ends at the first poll after the last clone is dropped. #[trial] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); @@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); // Many polls with nothing changed. - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - // The thread sees the switch gone at its next poll and stops probing. - std::thread::sleep(Duration::from_millis(50)); - let after_drop = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } /// A published connection reads back in its documented shape, and only the process that wrote it removes it. @@ -308,6 +338,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() { TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); } +/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the +/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every +/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again. +#[trial] +fn a_refused_token_file_is_not_retried_until_the_settings_change() { + let dir = temp_dir("link-token-no-retry"); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let wanted = free_port(); + assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + // The file is fixed, but the same settings don't look at it again. + std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let same = link.sync(Some(&on(u32::from(wanted))), &host); + assert!(same.requests.is_none() && !same.changed, "no retry with the same settings"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + let changed = link.sync(Some(&on(0)), &host); + assert!(changed.requests.is_some(), "a settings change tries again"); + assert_eq!(link.status().problem, None); +} + +/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its +/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can +/// connect instead of staying out until someone deletes the file (photocraft#17006). +#[trial] +fn a_refused_token_file_is_replaced_with_a_new_token() { + let dir = temp_dir("link-token-refresh"); + let file = dir.path().join(TOKEN_FILE); + std::fs::write(&file, "not a token\n").unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + let token = std::fs::read_to_string(&file).unwrap(); + assert_ne!(token.trim(), "not a token"); + assert_eq!(token.trim().len(), 64, "a new token: {token:?}"); + assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening")); +} + +/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows +/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time. +#[trial] +fn a_taken_port_retry_reuses_the_checked_token() { + let dir = temp_dir("link-token-reuse"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + // Reading the file now fails, so a retry that read it would report a token file problem. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let retried = link.sync(Some(&on(port)), &host); + assert!(retried.requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + + // Once a start succeeded, the next one reads the file again. + let moved = link.sync(Some(&on(0)), &host); + assert!(moved.requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + +/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token +/// file again, so a server never listens with a token the file no longer holds. +#[trial] +fn a_settings_change_reads_the_token_file_again() { + let dir = temp_dir("link-token-settings"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + assert!(!link.sync(None, &host).stopped, "nothing was running"); + // While agents are off the token file changes; here it can't be read at all, which the next start must report. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let back = link.sync(Some(&on(port)), &host); + assert!(back.requests.is_none(), "started with the token the file no longer holds"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + /// Dropping the link stops its server and removes its connection file. #[trial] fn dropping_the_link_removes_its_connection_file() { diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index ad6986f096..b15b926dcd 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -1,9 +1,13 @@ //! `ui.dialog.*` on typed dialogs through one generic path. -use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect}; +use std::sync::mpsc::{Receiver, channel}; + +use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse}; +use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect}; use craft_ui::contract::{Bind, SaveKey}; -use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::{Label, Word}; use craft_ui::testing::trial; use egui::Context; use serde_json::{Value, json}; @@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() { assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); } +const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists"); + +/// The open parameter dialog `id` names. +fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog { + host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).expect("the held dialog is open") +} + +/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered, +/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog +/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a +/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once. +#[trial] +fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + let (_requests, rx) = channel(); + let mut control = ControlChannel::new(rx); + let dialog = |ctx: &Context, held: bool| { + let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields)) + }); + if held { dialog.held_ok() } else { dialog } + }; + let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver { + let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()})); + let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method"); + control.settle(request, outcome, None, 0.0); + reply + }; + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + control.poll_held(&host); + assert!(reply.try_recv().is_err(), "the reply waits for the app's answer"); + assert_eq!(control.waiting(), 1); + let again = confirm(&mut host, &mut control, id); + assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused"); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 0); + + // A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal. + let first = confirm(&mut host, &mut control, id); + assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some()); + held(&mut host, id).answer_ok(Ok(())); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null}))); + assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes"); + assert!(matches!(host.take_keyed::(), Some((DialogResult::Ok(_), _)))); + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + control.poll_held(&host); + let closed = reply.try_recv().expect("a closed dialog answers the held confirm"); + assert_eq!(closed["ok"], false); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + host.take_keyed::(); + + // The same dialog opened again is a new open: its answer is not the closed one's. + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id"); + assert_eq!(control.waiting(), 1); + control.poll_held(&host); + let closed = reply.try_recv().expect("the closed open's confirm is answered"); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + assert!(host.cancel_by_id(&ctx, id)); + host.take_keyed::(); + + let id = host.open(dialog(&ctx, false)); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once"); + assert_eq!(control.waiting(), 0); +} + /// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that /// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread. #[trial] diff --git a/crates/automation/tests/it/screenshot.rs b/crates/automation/tests/it/screenshot.rs index e9f06c409e..28a0ac8f35 100644 --- a/crates/automation/tests/it/screenshot.rs +++ b/crates/automation/tests/it/screenshot.rs @@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() { } } +/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app +/// also passes to `issue` and `drain`, not from the wall clock. +#[trial] +fn a_screenshot_settled_at_a_time_counts_from_that_time() { + use craft_automation::control::{ControlChannel, ControlRequest, Reply}; + use craft_automation::screenshot::ScreenshotParams; + use serde_json::json; + + let ctx = Context::default(); + // An app clock ahead of the wall clock. + let arrived = motion::now() + Duration::from_secs(60); + let (_transport, requests) = channel(); + let mut control = ControlChannel::new(requests); + control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0)); + let (request, rx) = ControlRequest::new("ui.screenshot", json!({})); + let params = ScreenshotParams::from_params(&json!({})).expect("no params"); + control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived); + assert!(rx.try_recv().is_err(), "the reply waits for the capture"); + + let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None); + assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::>()); + assert!(callbacks.is_empty(), "not issued inside its settle delay"); + assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline"); + let finished = control.captures.drain(arrived + DEADLINE, None); + assert_eq!(finished.len(), 1); + assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0])); +} + /// Cancelling releases the budget at once; an image that arrives afterwards is dropped. #[trial] fn cancellation_releases_the_budget_and_drops_a_late_image() { diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index ee2c484f6c..dc3ca5efb6 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,12 +1,12 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::access::NO_TREE; -use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::access::{NO_CONTROL, NO_TREE}; +use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -123,6 +123,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -292,6 +338,25 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. That holds +/// for a document end without a canvas and for a control end that names no control of the window. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); + let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}}); + let answer = input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &map); + assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}"); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -358,6 +423,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "y": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})), ("ui.move", json!({"x": 10, "y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index b8572fcd05..2184f141dd 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -578,7 +578,17 @@ impl Layout

{ moving.column.groups.iter_mut().for_each(|group| group.height = height); } let index = place.group_index().ok_or(DockError::InvalidPlacement)?; - let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups; + let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?; + // Groups shown at a width of their own, in a floating window or an expanded column, keep it + // as the flyout width of the collapsed column they join. + if column.iconic + && !moving.column.iconic + && let Some(width) = moving.column.width + { + let flyout = (column.width != Some(width)).then_some(width); + moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout); + } + let groups = &mut column.groups; let index = (index + usize::from(below)).min(groups.len()); groups.splice(index..index, moving.column.groups); Ok(()) diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 442c65f8b0..74879e4676 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -42,7 +42,8 @@ pub struct Workspace

{ #[serde(default)] hidden: Vec<(P, Location

)>, /// Floating panels, and closed panels that were floating, with the docked location each one left, so Dock Panel - /// can return it. A closed panel's record lives as long as its `hidden` record. Saved with the workspace. + /// can return it; a closed panel that floats records the place it would reopen at. A closed panel's record lives + /// as long as its `hidden` record. Saved with the workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] floated: Vec<(P, Location

)>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. @@ -264,6 +265,16 @@ impl Workspace

{ Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?, _ => false, }; + // Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel + // that would reopen in a floating window has no docked place. + let hidden_place = match &action { + Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed + .restored(panel, &policy) + .filter(|restored| !floats(&restored.layout, panel)) + .and_then(|restored| restored.layout.location(panel).ok()) + .map(|location| (panel.clone(), location)), + _ => None, + }; if !reopened { // SetNative records where the window system has a floating window, so a lock // does not refuse it. @@ -278,6 +289,12 @@ impl Workspace

{ proposed.hidden.push((panel, location)); } proposed.track_floated(&before); + if let Some((panel, location)) = hidden_place + && floats(&proposed.layout, &panel) + && !proposed.floated.iter().any(|(p, _)| p == &panel) + { + proposed.floated.push((panel, location)); + } all_closed.extend(closed); } let visible: HashSet

= proposed.layout.panels().into_iter().cloned().collect(); diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..4b8355d7cf 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,7 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. +//! All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,19 +231,39 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } - /// The item with a shorter form `extent` long, which it takes before any free item leaves. + /// The item with a shorter form `extent` long, which it takes before any free item leaves unless it is late. + /// An item marked [`FitItem::short_late`] takes that form only after no free item is left to leave. pub const fn short(mut self, extent: f32) -> Self { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: lower ranks shorten first, and the last item of a rank first. + /// Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left. + /// The other items go to the overflow menu before this one shortens. A free item with a late short form leaves + /// in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +298,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +325,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 7fa0422777..4704686970 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -544,7 +544,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9; const PHI: f64 = 1.0 + INV_PHI; /// The composition guide drawn inside a crop frame, in Photoshop's menu order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropGuide { @@ -727,7 +727,7 @@ fn golden_spiral() -> Vec<[f64; 2]> { } /// When the guide shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum GuideShow { diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index bd782a0e9c..103a97fcf0 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -85,15 +85,12 @@ pub struct GridCursor { impl GridCursor { /// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A /// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share - /// does not go below it. + /// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns. pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self { let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0); let content: Vec = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect(); - let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x) - .into_iter() - .enumerate() - .map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width }) - .collect(); + let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x); + keep_fill_least(columns, &mut widths, least); let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect(); GridCursor { flow, @@ -266,6 +263,44 @@ impl GridCursor { } } +/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a +/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight. +/// The fill columns together take more than their room only when their least widths do not fit in it. +fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) { + let fills: Vec<(usize, f32)> = columns + .iter() + .enumerate() + .filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None }) + .collect(); + let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum(); + if !room.is_finite() { + // Room with no bound leaves every share above its least. + for (i, _) in &fills { + widths[*i] = widths[*i].max(least(*i)); + } + return; + } + let mut raised = vec![false; columns.len()]; + loop { + let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::(); + let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum(); + let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 }; + let mut more = false; + for (i, weight) in &fills { + if !raised[*i] && share(*weight) < least(*i) { + raised[*i] = true; + more = true; + } + } + if !more { + for (i, weight) in &fills { + widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) }; + } + return; + } + } +} + /// `columns` with each `Fill` column as a `Content` column. fn as_content(columns: &[ColumnWidth]) -> Vec { columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect() @@ -288,4 +323,43 @@ mod tests { cursor.cell(Vec2::new(150.0, 100.0)); assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds"); } + + /// The widths of one row of `columns` placed by `last`, read from the cells. + fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec { + let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last); + columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect() + } + + #[test] + fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &fitting); + let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0])); + assert!(shares[0] < 120.0, "the first column's share is below its least"); + assert!(raised[0] >= 120.0, "the first column keeps its least"); + assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow"); + assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights"); + assert_eq!(raised[3], shares[3], "the content column keeps its width"); + assert_eq!(raised.iter().sum::(), 300.0, "the row fills the grid and no more"); + } + + #[test] + fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]); + let widths = row_widths(&columns, &last); + assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least"); + assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room"); + assert_eq!(widths.iter().sum::(), 330.0, "the row is as wide as the least widths and no wider"); + } + + #[test] + fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &last); + let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0])); + assert_eq!(kept, shares); + } } diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index 0aae495027..af3c06e5d1 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool { } /// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can -/// tell it from a number or an operator. +/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch). pub fn is_unit_spelling(spelling: &str) -> bool { - !spelling.is_empty() && spelling.chars().all(is_unit_char) + let letters = spelling.strip_prefix('/').unwrap_or(spelling); + !letters.is_empty() && letters.chars().all(is_unit_char) } /// A unit spelling and the factor that turns its quantity into the base unit. @@ -41,7 +42,9 @@ struct Unit { /// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it /// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest /// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a -/// quantity when `px` is registered. A group separator counts only before exactly three digits. +/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after +/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before +/// exactly three digits. #[derive(Clone, Debug, PartialEq)] pub struct Reader { decimal: char, @@ -79,7 +82,8 @@ impl Reader { self } - /// The digit-group separator, which the reader skips between digits. + /// The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a + /// decimal when it is the number's only separator and digits follow it. #[must_use] pub fn group(mut self, group: char) -> Self { self.group = Some(group); @@ -213,8 +217,9 @@ impl Parse<'_> { } } - /// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no - /// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it. + /// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a + /// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them, + /// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide. fn quantity(&mut self, scaled: bool) -> Result { let number = self.number()?; self.tag = None; @@ -223,8 +228,11 @@ impl Parse<'_> { return Ok(number / 100.0); } let reader = self.reader; - let run: Vec = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); - let unit = (1..=run.len()).rev().find_map(|len| { + let after = &self.chars[self.at..]; + let slash = usize::from(after.first() == Some(&'/')); + let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count(); + let run = &after[..slash + letters]; + let unit = (1 + slash..=run.len()).rev().find_map(|len| { let lowered = run[..len].iter().collect::().to_lowercase(); reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit)) }); @@ -243,11 +251,6 @@ impl Parse<'_> { } } - /// Whether the group separator at `at` is followed by exactly three digits. - fn three_digits_after(&self, at: usize) -> bool { - self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3 - } - fn number(&mut self) -> Result { let mut text = String::new(); let mut seen_decimal = false; @@ -257,7 +260,16 @@ impl Parse<'_> { } else if c == self.reader.decimal && !seen_decimal { seen_decimal = true; text.push('.'); - } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) { + } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() { + let after = &self.chars[self.at + 1..]; + let digits = after.iter().take_while(|c| digit(**c).is_some()).count(); + let only_mark = after.get(digits).is_none_or(|&next| next != c && next != self.reader.decimal); + if text == "0" && matches!(c, '.' | ',') && digits > 0 && only_mark { + seen_decimal = true; + text.push('.'); + } else if digits != 3 { + break; + } } else { break; } @@ -274,6 +286,28 @@ impl Parse<'_> { mod tests { use super::*; + #[test] + fn a_single_group_mark_after_zero_reads_as_a_decimal() { + for (decimal, group) in [('.', ','), (',', '.')] { + let reader = Reader::new().decimal(decimal).group(group).unit("cm", 2.0); + for (text, want) in [ + (format!("0{group}125+2"), 2.125), + (format!("2x0{group}125"), 0.25), + (format!("-0{group}25 cm"), -0.5), + (format!("٠{group}١٢٥"), 0.125), + (format!("1{group}125"), 1125.0), + (format!("1{group}234{decimal}5"), 1234.5), + (format!("0{group}123{group}456"), 123456.0), + (format!("0{group}125{decimal}5"), 125.5), + ] { + assert_eq!(reader.read(&text, None), Ok(want), "{text}"); + } + assert_eq!(reader.read(&format!("0{group}"), None), Err(NotAValue)); + } + let swiss = Reader::new().group('\''); + assert_eq!(swiss.read("0'125", None), Ok(125.0)); + } + #[test] fn expressions_units_and_relative_input_read_through_one_grammar() { let reader = Reader::new().decimal(',').group('.').unit("in", 72.0).unit("pt", 1.0); @@ -326,6 +360,20 @@ mod tests { near(&percent, "2%", 14.0); assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share"); + let per_inch = Reader::new().unit_tagged("/in", 1.0, 0); + assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in")); + for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] { + near(&per_inch, text, 40.0); + } + assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit"); + assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product"); + assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value"); + for bad in ["", "/in", "40/inch", "40/"] { + assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value"); + } + near(&lengths, "144/2in", 1.0); + assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number"); + let german = Reader::new().decimal(',').group('.'); near(&german, "1.234,5", 1234.5); near(&german, "1.234.567", 1_234_567.0); diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 1985e4bf9c..12c36a01e3 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -66,6 +66,15 @@ pub struct Wheel { pub lines: Vec2, /// Zoom factor; 1 for none. pub zoom: f32, + /// The wheel motion that reached the share as `zoom` instead of `scroll`, in wheel lines: wheel events under the + /// zoom modifier, and the Ctrl+wheel steps the service reads as a touchpad's pinch on Windows and Linux. A line + /// event counts its lines (notches) as the device sent them, a point or page event its points over egui's line + /// scroll speed. It travels with the zoom share, so a taker can count the notches or lines of a Ctrl+wheel that + /// zooms without the zoom speed; zero for a native pinch and for a wheel without the modifier. + pub zoom_lines: Vec2, + /// The running gesture's `zoom_lines` gathered so far, this share included, for the taker that owns the gesture; + /// another taker's share gathers only itself, as with `gathered`. + pub zoom_gathered: Vec2, /// The modifiers held. pub mods: Mods, /// The unit the device reported. @@ -224,6 +233,8 @@ impl Wheel { scroll, lines: Vec2::ZERO, zoom: 1.0, + zoom_lines: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, mods, unit, phase, @@ -245,6 +256,13 @@ impl Wheel { self } + /// The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). + #[must_use] + pub const fn zoom_lines(mut self, lines: Vec2) -> Self { + self.zoom_lines = lines; + self + } + /// The same gesture with the two-finger touch zoom factor `zoom`. pub const fn touch_zoom(mut self, zoom: f32) -> Self { self.touch_zoom = zoom; @@ -563,13 +581,28 @@ fn for_field(wheel: &Wheel) -> bool { /// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values. fn pinches(wheel: &Wheel) -> bool { - wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO + wheel.zoom != 1.0 + || wheel.zoom_lines != Vec2::ZERO + || wheel.touch_zoom != 1.0 + || wheel.rotation != 0.0 + || wheel.touch_rotation != 0.0 + || wheel.touch_pan != Vec2::ZERO } /// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region /// never reads one. const fn scroll_only(wheel: Wheel) -> Wheel { - Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel } + Wheel { + zoom: 1.0, + zoom_lines: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, + touch_zoom: 1.0, + rotation: 0.0, + touch_rotation: 0.0, + touch_pan: Vec2::ZERO, + zooms: false, + ..wheel + } } /// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes @@ -715,6 +748,7 @@ fn split_at( Some((_, share)) => { share.scroll += part.scroll; share.zoom *= part.zoom; + share.zoom_lines += part.zoom_lines; share.touch_zoom *= part.touch_zoom; share.rotation += part.rotation; share.touch_rotation += part.touch_rotation; diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index ba1ff28419..be5f2b3a8b 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -247,6 +247,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() { assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record"); } +/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old +/// group keeps its front tab; docking it then returns it to that group at its old index. +#[test] +fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() { + let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0)); + let mut opened = Workspace::new(docked()); + opened.apply(Action::close(2), false, allow).unwrap(); + opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap(); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(float, false, allow).unwrap(); + let layout = workspace.layout(); + assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. }))); + assert_eq!(group_members(layout, 3), [3]); + assert_eq!(front(layout, 3), 3, "the old group keeps its front tab"); + assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives"); + + let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) }; + let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone()); + workspace.apply(back, false, allow).unwrap(); + assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index"); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(6), false, allow).unwrap(); + workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place"); +} + /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); @@ -290,6 +319,45 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect"); } +/// A group docked into a collapsed column keeps the width it was shown at as its flyout width: a floating window's +/// width, or an expanded column's. A width equal to the column's leaves the flyout following the column, and a group +/// moved between collapsed columns keeps its own flyout width. +#[test] +fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() { + let flyout = |layout: &Layout, panel: u32| layout.group(&layout.place(&panel).unwrap()).unwrap().flyout_width; + + let mut layout = columns(); + layout.apply(Action::move_floating(6, rect(100.0, 100.0, 420.0, 400.0))).unwrap(); + layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert!(!floats(&layout, 6) && column_of(&layout, 6).iconic); + assert_eq!(flyout(&layout, 6), Some(420.0), "the floating window's width"); + + layout.apply(Action::resize_flyout_width(6, Some(380.0))).unwrap(); + layout.apply(Action::move_group(6, Target::float(rect(100.0, 100.0, 380.0, 400.0)))).unwrap(); + layout.apply(Action::set_iconic(6, false)).unwrap(); + layout.apply(Action::move_floating(6, rect(100.0, 100.0, 300.0, 400.0))).unwrap(); + layout.apply(Action::move_group(6, Target::at(4, DockPlacement::group(false, None)))).unwrap(); + assert_eq!(flyout(&layout, 6), Some(300.0), "the width the window was resized to, not the flyout width it left with"); + + let mut layout = columns(); + layout.apply(Action::resize_column(2, 260.0)).unwrap(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 2), Some(260.0), "the expanded column's width"); + + let mut layout = columns(); + layout.apply(Action::resize_column(3, 300.0)).unwrap(); + layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 6), None, "a width equal to the column's follows the column"); + + let mut layout = columns(); + let start = Node::dock(DockEdge::Start, vec![Column::new(vec![g(&[7], 0)]).with_iconic(true)]); + let Some(root) = layout.root.take() else { panic!("no root") }; + layout.root = Some(Node::split(Axis::X, SplitSize::FixedFirst(48.0), start, root)); + layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); + layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own"); +} + /// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a /// column float in its state; groups joining a column, docked or floating, take that column's state. #[test] diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e83b868ce2..4251b79efb 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -351,7 +351,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { return Some(Format::SubViewer); } - if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) { + if !first_lines.is_empty() + && head.lines().map(str::trim_start).filter(|line| !line.trim().is_empty()).take(3).all(|line| vplayer::split_line(line).is_some()) + { return Some(Format::VPlayer); } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index 169e4f24a0..bcc834f58a 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -49,7 +49,7 @@ pub fn parse(text: &str) -> Result { if line.trim().is_empty() { continue; } - match split_line(line.trim()) { + match split_line(line.trim_start()) { Some((t, raw)) => { let lines: Vec = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect(); starts.push((t, lines.join("\n"))); @@ -121,6 +121,38 @@ pub fn write(doc: &Document) -> String { mod tests { use super::*; + #[test] + fn empty_clearing_lines_keep_each_separator() { + for separator in [":", "=", " "] { + for indent in ["", " \t"] { + let input = format!("{indent}00:00:01{separator} hello \n{indent}00:00:02{separator} \n"); + assert_eq!(crate::detect(input.as_bytes(), None), Some(crate::Format::VPlayer), "{input:?}"); + let doc = parse(&input).unwrap(); + assert_eq!(doc.cues.len(), 1, "{input:?}"); + assert_eq!(doc.cues[0].text, "hello", "{input:?}"); + assert_eq!(doc.cues[0].end, ms_to_tick(2000), "{input:?}"); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + } + } + } + + #[test] + fn detection_keeps_clearing_lines_at_each_sampled_position() { + for separator in [":", "=", " "] { + for at in 0..3 { + let mut lines = ["00:00:01=one".to_owned(), "00:00:02=two".to_owned(), "00:00:03=three".to_owned()]; + lines[at] = format!(" \t00:00:0{}{separator} \t", at + 1); + let input = format!("\u{feff}\n \t\n{}\n", lines.join("\n")); + let format = crate::detect(input.as_bytes(), None).unwrap(); + assert_eq!(format, crate::Format::VPlayer, "{input:?}"); + let document = crate::parse(input.as_bytes(), format).unwrap(); + assert_eq!(document.cues.len(), 2, "{input:?}"); + assert!(document.warnings.is_empty(), "{:?}", document.warnings); + } + } + assert_eq!(crate::detect(b"00:00:01 hello\n00:00:02\n", None), None); + } + #[test] fn short_duration_cue_preserves_positive_duration_on_write_and_read() { let mut doc = Document::default(); diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml index f208a7ef47..9847550082 100644 --- a/crates/cdr/Cargo.toml +++ b/crates/cdr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-cdr" -description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings, and a .cmx writer in the layouts it reads" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index a7974a705d..772f915350 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -1,8 +1,10 @@ # Where each layout comes from The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15 -files by the same rows, with R64 to R73 for what only the writer needs. Code cites a row by its id -(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here. +files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer +(`src/cmx_write.rs`) writes in them, with R74 and R77 for what only it needs ("Written fields" lists each +field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a +cited id has no row here. Sources: @@ -54,10 +56,20 @@ Sources: https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, was read for the order of fields that the notes do not spell out (the table entries, the rendering attributes and the curve body); no code was copied from it +- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h` + and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h + and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h, + read for the header's offsets, the index chunks and the fields of a color entry; no code was + copied from it Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks -confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; -listed so it can be checked against a file, with what the reader does when it is wrong). +confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows; +listed so it can be checked against a file, with what the reader does when it is wrong). The +"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test +files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and +the synthetic test files do not set, chosen by the writer). Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the @@ -124,9 +136,9 @@ file is committed. | R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | -| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | | R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | -| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | +| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | | R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | | R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | @@ -142,3 +154,43 @@ file is committed. | R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) | | R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | | R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | +| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | +| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | + +## Written fields + +`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table +lists every field it sets. `own` marks a value the reader does not read, which the writer sets as +the synthetic test files of `src/synth_cmx.rs` set it. The header's bounds and instruction count +at bytes 96 to 116 are not written. + +| Field written | Rows | Status | +|---|---|---| +| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample | +| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) | +| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | +| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) | +| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | +| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) | +| `rlst` for each page: its layers' numbers | R77 | sample | +| Table counts and field lists | R55 | sample | +| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) | +| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) | +| `rpen` field 1: the width | R57 | public-notes | +| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own | +| `rott` field 1: the flags 2, 4, 8 and 16, the caps and the join | R57 | public-notes | +| `rdot` field 1: a count and the lengths in whole outline widths | R57 | public-notes | +| `rdot` field 1 of a solid outline's pattern: a count of 0 | R57, R58 | sample | +| `rotl` field 1: six entries, the screen and the arrowhead pair always 1, a solid outline's dash pattern the entry with a count of 0 | R58 | sample | +| `rota`: one pair of 0 | R59 | sample | +| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample | +| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) | +| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) | +| Begin page, field 1 after the edges: the offset of the end-page instruction, the layer count and the instruction count | R77 | sample | +| Begin page, field 4: the page's width and height | R61 | public-notes | +| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 4 zero bytes, the layer's instruction count, then the name as a u16 byte count and 8-bit characters | R62, R77 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the count; the name), own (the 4 bytes) | +| Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes | +| Begin group, field 1: the edges of the group's curves as the page's are measured (all 0 for a group with none), the groups directly inside it, its instruction count and the offset of the instruction after its end | R77 | sample (the counts and the offset), public-reader (the order), the writer's choice (the edges where they differ from the points' edges, as for a page) | +| End layer, group and page with no fields | R60 | own (the bodies are not read) | +| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) | +| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 37a3424e2e..e86a8aa393 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -97,6 +97,43 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h path is left out and the objects it clips are read without it. Files in big-endian byte order and files with 16-bit coordinates are refused. +`write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx` +reads, so that `read_cmx` leaves nothing out because of the `Limits` given: pages with their +sizes, layers with their names, groups, and curves with uniform fills and outlines. What the file +holds differently from the drawing is reported, as below. Rectangles and ellipses are +written as curves, and a clipping container as a group of its fill, the objects it clips +(unclipped) and its outline. A rounded rectangle scaled differently along its two sides gets round +corners, not stretched ones. Hidden layers, groups and shapes, guide and grid layers, guidelines +and master layers are left out; opacity, blend modes, fill rules and locked states are not +written, desktop layers are written as drawing layers, and a spot color with no name opens as a +process color; every use of a named spot color takes the look of its use at the strongest tint +among the uses whose look is known. Each color entry holds the color twice: as the property list +`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In +those fields a spot color is written as its look at its tint, and the registration color as 100 +percent cyan, magenta, yellow and black. + +`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width +past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than +65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a +dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, a depth limit +of 0 (at which `read_cmx` leaves out the index list), more than 65,535 groups directly inside one +group, more chunks, +objects, coordinates or dashes than a read within the limits takes, a file longer than their input +size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes +rounded to whole outline widths, nonzero fills that may fill differently, names that open +shortened, spot colors at a tint too low to keep their look, with no name or with no known look +(written black), uses of one ink with different looks, and what was left out or written opaque, +unclipped or unlocked. + +The file holds an index, so that a reader that finds the tables and pages through it, rather than +by their chunk ids, opens it: the header gives where the master index starts, the index list +(`LIST indx`) gives where each table, page, page reference list and layer starts, and the page, +layer and group records give their instruction counts. A page's record also gives where its +end-page instruction starts, and a group's record gives where the instruction after its end-group +instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or +of the page when it has none. The header's bounds and instruction count are not written. +`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. + ## Writing `write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member, @@ -157,8 +194,8 @@ degree of its angle. ## Provenance -`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer -needs, with their public sources and status. +`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writers +need, with their public sources and status. Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the `synth` feature); no third-party file is committed. diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs new file mode 100644 index 0000000000..53d0ec8664 --- /dev/null +++ b/crates/cdr/src/cmx_write.rs @@ -0,0 +1,1834 @@ +//! Writer for `.cmx` exchange files with 32-bit coordinates, in the layouts [`crate::read_cmx`] +//! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and +//! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for +//! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines +//! (R63), and the index that gives where each of them starts (R77). `PROVENANCE.md`'s "Written +//! fields" lists every field the writer sets and where its layout comes from. +//! +//! Rectangles and ellipses are written as curves. A clipping container is written as a group of +//! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes, +//! guide and grid layers, guidelines and master layers are left out. Opacity, blend modes, fill +//! rules (a curve fills even-odd) and locked states are not written, and [`Written`] reports each +//! of these that the drawing held. The drawing's version is not written either; the file opens +//! with version 0. + +use std::collections::HashMap; +use std::hash::Hash; + +use crate::Error; +use crate::model::{Blend, Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Path, Pt, Segment, Shape, SubPath}; + +/// The size of a coordinate unit written: 0.1 µm, the unit of every sample file with 32-bit +/// coordinates (R54). +const UNIT_METERS: f64 = 1e-7; +/// Coordinate units per point. +const UNITS_PER_PT: f64 = 0.0254 / 72.0 / UNIT_METERS; +/// The most points one curve holds: its points field is at most 65,535 bytes long with its 3-byte +/// header, and holds a u16 count and 9 bytes for each point (R55, R62). +pub const MAX_CURVE_POINTS: usize = (u16::MAX as usize - 3 - 2) / 9; +/// The most UTF-16 units of a layer name or a color name written, as many as the reader takes in +/// (it keeps the first [`crate::records::MAX_NAME`] and a hash of the rest). +const MAX_NAME_UNITS: usize = 4096; +/// The most 8-bit characters of a layer name written, as many as the reader keeps. +const MAX_NAME_BYTES: usize = crate::records::MAX_NAME; +/// The most entries one table holds: its count is a u16 (R55), and objects name entries by a u16 +/// from 1. +const MAX_ENTRIES: usize = u16::MAX as usize; +/// The screen entry's field 1, as the sample files with 32-bit coordinates write it (R74). +const SCREEN: [u8; 13] = [0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xa5, 0xae, 0x02, 0x00]; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const CURVE: i16 = 67; + +// Point type bytes (R16): bits 7 and 6 give the operation, bit 3 closes the subpath. Bit 2, which +// the reader does not read, is set on every node and left clear on control points, as the test +// files of `synth_cmx` set it. +const MOVE: u8 = 0x04; +const LINE: u8 = 0x44; +const CURVE_END: u8 = 0x84; +const CONTROL: u8 = 0xC0; +const CLOSES: u8 = 0x08; + +/// A written file and what it changed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Written { + /// The file. + pub bytes: Vec, + /// A path held more than [`MAX_CURVE_POINTS`] points and was written as several curves in a + /// group, so overlapping parts of its fill may draw differently. + pub split_paths: bool, + /// A filled or outlined shape had a subpath of more than [`MAX_CURVE_POINTS`] points, which was + /// cut into open pieces, so its fill draws differently and its outline gets caps, and starts + /// its dashes again, where the pieces meet. + pub cut_subpaths: bool, + /// A dash or gap length was rounded to a whole number of outline widths, the unit the dash + /// table stores (R57), held to the 65,535 widths a length there holds, or, when it is not a + /// number, stored as 0. + pub rounded_dashes: bool, + /// A layer or spot color name is longer than the 256 UTF-16 units the reader keeps whole, or + /// ends in NUL characters, which the reader drops, so it opens shortened. Past 4,096 units it + /// is also cut when written. Two spot colors whose names differ only in what is cut or dropped + /// open as one. A layer name that holds a NUL opens cut there, and one of only white space + /// opens with no name. + pub long_names: bool, + /// A spot color's tint is too low for its ink's look to open again: the record stores the color + /// with its tint applied in 8-bit values (R14), so at 0 % it is white and at a low tint the + /// look opens changed. + pub zero_tints: bool, + /// A shape filled with the nonzero rule may fill differently with the even-odd rule every + /// curve is written with: one of its cubics loops, one of its subpaths crosses or touches + /// itself or loops over itself, or two turn the same way and their boxes overlap, measured + /// with each cubic flattened to 16 lines, with two lines that are not neighbors taken to cross + /// when they are closer than the cubics may stray from them, and with two neighbors taken to + /// cross when the curves along them may meet away from their shared point. Past 50,000,000 comparisons of edges and boxes in one + /// file, a shape is taken to fill differently. + pub nonzero_fills: bool, + /// A spot color has no name, so it opens as a process color, its look at its tint: the reader + /// takes a color without a name as a process color. + pub unnamed_spots: bool, + /// A spot color's look is unknown in every use of its name (or, for a spot color with no name, + /// in that use), so it is written, and opens, as black at its tint. + pub unknown_looks: bool, + /// A spot color name was used with different looks, and a use was written with the look of + /// the use at the strongest tint among the uses whose look is known, so that it opens more than 2/255 off what its own look would + /// open as, or off its own look where its own look would not. + pub merged_looks: bool, + /// The drawing held what the file does not hold: hidden layers, groups or shapes, guide and + /// grid layers, guidelines and master layers (left out), opacity below 1 or a blend mode + /// (written opaque and normal), clipping (written unclipped), locked layers, groups or shapes + /// (written unlocked), art on a desktop layer (written on a drawing layer), shapes whose paths + /// have no segments (left out) or a layer with nothing on it (written, and left out by the + /// reader). + pub left_out: bool, +} + +/// Write `drawing` as a `.cmx` file that a read within `limits` takes all of, as +/// [`crate::write_cmx`] describes. Coordinates are rounded to 0.1 µm. A page without its own size takes the drawing's; +/// with neither, it opens with no size. An all-zero dash pattern is solid and stores no lengths. +pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result { + let mut w = Writer { + limits, + // The RIFF header, the form type and the `cont` chunk. + file_bytes: 12 + 8 + 180, + looks: spot_looks(drawing), + crossing_budget: CROSSING_BUDGET, + left_out: !drawing.master.is_empty() || !drawing.guides.is_empty(), + ..Writer::default() + }; + // The RIFF chunk's size, counted as each child is made: the form type, then the children, each a + // whole chunk with its pad byte. + let mut size = 4u32; + let mut children = Vec::new(); + let mut add = |c: Vec| -> Result<(), Error> { + size = u32::try_from(c.len()).ok().and_then(|n| size.checked_add(n)).ok_or(Error::Limit("chunk size"))?; + children.push(c); + Ok(()) + }; + // The header's index offset is set once the index is placed. + add(chunk(b"cont", &cont(0))?)?; + // Each page chunk and its reference list, with where they start in the file and the start and + // name of each of the page's layers. + let mut pages = Vec::new(); + let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> { + let at = w.file_bytes; + let (c, written) = w.page(n, size, layers)?; + add(c)?; + let refs = w.file_bytes; + let r = chunk(b"rlst", &reference_list(written.len()))?; + w.check_bytes(r.len())?; + w.file_bytes += r.len(); + add(r)?; + pages.push(PageAt { at, refs, layers: written }); + Ok(()) + }; + for (n, p) in drawing.pages.iter().enumerate() { + page(&mut w, n, p.size.or(drawing.page_size), &p.layers)?; + } + // A drawing with no pages but a page size is written as one empty page of that size. + if drawing.pages.is_empty() && drawing.page_size.is_some() { + page(&mut w, 0, drawing.page_size, &[])?; + } + // The reader leaves out a list as deep as its depth limit, and the index is a list. + if w.limits.depth == 0 { + return Err(Error::Limit("nesting depth")); + } + // The reader also counts every chunk (`cont`, each page and its reference list, the seven + // tables, and the index list with its three chunks and a layer table for each page), every + // table entry and the one arrowhead pair. + let t = &w.tables; + let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1; + let index_chunks = pages.len().saturating_add(4); + w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + 2 * pages.len() + 7 + entries + index_chunks); + w.read_cost.check(&w.limits)?; + // Where each table chunk starts, by its id. + let mut tables = Vec::new(); + let mut at = w.file_bytes; + for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? { + let id: [u8; 4] = c[0..4].try_into().map_err(|_| Error::Limit("chunk size"))?; + tables.push((id, at)); + at = at.saturating_add(c.len()); + add(c)?; + } + let (list, ixmr) = index(at, &pages, &tables)?; + add(list)?; + let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?; + if total > w.limits.input { + return Err(Error::Limit("input size")); + } + children[0] = chunk(b"cont", &cont(ixmr))?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; + bytes.extend(b"RIFF"); + bytes.extend(size.to_le_bytes()); + bytes.extend(b"CMX1"); + for c in children { + bytes.extend(c); + } + Ok(Written { + bytes, + split_paths: w.split_paths, + cut_subpaths: w.cut_subpaths, + rounded_dashes: w.rounded_dashes, + long_names: w.long_names, + zero_tints: w.zero_tints, + nonzero_fills: w.nonzero_fills, + unnamed_spots: w.unnamed_spots, + unknown_looks: w.unknown_looks, + merged_looks: w.merged_looks, + left_out: w.left_out, + }) +} + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). A body past +/// what the size holds is an [`Error::Limit`]. +fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { + let size = u32::try_from(body.len()).map_err(|_| Error::Limit("chunk size"))?; + let mut out = Vec::with_capacity(body.len() + 9); + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + Ok(out) +} + +/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 +/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file +/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the +/// picture of the drawing, which the file does not hold (R77); the rest are zeros. +fn cont(ixmr: u32) -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = b'4'; + c[54] = b'2'; + c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); + c[84..88].copy_from_slice(&ixmr.to_le_bytes()); + c[88..96].fill(0xFF); + c +} + +/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name. +type LayerAt = (usize, Vec); + +/// Where a page's chunks start in the file, and its layers. +struct PageAt { + at: usize, + /// The page's reference list `rlst`. + refs: usize, + layers: Vec, +} + +/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16 +/// values 2 and 9 and its number. +fn reference_list(layers: usize) -> Vec { + let mut r = (layers as u16).to_le_bytes().to_vec(); + for n in 1..=layers { + r.extend([2u16, 9, n as u16].map(u16::to_le_bytes).concat()); + } + r +} + +/// A file offset as the u32 the index stores. +fn offset(at: usize) -> Result { + u32::try_from(at).map_err(|_| Error::Limit("chunk size")) +} + +/// The index list `LIST indx` starting at file offset `at` (R77): a layer table `ixlr` for each +/// page, the table of layer tables `ixtl`, the page index `ixpg` and the master index `ixmr`, with +/// the file offset of `ixmr`. `tables` gives where each table chunk starts, by its id. +fn index(at: usize, pages: &[PageAt], tables: &[([u8; 4], usize)]) -> Result<(Vec, u32), Error> { + let mut body = b"indx".to_vec(); + // Where the next chunk of the list starts. + let next = |body: &Vec| at.saturating_add(8).saturating_add(body.len()); + let mut layer_tables = Vec::with_capacity(pages.len()); + for (n, p) in pages.iter().enumerate() { + layer_tables.push(next(&body)); + // The layer count and the page number, then for each layer the size of its record before + // the 0xFFFFFFFF that ends it, its begin-layer instruction and its name. + let mut t = (p.layers.len() as u16).to_le_bytes().to_vec(); + t.extend(u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?.to_le_bytes()); + for (start, name) in &p.layers { + t.extend(((8 + name.len()) as u16).to_le_bytes()); + t.extend(offset(*start)?.to_le_bytes()); + t.extend((name.len() as u16).to_le_bytes()); + t.extend(name); + t.extend(u32::MAX.to_le_bytes()); + } + body.extend(chunk(b"ixlr", &t)?); + } + // The table of layer tables: their count, the size of each record, the type 3 and the offsets. + let ixtl = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + t.extend(4u16.to_le_bytes()); + t.extend(3u16.to_le_bytes()); + for l in &layer_tables { + t.extend(offset(*l)?.to_le_bytes()); + } + body.extend(chunk(b"ixtl", &t)?); + // The page index: the page count, then for each page the size of its record, its page chunk, + // its layer table, 0xFFFFFFFF for a picture of the page it does not have and its reference + // list. + let ixpg = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + for (p, l) in pages.iter().zip(&layer_tables) { + t.extend(16u16.to_le_bytes()); + for v in [offset(p.at)?, offset(*l)?, u32::MAX, offset(p.refs)?] { + t.extend(v.to_le_bytes()); + } + } + body.extend(chunk(b"ixpg", &t)?); + // The master index: the values 1 and 24, the entry count, then an id and an offset for itself, + // the page index, the table of layer tables and each table. + let ixmr = next(&body); + let ids: [(&[u8; 4], u16); 7] = [(b"rotl", 15), (b"rott", 16), (b"rota", 17), (b"rscr", 18), (b"rpen", 19), (b"rdot", 20), (b"rclr", 21)]; + let mut entries = vec![(1u16, ixmr), (2, ixpg), (3, ixtl)]; + for (id, n) in ids { + if let Some((_, start)) = tables.iter().find(|(t, _)| t == id) { + entries.push((n, *start)); + } + } + let mut t = [1u16, 24, entries.len() as u16].map(u16::to_le_bytes).concat(); + for (n, start) in entries { + t.extend(n.to_le_bytes()); + t.extend(offset(start)?.to_le_bytes()); + } + body.extend(chunk(b"ixmr", &t)?); + Ok((chunk(b"LIST", &body)?, offset(ixmr)?)) +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the +/// data does not fit the length. +fn field(tag: u8, data: &[u8]) -> Option> { + let len = u16::try_from(data.len() + 3).ok()?; + let mut f = Vec::with_capacity(data.len() + 3); + f.push(tag); + f.extend(len.to_le_bytes()); + f.extend(data); + Some(f) +} + +/// A field list: the fields, then 0xff (R55). +fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// An instruction: the short form when its size fits a u16 below 0xFFFF, else the long form +/// (R60). +fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = Vec::with_capacity(body.len() + 8); + match u16::try_from(body.len() + 4).ok().filter(|n| *n != u16::MAX) { + Some(n) => i.extend(n.to_le_bytes()), + None => { + i.extend(u16::MAX.to_le_bytes()); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + } + } + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// A length in points as coordinate units. +fn units(v: f64) -> Result { + let u = (v * UNITS_PER_PT).round(); + if u.is_finite() && u >= f64::from(i32::MIN) && u <= f64::from(i32::MAX) { Ok(u as i32) } else { Err(Error::Limit("coordinate range")) } +} + +/// A length that can't be negative (a width) in coordinate units. +fn width_units(v: f64) -> Result { + let u = (v.max(0.0) * UNITS_PER_PT).round(); + if u.is_finite() && u <= f64::from(u32::MAX) { Ok(u as u32) } else { Err(Error::Limit("coordinate range")) } +} + +/// The distinct entries of one table, in the order they were first used, and the 1-based index of +/// each. +struct Table { + entries: Vec, + index: HashMap, +} + +impl Default for Table { + fn default() -> Self { + Table { entries: Vec::new(), index: HashMap::new() } + } +} + +impl Table { + /// The 1-based index of `k`, added when it is new. + fn index(&mut self, k: K) -> Result { + if let Some(i) = self.index.get(&k) { + return Ok(*i); + } + if self.entries.len() >= MAX_ENTRIES { + return Err(Error::Limit("table entries")); + } + let i = u16::try_from(self.entries.len() + 1).map_err(|_| Error::Limit("table entries"))?; + self.entries.push(k.clone()); + self.index.insert(k, i); + Ok(i) + } +} + +/// A color as it is stored, so equal colors share an entry. +#[derive(Clone, PartialEq, Eq, Hash)] +struct ColorKey { + model: u16, + values: [u8; 4], + name: Option, +} + +/// The tables the instructions refer to (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Table, + /// Widths in coordinate units. + pens: Table, + /// Flags, and the caps and join. + line_types: Table<(u8, u8)>, + dashes: Table>, + /// Line type, color, pen and dashes (the screen and the arrowheads are always the first). + outlines: Table<[u16; 4]>, +} + +impl Tables { + /// The table chunks, or an [`Error::Limit`] once they take more than `left` bytes. + fn chunks(&self, left: usize) -> Result>, Error> { + // The bytes taken so far, charged as each entry is made and then for each table's header. + let used = std::cell::Cell::new(0usize); + let charge = |n: usize| { + used.set(used.get().saturating_add(n)); + if used.get() > left { Err(Error::Limit("input size")) } else { Ok(()) } + }; + let table = |id: &[u8; 4], entries: Vec>| -> Result, Error> { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + let c = chunk(id, &d)?; + charge(c.len() + 2 - d.len())?; + Ok(c) + }; + let one = |tag: u8, data: &[u8]| -> Result, Error> { + let e = field(tag, data).map(|f| fields(&[f])).ok_or(Error::Limit("table entry size"))?; + charge(e.len())?; + Ok(e) + }; + let colors = self + .colors + .entries + .iter() + .map(|k| -> Result, Error> { + let e = color_entry(k)?; + charge(e.len())?; + Ok(e) + }) + .collect::, _>>()?; + // A pen: the width, an aspect of 100 percent, an angle of 0 and a matrix of type 1 + // (R57). + let pens = self + .pens + .entries + .iter() + .map(|w| { + let mut d = w.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + one(1, &d) + }) + .collect::, _>>()?; + let line_types = self.line_types.entries.iter().map(|(f, cj)| one(1, &[*f, *cj])).collect::, _>>()?; + let dashes = self + .dashes + .entries + .iter() + .map(|d| { + let mut b = (d.len() as u16).to_le_bytes().to_vec(); + b.extend(d.iter().flat_map(|x| x.to_le_bytes())); + one(1, &b) + }) + .collect::, _>>()?; + // An outline: line type, screen, color, arrowhead pair, pen and dash pattern (R58). + let outlines = self + .outlines + .entries + .iter() + .map(|[line, color, pen, dash]| one(1, &[*line, 1, *color, 1, *pen, *dash].map(u16::to_le_bytes).concat())) + .collect::, _>>()?; + // One arrowhead pair with no arrowheads, which every outline names (R59). + let mut rota = 1u16.to_le_bytes().to_vec(); + rota.extend([0; 4]); + Ok(vec![ + table(b"rclr", colors)?, + table(b"rpen", pens)?, + table(b"rott", line_types)?, + table(b"rdot", dashes)?, + table(b"rotl", outlines)?, + chunk(b"rota", &rota)?, + // One screen, which every outline names (R74). + table(b"rscr", vec![one(1, &SCREEN)?])?, + ]) + } +} + +/// A color as a color record (R14): the model and four value bytes. A spot color is model 21, its +/// look at its tint in blue, green and red with the tint in percent, and its name; with no look it +/// is black at its tint. +fn color_key(c: &Color) -> ColorKey { + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round() as u8; + match c { + Color::Rgb([r, g, b]) => ColorKey { model: 5, values: [byte(*b), byte(*g), byte(*r), 0], name: None }, + Color::Cmyk([c, m, y, k]) => ColorKey { model: 2, values: [pct(*c), pct(*m), pct(*y), pct(*k)], name: None }, + Color::Gray(k) => ColorKey { model: 9, values: [byte(1.0 - k), 0, 0, 0], name: None }, + Color::Registration => ColorKey { model: 20, values: [0; 4], name: None }, + Color::Spot { name, tint, look } => { + // The look is mixed at the whole percent stored, the tint the reader takes it back + // out at. + let stored = pct(*tint); + let t = f32::from(stored) / 100.0; + let [r, g, b] = look.unwrap_or([0.0; 3]).map(|v| 1.0 - (1.0 - v.clamp(0.0, 1.0)) * t); + ColorKey { model: 21, values: [byte(b), byte(g), byte(r), stored], name: Some(name.clone()) } + } + } +} + +/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5, +/// then four value bytes. A spot color is written as its look at its tint in red, green and blue, +/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the +/// models of these fields hold neither. +fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) { + let [v0, v1, v2, v3] = k.values; + match k.model { + 2 => (2, [v0, v1, v2, v3]), + // Red, green and blue, where the color record holds blue, green and red. + 5 | 21 => (5, [v2, v1, v0, 0]), + 9 => (9, [v0, 0, 0, 0]), + _ => (2, [100; 4]), + } +} + +/// A color entry (R56): field 1 the model and the palette, field 2 the values, as +/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8 +/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, +/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units. +fn color_entry(k: &ColorKey) -> Result, Error> { + let mut list = vec![1u8]; + list.extend(12u32.to_le_bytes()); + list.extend(k.model.to_le_bytes()); + list.extend(5u16.to_le_bytes()); + list.extend([0; 4]); + list.extend(k.values); + if let Some(name) = &k.name { + let units = utf16_prefix(name); + list.push(3); + list.extend((4 + 2 * units.len() as u32).to_le_bytes()); + list.extend((units.len() as u32).to_le_bytes()); + list.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } + let mut rec = (list.len() as u32).to_le_bytes().to_vec(); + rec.extend(list); + let (model, values) = older_fields(k); + let size = || Error::Limit("table entry size"); + Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?])) +} + +/// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file. +#[derive(Default)] +struct ReadCost { + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, +} + +impl ReadCost { + /// An [`Error::Limit`] when a read within `limits` would refuse the file or leave out part of + /// it. + fn check(&self, limits: &crate::Limits) -> Result<(), Error> { + if self.chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + if self.objects > limits.objects { + return Err(Error::Limit("objects")); + } + if self.coordinates > limits.coordinates { + return Err(Error::Limit("coordinates")); + } + if self.dashes > limits.dashes { + return Err(Error::Limit("dashes")); + } + Ok(()) + } +} + +#[derive(Default)] +struct Writer { + /// What the file must open within. + limits: crate::Limits, + /// The bytes of the chunks written so far, with the RIFF header. + file_bytes: usize, + /// At least the bytes the table entries added so far take in the tables written at the end: + /// a dash pattern's lengths and a color's name. + table_bytes: usize, + tables: Tables, + /// The look of each named spot color, from [`spot_looks`]. + looks: HashMap, + /// The comparisons [`may_fill_differently`] may still make. + crossing_budget: u64, + /// The groups open where the next instruction is written, outermost first. + open_groups: Vec, + /// The instructions written on the current page, its begin-page instruction included. + instructions: usize, + /// For each group closed on the current page, where its end offset goes in the page's + /// instructions after the begin-page instruction, and the offset there, both counted from the + /// end of the begin-page instruction. + group_ends: Vec<(usize, usize)>, + /// The smallest and largest x and y the curves written on the current page reach, in + /// coordinate units. + bounds: Option<[i32; 4]>, + /// What [`crate::read_cmx`] counts against [`crate::Limits`] in the instructions written so + /// far: instructions (chunks), groups and curves (objects), curve points (coordinates) and the + /// dash lengths of every curve's outline (dashes). + read_cost: ReadCost, + split_paths: bool, + cut_subpaths: bool, + rounded_dashes: bool, + long_names: bool, + zero_tints: bool, + nonzero_fills: bool, + unnamed_spots: bool, + unknown_looks: bool, + merged_looks: bool, + left_out: bool, +} + +/// Whether a spot color's `name`, as written, reads back as no name: the reader drops trailing NULs. +fn unnamed(name: &str) -> bool { + utf16_prefix(name).iter().all(|u| *u == 0) +} + +/// Whether `name` opens shortened: it is longer than the UTF-16 units the reader keeps whole, or +/// it ends in NULs, which the reader drops. +fn shortened(name: &str) -> bool { + name.ends_with('\0') || name.encode_utf16().nth(crate::records::MAX_NAME).is_some() +} + +/// `name` in UTF-16, cut after its last whole character within [`MAX_NAME_UNITS`] units. +fn utf16_prefix(name: &str) -> Vec { + let mut units = Vec::new(); + let mut buf = [0u16; 2]; + for c in name.chars() { + let enc = c.encode_utf16(&mut buf); + if units.len() + enc.len() > MAX_NAME_UNITS { + break; + } + units.extend_from_slice(enc); + } + units +} + +/// The look of each named spot color in `drawing`, master layers included, from the use at the +/// strongest tint that gives one. +fn spot_looks(drawing: &Drawing) -> HashMap { + let mut looks: HashMap = HashMap::new(); + let layers = drawing.pages.iter().flat_map(|p| &p.layers).chain(&drawing.master); + let mut stack: Vec<&Object> = layers.flat_map(|l| &l.objects).collect(); + while let Some(o) = stack.pop() { + let shape = match o { + Object::Shape(s) => s, + Object::Group { objects, .. } => { + stack.extend(objects); + continue; + } + Object::Clip { container, objects } => { + stack.extend(objects); + container + } + }; + for c in shape.fill.iter().chain(shape.outline.as_ref().map(|o| &o.color)) { + if let Color::Spot { name, tint, look: Some(look) } = c + && !unnamed(name) + { + let known = looks.entry(name.clone()).or_insert((*tint, *look)); + if *tint > known.0 { + *known = (*tint, *look); + } + } + } + } + looks.into_iter().map(|(name, (_, look))| (name, look)).collect() +} + +impl Writer { + /// The 1-based color entry of `c`. A named spot color takes its ink's look: the look of the + /// use of its name at the strongest tint among the uses whose look is known, hidden uses + /// included. + fn color(&mut self, c: &Color) -> Result { + let key = match c { + Color::Spot { name, tint, .. } if self.looks.contains_key(name) => { + color_key(&Color::Spot { name: name.clone(), tint: *tint, look: self.looks.get(name).copied() }) + } + _ => color_key(c), + }; + if let Color::Spot { name, look, .. } = c { + self.unnamed_spots |= unnamed(name); + self.long_names |= shortened(name); + // The reader takes the tint back out of the stored color; at a low tint the 8-bit + // values do not hold enough of the look for that. + let opens = |k: &ColorKey| { + let [b, g, r] = [k.values[0], k.values[1], k.values[2]].map(|v| f32::from(v) / 255.0); + crate::records::untinted([r, g, b], f32::from(k.values[3]) / 100.0) + }; + // More than 2/255 apart in some value, with room for the reader's rounding. + let lost = |opened: &[f32; 3], want: [f32; 3]| opened.iter().zip(want).any(|(a, w)| (a - w.clamp(0.0, 1.0)).abs() > 2.0 / 255.0 + 1e-6); + let back = opens(&key); + let ink = self.looks.get(name).copied().or(*look).unwrap_or([0.0; 3]); + self.zero_tints |= key.values[3] == 0 || lost(&back, ink); + self.unknown_looks |= look.is_none() && !self.looks.contains_key(name); + // A use with a look of its own: the ink's look written in its place changed it when the + // use opens off what its own look would open as, or off its own look where its own + // look would not. Otherwise the tint alone keeps its own look from opening again. + if let Some(own) = look { + let back_own = if self.looks.get(name) == Some(own) { back } else { opens(&color_key(c)) }; + if lost(&back, back_own) || (lost(&back, *own) && !lost(&back_own, *own)) { + self.merged_looks = true; + } else { + self.zero_tints |= lost(&back_own, *own); + } + } + } + if let Some(name) = key.name.as_ref().filter(|_| !self.tables.colors.index.contains_key(&key)) { + self.table_bytes = self.table_bytes.saturating_add(2 * utf16_prefix(name).len()); + self.check_bytes(0)?; + } + self.tables.colors.index(key) + } + + /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60), + /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name. + /// The chunk starts at the file offset [`Writer::file_bytes`] gives. + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec), Error> { + let mut out = Vec::new(); + self.bounds = None; + self.instructions = 1; + self.group_ends.clear(); + // Where each layer's begin-layer instruction starts in `out`, and its 8-bit name. + let mut starts = Vec::new(); + // The model holds layers and objects front to back; the file lists them back to front. + let mut written = 0; + for layer in layers.iter().rev() { + // A desktop layer is written as a drawing layer, which is how the reader takes it. + self.left_out |= !layer.guides.is_empty() || layer.flags.locked || (layer.kind == LayerKind::Desktop && !layer.objects.is_empty()); + // The reader leaves out a layer that holds nothing. + self.left_out |= layer.objects.is_empty(); + // Guide and grid layers hold construction art, which a reader takes as drawing art. + if layer.flags.hidden || matches!(layer.kind, LayerKind::Guides | LayerKind::Grid) { + self.left_out = true; + continue; + } + // The reader also stops a layer's name at its first NUL and takes a blank name as none. + let name = &layer.name; + self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty()); + let body = layer_fields(n, written, &layer.name)?; + let begin = instr(BEGIN_LAYER, &body); + // The layer's instruction count goes at bytes 8 to 12 of field 1, after the + // instruction's header and the field's tag and length. + let count_at = out.len() + begin.len() - body.len() + 3 + 8; + let first = self.instructions; + starts.push((out.len(), narrow_name(&layer.name))); + out.extend(begin); + self.instructions += 1; + written += 1; + self.objects(&layer.objects, &mut out)?; + out.extend(instr(END_LAYER, &[])); + self.instructions += 1; + put_u32(&mut out, count_at, self.instructions - first)?; + self.read_cost.chunks += 2; + self.read_cost.check(&self.limits)?; + self.check_bytes(out.len())?; + } + let end = out.len(); + out.extend(instr(END_PAGE, &[])); + self.instructions += 1; + // The begin and end page instructions. + self.read_cost.chunks += 2; + self.read_cost.check(&self.limits)?; + let bounds = self.bounds.take(); + let begin_len = begin_page(n, size, bounds, PageTail::default())?.len(); + // The page's instructions after the begin-page instruction start here in the file. + let base = self.file_bytes.saturating_add(8).saturating_add(begin_len); + let tail = PageTail { + end: offset(base.saturating_add(end))?, + layers: u16::try_from(written).map_err(|_| Error::Limit("layers"))?, + instructions: u32::try_from(self.instructions).map_err(|_| Error::Limit("chunk count"))?, + }; + for (at, end) in std::mem::take(&mut self.group_ends) { + put_u32(&mut out, at, base.saturating_add(end))?; + } + let begin = begin_page(n, size, bounds, tail)?; + if u32::try_from(begin.len() + out.len()).is_err() { + return Err(Error::Limit("chunk size")); + } + let mut page = begin; + page.extend(out); + let c = chunk(b"page", &page)?; + self.check_bytes(c.len())?; + let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect(); + self.file_bytes += c.len(); + Ok((c, layers)) + } + + /// An [`Error::Limit`] when the file would be longer than the input size of the limits with + /// `pending` more bytes. + fn check_bytes(&self, pending: usize) -> Result<(), Error> { + if self.file_bytes.saturating_add(self.table_bytes).saturating_add(pending) > self.limits.input { + Err(Error::Limit("input size")) + } else { + Ok(()) + } + } + + /// The shown `objects` (front to back) in the order they are drawn. Groups are walked with a + /// stack, not by recursion. + fn objects(&mut self, objects: &[Object], out: &mut Vec) -> Result<(), Error> { + // Each entry: the objects of a list still to write, back to front, whether a group ends + // after them, and a clipping container's outline drawn over them. + type Level<'a> = (std::iter::Rev>, bool, Option); + let mut stack: Vec> = vec![(objects.iter().rev(), false, None)]; + while let Some((iter, _, _)) = stack.last_mut() { + // A page chunk holds at most what its 32-bit size counts. + if u32::try_from(out.len()).is_err() { + return Err(Error::Limit("chunk size")); + } + self.check_bytes(out.len())?; + let Some(o) = iter.next() else { + if let Some((_, ends, over)) = stack.pop() { + if let Some(s) = over { + self.shape(&s, out)?; + } + if ends { + self.end_group(out)?; + } + } + continue; + }; + match o { + // A hidden clipping container hides what it clips too. + Object::Shape(s) | Object::Clip { container: s, .. } if s.flags.hidden => self.left_out = true, + Object::Group { flags, .. } if flags.hidden => self.left_out = true, + Object::Shape(s) => self.shape(s, out)?, + Object::Group { objects, flags } => { + self.left_out |= flags.locked; + self.begin_group(out)?; + stack.push((objects.iter().rev(), true, None)); + } + Object::Clip { container, objects } => { + self.left_out = true; + self.begin_group(out)?; + // The container's fill is drawn behind the objects it clips and its outline + // over them; an outline behind a fill is drawn behind them too, and an + // outline with no fill to be behind is drawn over them. A container with + // neither draws nothing and is not written. + let mut over = None; + match (&container.fill, &container.outline) { + (None, None) => {} + (None, Some(_)) => over = Some((**container).clone()), + (Some(_), Some(o)) if !o.behind_fill => { + self.shape(&Shape { outline: None, ..(**container).clone() }, out)?; + over = Some(Shape { fill: None, ..(**container).clone() }); + } + _ => self.shape(container, out)?, + } + stack.push((objects.iter().rev(), true, over)); + } + } + } + Ok(()) + } + + /// Begin a group. A group inside as many groups as the reader opens (the depth of the + /// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds. + fn begin_group(&mut self, out: &mut Vec) -> Result<(), Error> { + if self.open_groups.len() >= self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + if let Some(parent) = self.open_groups.last_mut() { + parent.groups = parent.groups.checked_add(1).ok_or(Error::Limit("groups"))?; + } + self.open_groups.push(OpenGroup { at: out.len(), first: self.instructions, groups: 0, bounds: None }); + out.extend(group()); + self.instructions += 1; + self.read_cost.chunks += 1; + self.read_cost.objects += 1; + self.read_cost.check(&self.limits) + } + + /// End the innermost open group, and fill in its begin-group record (R77): the edges of its + /// curves (all 0 when it has none), the groups directly inside it, its instructions from begin + /// to end, and where the instruction after its end starts, which [`Writer::page`] places in + /// the file. + fn end_group(&mut self, out: &mut Vec) -> Result<(), Error> { + out.extend(instr(END_GROUP, &[])); + self.instructions += 1; + self.read_cost.chunks += 1; + let Some(g) = self.open_groups.pop() else { return Ok(()) }; + if let (Some(parent), Some(b)) = (self.open_groups.last_mut(), g.bounds) { + parent.bounds = Some(match parent.bounds { + Some(p) => [p[0].min(b[0]), p[1].min(b[1]), p[2].max(b[2]), p[3].max(b[3])], + None => b, + }); + } + // Field 1's data starts after the instruction's 4-byte header and the field's tag and + // length. + let data = g.at + 4 + 3; + let [x0, y0, x1, y1] = g.bounds.unwrap_or_default(); + for (i, v) in [x0, y1, x1, y0].into_iter().enumerate() { + out[data + 4 * i..data + 4 * i + 4].copy_from_slice(&v.to_le_bytes()); + } + out[data + 16..data + 18].copy_from_slice(&g.groups.to_le_bytes()); + put_u32(out, data + 18, self.instructions - g.first)?; + self.group_ends.push((data + 22, out.len())); + Ok(()) + } + + /// Take in `[x0, y0, x1, y1]`, the edges of a written curve, in the page's and the innermost + /// open group's edges. + fn reach(&mut self, e: [i32; 4]) { + for b in [Some(&mut self.bounds), self.open_groups.last_mut().map(|g| &mut g.bounds)].into_iter().flatten() { + let b = b.get_or_insert(e); + *b = [b[0].min(e[0]), b[1].min(e[1]), b[2].max(e[2]), b[3].max(e[3])]; + } + } + + /// A shape as one curve, or as a group of curves when its path holds more than + /// [`MAX_CURVE_POINTS`] points. + fn shape(&mut self, s: &Shape, out: &mut Vec) -> Result<(), Error> { + self.left_out |= s.opacity < 1.0 || s.blend != Blend::Normal || s.flags.locked; + // A path's nodes are at least as many as its segments and starts; a path past what the + // limits leave is refused before its points are made. + if let Geometry::Path(p) = &s.geometry { + let nodes = p.subpaths.iter().filter(|sp| !sp.segments.is_empty()).fold(0usize, |n, sp| { + sp.segments.iter().fold(n.saturating_add(1), |n, seg| n.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { 3 })) + }); + // A path split into several curves is written once for its fill and once for its + // outline. + let passes = if s.fill.is_some() && s.outline.is_some() && nodes > MAX_CURVE_POINTS { 2 } else { 1 }; + let nodes = nodes.saturating_mul(passes); + if self.read_cost.coordinates.saturating_add(nodes) > self.limits.coordinates { + return Err(Error::Limit("coordinates")); + } + // A path with segments takes at least one object and one instruction. + if nodes > 0 { + let cost = ReadCost { chunks: self.read_cost.chunks + 1, objects: self.read_cost.objects + 1, ..ReadCost::default() }; + cost.check(&self.limits)?; + } + self.check_bytes(out.len().saturating_add(nodes.saturating_mul(9)))?; + } + let points = points_of(&s.geometry, &s.matrix)?; + let curves = split(&points); + // A path with no segments draws nothing, and the file has no curve for it. + if curves.is_empty() { + self.left_out = true; + return Ok(()); + } + // A shape written as several curves paints all its fill and then all its outline (the + // other way round for an outline behind the fill); one curve carries both. + let passes: Vec<(Option<&Color>, Option<&Outline>)> = match (&s.fill, &s.outline) { + (Some(f), Some(o)) if curves.len() > 1 && o.behind_fill => vec![(None, Some(o)), (Some(f), None)], + (Some(f), Some(o)) if curves.len() > 1 => vec![(Some(f), None), (None, Some(o))], + (f, o) => vec![(f.as_ref(), o.as_ref())], + }; + let mut attrs = Vec::with_capacity(passes.len()); + for (f, o) in passes { + attrs.push(self.attributes(f, o, &s.matrix)?); + } + if !self.nonzero_fills + && s.nonzero + && s.fill.is_some() + && let Geometry::Path(p) = &s.geometry + { + self.nonzero_fills = may_fill_differently(p, &mut self.crossing_budget); + } + self.cut_subpaths |= (s.fill.is_some() || s.outline.is_some()) && points.iter().any(|sp| sp.len() > MAX_CURVE_POINTS); + if curves.len() > 1 { + self.split_paths = true; + self.begin_group(out)?; + } + // Each pass writes every curve, and the reader takes the outline's dashes again for every + // curve that names it. + let points_count = curves.iter().fold(0usize, |n, c| n.saturating_add(c.len())); + for (_, dashes) in &attrs { + let cost = &mut self.read_cost; + cost.chunks = cost.chunks.saturating_add(curves.len()); + cost.objects = cost.objects.saturating_add(curves.len()); + cost.coordinates = cost.coordinates.saturating_add(points_count); + cost.dashes = cost.dashes.saturating_add(dashes.saturating_mul(curves.len())); + } + self.read_cost.check(&self.limits)?; + // Each curve instruction holds at least 9 bytes for each point. + self.check_bytes(out.len().saturating_add(points_count.saturating_mul(9).saturating_mul(attrs.len())))?; + let mut bodies = Vec::with_capacity(curves.len()); + for c in &curves { + let mut g = (c.len() as u16).to_le_bytes().to_vec(); + // The points as written, in coordinate units. + let mut written = Vec::with_capacity(c.len()); + for (p, t) in c.iter() { + let (x, y) = (units(p.x)?, units(p.y)?); + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + written.push((Pt { x: f64::from(x), y: f64::from(y) }, *t)); + } + // The page's art edges take in the written curve itself: its anchors and each cubic's + // extremes, rounded outward. + for (i, (p, t)) in written.iter().enumerate() { + let [x0, y0, x1, y1] = match (t >> 6, i.checked_sub(3).and_then(|s| written.get(s..i))) { + (2, Some([(a, _), (b, _), (d, _)])) => cubic_extent(*a, *b, *d, *p), + (3, _) => continue, + _ => [p.x, p.y, p.x, p.y], + }; + // Within the anchors and control points, which are i32, so the casts keep them. + self.reach([x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32]); + } + g.extend(c.iter().map(|(_, t)| *t)); + bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?); + } + for (a, _) in &attrs { + let f1 = field(1, a).ok_or(Error::Limit("rendering attributes size"))?; + for f2 in &bodies { + let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()])); + self.check_bytes(out.len().saturating_add(i.len()))?; + out.extend(i); + self.instructions += 1; + } + } + if curves.len() > 1 { + self.end_group(out)?; + } + Ok(()) + } + + /// Rendering attributes (R63): the mask, then the uniform fill's field list (fill type 1 and a + /// field 1 of the color entry and screen entry 1, R74) and the outline's (its `rotl` entry), + /// with the number of dash lengths the outline names. + fn attributes(&mut self, fill: Option<&Color>, outline: Option<&Outline>, matrix: &Matrix) -> Result<(Vec, usize), Error> { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1); + let mut a = vec![mask]; + let mut dashes = 0; + if let Some(c) = fill { + let index = self.color(c)?; + let mut v = 1u16.to_le_bytes().to_vec(); + v.extend(fields(&[field(1, &[index.to_le_bytes(), 1u16.to_le_bytes()].concat()).ok_or(Error::Limit("fill size"))?])); + a.extend(fields(&[field(1, &v).ok_or(Error::Limit("fill size"))?])); + } + if let Some(o) = outline { + // The points are written placed by the matrix, so an outline that scales with the + // shape takes the matrix's scale into its width, as the engine applies it (R50). + let [m0, m1, m2, m3, _, _] = matrix.0; + let scale = if o.scale_with { (m0 * m3 - m1 * m2).abs().sqrt() } else { 1.0 }; + let (index, n) = self.outline(o, scale)?; + dashes = n; + a.extend(fields(&[field(1, &index.to_le_bytes()).ok_or(Error::Limit("outline size"))?])); + } + Ok((a, dashes)) + } + + /// The `rotl` entry of an outline (R57, R58): its line type (2 solid, 4 dashed, 8 behind the + /// fill, 16 scaled with the object; the caps in the low 4 bits and the join in the high 4 + /// bits), color, pen and dash pattern, and the number of dash lengths stored. `scale` + /// multiplies the width. + fn outline(&mut self, o: &Outline, scale: f64) -> Result<(u16, usize), Error> { + // A pattern with no positive length draws a solid line (R57). + let lengths: &[f64] = if !o.dashes.iter().any(|d| *d > 0.0) { &[] } else { &o.dashes }; + // A length that is not a number is stored as 0. + self.rounded_dashes |= o.dashes.iter().any(|d| d.is_nan()); + // One table entry holds a u16 count and the lengths in a field of at most 65,535 bytes. + if lengths.len() > (usize::from(u16::MAX) - 3 - 2) / 2 { + return Err(Error::Limit("table entry size")); + } + let mut dashes: Vec = lengths.iter().map(|d| d.max(0.0).round().min(f64::from(u16::MAX)) as u16).collect(); + if lengths.iter().zip(&dashes).any(|(d, r)| *d != f64::from(*r)) { + self.rounded_dashes = true; + } + // Marks (the even entries) that all round to nothing would draw nothing, and lengths that + // all round to nothing would draw a solid line: the positive ones are kept as short as the + // table allows (gaps only in the second case). + let all_zero = dashes.iter().all(|d| *d == 0); + let marks_gone = dashes.iter().step_by(2).all(|d| *d == 0) && lengths.iter().step_by(2).any(|d| *d > 0.0); + if !dashes.is_empty() && (all_zero || marks_gone) { + for (i, (r, d)) in dashes.iter_mut().zip(lengths).enumerate() { + if *r == 0 && *d > 0.0 && (all_zero || i % 2 == 0) { + *r = 1; + } + } + self.rounded_dashes = true; + } + let dashed = !dashes.is_empty(); + let flags = 2 | if dashed { 4 } else { 0 } | if o.behind_fill { 8 } else { 0 } | if o.scale_with { 16 } else { 0 }; + let cap = match o.cap { + Cap::Butt => 0, + Cap::Round => 1, + Cap::Square => 2, + }; + let join = match o.join { + Join::Miter => 0, + Join::Round => 1, + Join::Bevel => 2, + }; + let line = self.tables.line_types.index((flags, cap | (join << 4)))?; + let color = self.color(&o.color)?; + // A pen of width 0 reads as a hairline, so a thinner positive width is written as one unit. + if o.width.is_nan() || o.width < 0.0 { + return Err(Error::Limit("outline width")); + } + let width = o.width * scale; + if width.is_nan() { + return Err(Error::Limit("outline width")); + } + let pen = self.tables.pens.index(if width > 0.0 { width_units(width)?.max(1) } else { 0 })?; + // A solid outline names an empty pattern, as the sample files' solid outlines do (R58). + let stored = dashes.len(); + if !self.tables.dashes.index.contains_key(&dashes) { + self.table_bytes = self.table_bytes.saturating_add(2 * stored); + self.check_bytes(0)?; + } + let dash = self.tables.dashes.index(dashes)?; + Ok((self.tables.outlines.index([line, color, pen, dash])?, stored)) + } +} + +/// A group open where the next instruction is written. +struct OpenGroup { + /// Where its begin-group instruction starts in the page's instructions after the begin-page + /// instruction. + at: usize, + /// The page's instructions written before it. + first: usize, + /// The groups directly inside it so far. + groups: u16, + /// The smallest and largest x and y its curves reach so far, in coordinate units. + bounds: Option<[i32; 4]>, +} + +/// What begin page keeps of the rest of the page (R77). +#[derive(Clone, Copy, Default)] +struct PageTail { + /// The file offset of the end-page instruction. + end: u32, + /// The layers on the page. + layers: u16, + /// The page's instructions, begin and end page included. + instructions: u32, +} + +/// Write `v` as a u32 at `at` of `out`. +fn put_u32(out: &mut [u8], at: usize, v: usize) -> Result<(), Error> { + let v = u32::try_from(v).map_err(|_| Error::Limit("chunk size"))?; + out.get_mut(at..at + 4).ok_or(Error::Limit("chunk size"))?.copy_from_slice(&v.to_le_bytes()); + Ok(()) +} + +/// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left, +/// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y), +/// or of the page around its center when it has no art, then `tail` (R77); field 4 its width and +/// height. Without a size the edges are all 0, which the reader takes as no size. +fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail: PageTail) -> Result, Error> { + let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?; + let mut d = number.to_le_bytes().to_vec(); + d.extend(0u32.to_le_bytes()); + let mut list = Vec::new(); + let mut size_field = None; + let mut edges = [0i32; 4]; + if let Some((w, h)) = size { + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + edges = match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }; + let mut s = wu.to_le_bytes().to_vec(); + s.extend(hu.to_le_bytes()); + size_field = Some(s); + } + for v in edges { + d.extend(v.to_le_bytes()); + } + d.extend(tail.end.to_le_bytes()); + d.extend(tail.layers.to_le_bytes()); + d.extend(tail.instructions.to_le_bytes()); + list.push(field(1, &d).ok_or(Error::Limit("page size"))?); + if let Some(s) = size_field { + list.push(field(4, &s).ok_or(Error::Limit("page size"))?); + } + Ok(instr(BEGIN_PAGE, &fields(&list))) +} + +/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. +fn windows_1252_byte(c: char) -> u8 { + match u8::try_from(u32::from(c)) { + Ok(b) if !(0x80..0xa0).contains(&b) => b, + _ => crate::records::CP1252_HIGH.iter().position(|h| *h == c && c != '\u{FFFD}').and_then(|i| u8::try_from(0x80 + i).ok()).unwrap_or(b'?'), + } +} + +/// Whether a layer's `name`, up to the first NUL where the reader stops, is blank: it is written +/// empty, so it opens with no name. +fn blank_name(name: &str) -> bool { + name.split('\0').next().unwrap_or_default().trim().is_empty() +} + +/// A layer's name as written in 8-bit characters (Windows-1252: characters the code page has no +/// byte for are written as `?`). +fn narrow_name(name: &str) -> Vec { + if blank_name(name) { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() } +} + +/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 4 zero +/// bytes, the layer's instruction count, which [`Writer::page`] fills in (R77), then the name as a +/// u16 count and 8-bit characters ([`narrow_name`]); field 4 the name as a u32 count and UTF-16 +/// units. `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers +/// is an [`Error::Limit`]. +fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { + let blank = blank_name(name); + let narrow = narrow_name(name); + let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?; + let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?; + let mut d = page.to_le_bytes().to_vec(); + d.extend(number.to_le_bytes()); + d.extend([0; 8]); + d.extend((narrow.len() as u16).to_le_bytes()); + d.extend(&narrow); + let units = if blank { Vec::new() } else { utf16_prefix(name) }; + let mut wide = (units.len() as u32).to_le_bytes().to_vec(); + wide.extend(units.iter().flat_map(|u| u.to_le_bytes())); + let f1 = field(1, &d).ok_or(Error::Limit("layer name"))?; + let f4 = field(4, &wide).ok_or(Error::Limit("layer name"))?; + Ok(fields(&[f1, f4])) +} + +/// Begin a group: field 1 of 26 bytes, which [`Writer::end_group`] fills in (R77). +fn group() -> Vec { + instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()])) +} + +/// A subpath's points and their type bytes (R16), placed by `m`. +type Points = Vec<(Pt, u8)>; + +/// The subpaths of a geometry as points and type bytes, one list for each subpath. A closed +/// subpath ends back at its start, on a node that carries the closing bit. +fn points_of(g: &Geometry, m: &Matrix) -> Result, Error> { + let (path, m) = match g { + Geometry::Path(p) => (std::borrow::Cow::Borrowed(p), Matrix(m.0)), + Geometry::Rect { w, h, radii } => { + let (w, h, radii, m) = fold_scale(*w, *h, *radii, m); + (std::borrow::Cow::Owned(rect_path(w, h, radii)), m) + } + Geometry::Ellipse { w, h } => (std::borrow::Cow::Owned(ellipse_path(*w, *h)), Matrix(m.0)), + }; + path.subpaths.iter().filter(|s| !s.segments.is_empty()).map(|s| subpath_points(s, &m)).collect() +} + +/// A rectangle placed by `m` with the scale of `m` taken into its size, when the matrix keeps right +/// angles: the width and height times the matrix's scale along each, the radii times the square +/// root of its area scale, and the matrix left with its rotation, mirroring and offset. The +/// corners then stay round. Other matrices are kept whole. +fn fold_scale(w: f64, h: f64, radii: [f64; 4], m: &Matrix) -> (f64, f64, [f64; 4], Matrix) { + let [m0, m1, m2, m3, m4, m5] = m.0; + let (sx, sy) = (m0.hypot(m1), m2.hypot(m3)); + let square = sx > 1e-12 && sy > 1e-12 && (m0 * m2 + m1 * m3).abs() <= 1e-9 * sx * sy; + if !square || !m.0.iter().all(|c| c.is_finite()) { + return (w, h, radii, Matrix(m.0)); + } + let k = (sx * sy).sqrt(); + (w * sx, h * sy, radii.map(|r| r * k), Matrix([m0 / sx, m1 / sx, m2 / sy, m3 / sy, m4, m5])) +} + +/// A subpath's points; more than memory holds is an [`Error::Limit`]. +fn subpath_points(s: &SubPath, m: &Matrix) -> Result { + let size = |segs: &[Segment]| segs.iter().fold(1usize, |n, seg| n.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { 3 })); + // The closing bit on the last node closes a subpath that fits in one curve. One that is cut + // into open pieces ends with a line back to its start instead. + let open_end = s.closed && last_point(&s.segments).is_some_and(|p| p != s.start); + let closing = (open_end && size(&s.segments) > MAX_CURVE_POINTS).then_some(Segment::Line(s.start)); + let count = size(&s.segments).saturating_add(usize::from(closing.is_some())); + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| Error::Limit("path size"))?; + out.push((m.apply(s.start), if s.closed { MOVE | CLOSES } else { MOVE })); + for seg in s.segments.iter().chain(closing.as_ref()) { + match seg { + Segment::Line(p) => out.push((m.apply(*p), LINE)), + Segment::Cubic(c1, c2, p) => { + out.push((m.apply(*c1), CONTROL)); + out.push((m.apply(*c2), CONTROL)); + out.push((m.apply(*p), CURVE_END)); + } + } + } + if s.closed + && let Some(end) = out.last_mut() + { + end.1 |= CLOSES; + } + Ok(out) +} + +fn last_point(segments: &[Segment]) -> Option { + segments.last().map(|s| match s { + Segment::Line(p) | Segment::Cubic(_, _, p) => *p, + }) +} + +/// The subpaths gathered into curves of at most [`MAX_CURVE_POINTS`] points, whole subpaths kept +/// together where they fit. A subpath longer than that is cut into open pieces that meet end to +/// start, each piece cut after a node. +fn split(subpaths: &[Points]) -> Vec { + let mut curves: Vec = vec![Vec::new()]; + for sp in subpaths { + if sp.len() > MAX_CURVE_POINTS { + let mut rest: &[(Pt, u8)] = sp; + while rest.len() > 1 { + // Cut after a node, never between a curve's control points and its end. + let mut take = rest.len().min(MAX_CURVE_POINTS); + while take > 1 && rest.get(take - 1).is_some_and(|(_, t)| *t == CONTROL) { + take -= 1; + } + if take < 2 { + break; + } + let piece: Points = rest[..take].iter().enumerate().map(|(i, (p, t))| if i == 0 { (*p, MOVE) } else { (*p, *t & !CLOSES) }).collect(); + if curves.last().is_some_and(|c| !c.is_empty()) { + curves.push(Vec::new()); + } + curves.push(piece); + rest = &rest[take - 1..]; + } + continue; + } + if curves.last().is_some_and(|c| c.len() + sp.len() > MAX_CURVE_POINTS) { + curves.push(Vec::new()); + } + if let Some(c) = curves.last_mut() { + c.extend_from_slice(sp); + } + } + curves.retain(|c| !c.is_empty()); + curves +} + +/// The lines each cubic is flattened to for [`may_fill_differently`]. +const CURVE_STEPS: u32 = 16; + +/// The pairs of edges and of subpath boxes [`may_fill_differently`] may compare in one export; +/// past it a shape is taken to fill differently. +const CROSSING_BUDGET: u64 = 50_000_000; + +/// The pairs among `n` items, saturating. +fn pairs(n: u64) -> u64 { + n.saturating_mul(n.saturating_sub(1)) / 2 +} + +/// Take `cost` comparisons off `budget`; false, and the budget emptied, when it does not cover +/// them. +fn charge(budget: &mut u64, cost: u64) -> bool { + match budget.checked_sub(cost) { + Some(left) => { + *budget = left; + true + } + None => { + *budget = 0; + false + } + } +} + +/// The closed polygon of a subpath with each cubic flattened to [`CURVE_STEPS`] lines, without +/// repeated points, and for each edge (from a point to the next, and from the last point to the +/// first) how far the subpath may stray from that edge: 0 along a line, and along a piece of a +/// cubic `h² / 8` times the cubic's largest second derivative, `h` being the piece's share of the +/// cubic's parameter. +fn flatten(s: &SubPath) -> (Vec, Vec) { + // Each point with how far the subpath may stray from the edge that ends at it. + let mut pts = vec![(s.start, 0.0)]; + let mut last = s.start; + for seg in &s.segments { + match *seg { + Segment::Line(p) => { + pts.push((p, 0.0)); + last = p; + } + Segment::Cubic(c1, c2, p) => { + // The second derivative, 6 ((1 − t) (p0 − 2 c1 + c2) + t (c1 − 2 c2 + p3)), is at its + // largest at an end. + let second = |a: Pt, b: Pt, c: Pt| (a.x - 2.0 * b.x + c.x).hypot(a.y - 2.0 * b.y + c.y); + let steps = f64::from(CURVE_STEPS); + let stray = 6.0 * second(last, c1, c2).max(second(c1, c2, p)) / (8.0 * steps * steps); + for i in 1..=CURVE_STEPS { + let t = f64::from(i) / steps; + let u = 1.0 - t; + let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + let q = Pt { x: a * last.x + b * c1.x + c * c2.x + d * p.x, y: a * last.y + b * c1.y + c * c2.y + d * p.y }; + pts.push((q, stray)); + } + last = p; + } + } + } + // A repeated point is dropped; the subpath strays no further than that from the point, which + // is on the edge that ends at it. + let mut kept: Vec<(Pt, f64)> = Vec::with_capacity(pts.len()); + for (q, stray) in pts { + match kept.last_mut() { + Some((prev, e)) if *prev == q => *e = e.max(stray), + _ => kept.push((q, stray)), + } + } + // A last point back on the first is dropped, and its edge becomes the edge back to the first. + if kept.len() > 1 && kept.first().map(|f| f.0) == kept.last().map(|l| l.0) { + let back = kept.pop().map_or(0.0, |(_, e)| e); + if let Some(first) = kept.first_mut() { + first.1 = first.1.max(back); + } + } + let (points, ends): (Vec, Vec) = kept.into_iter().unzip(); + // Edge k runs from point k to point k + 1. + let n = ends.len(); + let strays = (0..n).map(|k| ends[(k + 1) % n]).collect(); + (points, strays) +} + +/// Whether `p` may fill differently even-odd than nonzero: one of its cubics loops, a subpath +/// crosses itself or turns around other than once, measured with the cubics flattened (two edges +/// that are not neighbors count as crossing when they are closer than the cubics may stray from +/// their lines, and two neighbors when the curves along them may meet away from their shared +/// point), or two of its subpaths turn the same way and their boxes, control points +/// included, overlap. Subpaths +/// that turn opposite ways, such as a letter's counter inside the letter, and subpaths apart from +/// each other, fill the same either way. `budget` counts down the comparisons, and is charged for +/// a subpath's edges before the subpath is flattened. +fn may_fill_differently(p: &Path, budget: &mut u64) -> bool { + let n = p.subpaths.len(); + // The boxes of every two subpaths are compared. + if !charge(budget, pairs(n as u64)) { + return true; + } + let mut polygons = Vec::with_capacity(n); + for s in &p.subpaths { + let points = + s.segments.iter().fold(1u64, |k, seg| k.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { u64::from(CURVE_STEPS) })); + if !charge(budget, pairs(points)) { + return true; + } + let mut last = s.start; + for seg in &s.segments { + match *seg { + Segment::Line(p) => last = p, + Segment::Cubic(c1, c2, p) => { + if cubic_loops(last, c1, c2, p) { + return true; + } + last = p; + } + } + } + let (pts, strays) = flatten(s); + if loops(&pts) || crosses(&pts, &strays) || joints_meet(s, budget) { + return true; + } + polygons.push(pts); + } + if n < 2 { + return false; + } + // Each subpath's turn (`None` when its area sums to 0, which matches either way) and box. + let shapes: Vec<(Option, [f64; 4])> = polygons + .iter() + .zip(&p.subpaths) + .map(|(pts, s)| { + // The area is summed from the first point, so far-off coordinates keep their precision. + let o = pts.first().copied().unwrap_or(s.start); + let area: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y)).sum(); + // The box holds every point, control points included, so it holds the curves too. + let controls = std::iter::once(s.start).chain(s.segments.iter().flat_map(|seg| match *seg { + Segment::Line(a) => vec![a], + Segment::Cubic(a, b, c) => vec![a, b, c], + })); + let bounds = controls.fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, q| [b[0].min(q.x), b[1].min(q.y), b[2].max(q.x), b[3].max(q.y)]); + ((area != 0.0).then_some(area > 0.0), bounds) + }) + .collect(); + shapes.iter().enumerate().any(|(i, (turn, a))| { + shapes[i + 1..] + .iter() + .any(|(other, b)| (turn.is_none() || other.is_none() || turn == other) && a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]) + }) +} + +/// The smallest x and y and the largest x and y the cubic from `p0` through `c1` and `c2` to `p3` +/// reaches: its ends and the points where it turns along either axis. +fn cubic_extent(p0: Pt, c1: Pt, c2: Pt, p3: Pt) -> [f64; 4] { + let at = |t: f64, a: f64, b: f64, c: f64, d: f64| { + let u = 1.0 - t; + u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d + }; + // The parameters in 0 to 1 where one coordinate's derivative is 0. + let turns = |a: f64, b: f64, c: f64, d: f64| -> Vec { + let (qa, qb, qc) = (-a + 3.0 * b - 3.0 * c + d, 2.0 * (a - 2.0 * b + c), b - a); + let mut ts = Vec::new(); + if qa.abs() < 1e-12 { + if qb.abs() > 1e-12 { + ts.push(-qc / qb); + } + } else { + let disc = qb * qb - 4.0 * qa * qc; + if disc >= 0.0 { + // Each root from the form that adds numbers of one sign, so neither cancels. + let q = -0.5 * (qb + qb.signum() * disc.sqrt()); + ts.push(q / qa); + if q != 0.0 { + ts.push(qc / q); + } + } + } + ts.retain(|t| (0.0..=1.0).contains(t)); + ts + }; + // An extreme between the ends is evaluated with rounding, so it is widened by a little more + // than that rounding: the edges then hold the curve. + let slack = |v: f64| v.abs() * 4.0 * f64::EPSILON + 1e-12; + let mut e = [p0.x.min(p3.x), p0.y.min(p3.y), p0.x.max(p3.x), p0.y.max(p3.y)]; + for t in turns(p0.x, c1.x, c2.x, p3.x) { + let x = at(t, p0.x, c1.x, c2.x, p3.x); + e = [e[0].min(x - slack(x)), e[1], e[2].max(x + slack(x)), e[3]]; + } + for t in turns(p0.y, c1.y, c2.y, p3.y) { + let y = at(t, p0.y, c1.y, c2.y, p3.y); + e = [e[0], e[1].min(y - slack(y)), e[2], e[3].max(y + slack(y))]; + } + e +} + +/// Whether the cubic from `p0` through `c1` and `c2` to `p3` crosses itself. With the cubic as +/// `a t³ + b t² + c t + p0`, two parameters `s` and `t` meet where `a (σ² − π) + b σ + c = 0`, with +/// `σ = s + t` and `π = s t`; the cubic loops when `s` and `t` are distinct and both in 0 to 1. +fn cubic_loops(p0: Pt, c1: Pt, c2: Pt, p3: Pt) -> bool { + let cross = |u: (f64, f64), v: (f64, f64)| u.0 * v.1 - u.1 * v.0; + let a = (-p0.x + 3.0 * c1.x - 3.0 * c2.x + p3.x, -p0.y + 3.0 * c1.y - 3.0 * c2.y + p3.y); + let b = (3.0 * p0.x - 6.0 * c1.x + 3.0 * c2.x, 3.0 * p0.y - 6.0 * c1.y + 3.0 * c2.y); + let r = (3.0 * p0.x - 3.0 * c1.x, 3.0 * p0.y - 3.0 * c1.y); + let det = cross(a, b); + if det == 0.0 || !det.is_finite() { + return false; + } + // u = σ² − π. + let (u, sum) = (cross(r, b) / det, cross(a, r) / det); + let disc = 4.0 * u - 3.0 * sum * sum; + if disc.is_nan() || disc <= 0.0 { + return false; + } + let q = disc.sqrt(); + let (s, t) = ((sum - q) / 2.0, (sum + q) / 2.0); + // The start meeting the end closes the curve; that is no crossing. + let closes = s.abs() < 1e-9 && (t - 1.0).abs() < 1e-9; + // Rounding can put a parameter of 0 or 1 just outside the range. + let inside = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); + inside(s) && inside(t) && !closes +} + +/// Whether the closed polygon through `pts` turns around other than once: the sum of its turning +/// angles is not one full turn either way. +fn loops(pts: &[Pt]) -> bool { + let edges: Vec<(f64, f64)> = + pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (b.x - a.x, b.y - a.y)).filter(|(x, y)| x.hypot(*y) > 1e-9).collect(); + if edges.len() < 3 { + return false; + } + let turning: f64 = edges.iter().zip(edges.iter().cycle().skip(1)).map(|(a, b)| (a.0 * b.1 - a.1 * b.0).atan2(a.0 * b.0 + a.1 * b.1)).sum(); + (turning / std::f64::consts::TAU).round().abs() != 1.0 +} + +/// Whether two edges of the closed polygon through `pts` that are not neighbors cross, touch or run +/// along each other: the subpath comes back to a place it has been. `strays` holds, for each edge +/// from a point to the next, how far the subpath may stray from it; two edges closer than their +/// subpath may stray from them count as crossing. +fn crosses(pts: &[Pt], strays: &[f64]) -> bool { + let n = pts.len(); + if n < 4 { + return false; + } + // Which side of the line from `a` to `b` the point `c` is on: 1, -1, or 0 on the line. + let side = |a: Pt, b: Pt, c: Pt| { + let v = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + i8::from(v > 0.0) - i8::from(v < 0.0) + }; + let edge = |i: usize| (pts[i], pts[(i + 1) % n]); + (0..n).any(|i| { + let (a, b) = edge(i); + // Edge i shares a point with edges i - 1 and i + 1, and edge 0 with edge n - 1. + (i + 2..n).filter(|j| !(i == 0 && *j == n - 1)).any(|j| { + let (c, d) = edge(j); + let (sc, sd) = (side(a, b, c), side(a, b, d)); + if sc == 0 && sd == 0 { + // On one line: they meet when their spans along it meet. + let along = |q: Pt| (q.x - a.x) * (b.x - a.x) + (q.y - a.y) * (b.y - a.y); + let (tc, td, tb) = (along(c), along(d), along(b)); + if tc.min(td).max(0.0) <= tc.max(td).min(tb) { + return true; + } + } else if sc * sd <= 0 && side(c, d, a) * side(c, d, b) <= 0 { + return true; + } + // A cubic's piece may cross an edge that its line passes close to. + let stray = strays.get(i).copied().unwrap_or(0.0) + strays.get(j).copied().unwrap_or(0.0); + stray > 0.0 && gap(a, b, c, d) <= stray * (1.0 + 1e-9) + }) + }) +} + +/// The distance between the segment from `a` to `b` and the segment from `c` to `d`, which do not +/// cross: the shortest distance from an end of one to the other. +fn gap(a: Pt, b: Pt, c: Pt, d: Pt) -> f64 { + let to = |p: Pt, a: Pt, b: Pt| { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let len = dx * dx + dy * dy; + let t = if len > 0.0 { (((p.x - a.x) * dx + (p.y - a.y) * dy) / len).clamp(0.0, 1.0) } else { 0.0 }; + (p.x - a.x - t * dx).hypot(p.y - a.y - t * dy) + }; + to(a, c, d).min(to(b, c, d)).min(to(c, a, b)).min(to(d, a, b)) +} + +/// A segment as the start, the two control points and the end of a cubic; a line as the cubic +/// along it. +type Bez = [Pt; 4]; + +/// How many times [`meet_away_from_start`] halves two cubics around their shared start before +/// taking what is left beside it not to meet, and [`boxes_meet`] halves two cubics before taking +/// them to meet. +const NEAR_HALVINGS: u32 = 32; +const APART_HALVINGS: u32 = 24; + +/// The point a share `t` of the way from `a` to `b`. +fn lerp(a: Pt, b: Pt, t: f64) -> Pt { + Pt { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t } +} + +/// The cubic `c` cut at `t` into the part before and the part after. +fn cut(c: Bez, t: f64) -> (Bez, Bez) { + let (ab, bc, cd) = (lerp(c[0], c[1], t), lerp(c[1], c[2], t), lerp(c[2], c[3], t)); + let (abc, bcd) = (lerp(ab, bc, t), lerp(bc, cd, t)); + let m = lerp(abc, bcd, t); + ([c[0], ab, abc, m], [m, bcd, cd, c[3]]) +} + +/// The directions from `c[0]` that the cubic `c` stays within away from that point, which its +/// control points and end bound: the angle halfway between the outermost two, and half the angle +/// between them. `None` when they span half a turn or more, or all lie on `c[0]`. +fn directions(c: &Bez) -> Option<(f64, f64)> { + let o = c[0]; + let vs: Vec<(f64, f64)> = c[1..].iter().map(|q| (q.x - o.x, q.y - o.y)).filter(|v| v.0 != 0.0 || v.1 != 0.0).collect(); + let first = *vs.first()?; + let angle = |v: &(f64, f64)| (first.0 * v.1 - first.1 * v.0).atan2(first.0 * v.0 + first.1 * v.1); + let (lo, hi) = vs.iter().map(angle).fold((0.0_f64, 0.0_f64), |(lo, hi), a| (lo.min(a), hi.max(a))); + (hi - lo < std::f64::consts::PI).then(|| (first.1.atan2(first.0) + (lo + hi) / 2.0, (hi - lo) / 2.0)) +} + +/// Whether the cubics `a` and `b`, which start at the same point, may meet away from it. Near that +/// point they stay within the directions their control points bound, so where those do not overlap +/// they do not meet there; the parts away from it are compared by their boxes. `halvings` counts +/// down how often the two are halved again. Two cubics that leave the point along the same tangent +/// keep overlapping directions however often they are halved; the parts left at the last halving +/// span 2⁻³² of each given cubic's parameter from the point, and are taken not to meet. `budget` counts +/// down the comparisons. +fn meet_away_from_start(a: Bez, b: Bez, halvings: u32, budget: &mut u64) -> bool { + if !charge(budget, 1) { + return true; + } + if let (Some((ca, wa)), Some((cb, wb))) = (directions(&a), directions(&b)) { + let apart = (ca - cb).sin().atan2((ca - cb).cos()).abs(); + if apart - (wa + wb) > 1e-9 { + return false; + } + // Each runs straight out along the same direction: one runs along the other. + if wa == 0.0 && wb == 0.0 { + return true; + } + } + if halvings == 0 { + return false; + } + let ((an, af), (bn, bf)) = (cut(a, 0.5), cut(b, 0.5)); + meet_away_from_start(an, bn, halvings - 1, budget) + || [(an, bf), (af, bn), (af, bf)].into_iter().any(|(x, y)| boxes_meet(x, y, APART_HALVINGS, budget)) +} + +/// Whether the cubics `a` and `b` may meet: their boxes, control points included, overlap or touch +/// after `halvings` halvings of both. `budget` counts down the comparisons. +fn boxes_meet(a: Bez, b: Bez, halvings: u32, budget: &mut u64) -> bool { + if !charge(budget, 1) { + return true; + } + let bounds = + |c: &Bez| c.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |e, q| [e[0].min(q.x), e[1].min(q.y), e[2].max(q.x), e[3].max(q.y)]); + let (p, q) = (bounds(&a), bounds(&b)); + if p[0] > q[2] || q[0] > p[2] || p[1] > q[3] || q[1] > p[3] { + return false; + } + if halvings == 0 { + return true; + } + let ((a0, a1), (b0, b1)) = (cut(a, 0.5), cut(b, 0.5)); + [(a0, b0), (a0, b1), (a1, b0), (a1, b1)].into_iter().any(|(x, y)| boxes_meet(x, y, halvings - 1, budget)) +} + +/// Whether, at a point where two segments of the subpath `s` meet (the last and the first +/// included, closing it), the subpath's pieces beside that point may meet away from it: a line +/// whole, and the first or last of a cubic's [`CURVE_STEPS`] pieces. These are the curves along +/// the neighboring edges of the flattened polygon, which [`crosses`] does not compare. Segments +/// that do not leave their start are skipped, and two lines are not compared. `budget` counts down +/// the comparisons. +fn joints_meet(s: &SubPath, budget: &mut u64) -> bool { + let line = |a: Pt, b: Pt| [a, lerp(a, b, 1.0 / 3.0), lerp(a, b, 2.0 / 3.0), b]; + // Each segment as a cubic, and whether it is a cubic. + let mut curves: Vec<(Bez, bool)> = Vec::with_capacity(s.segments.len() + 1); + let mut last = s.start; + for seg in &s.segments { + let c = match *seg { + Segment::Line(p) => (line(last, p), false), + Segment::Cubic(c1, c2, p) => ([last, c1, c2, p], true), + }; + last = c.0[3]; + if c.0.iter().any(|q| *q != c.0[0]) { + curves.push(c); + } + } + if last != s.start { + curves.push((line(last, s.start), false)); + } + let n = curves.len(); + if n < 2 { + return false; + } + let piece = 1.0 / f64::from(CURVE_STEPS); + (0..n).any(|k| { + let ((a, a_cubic), (b, b_cubic)) = (curves[k], curves[(k + 1) % n]); + // Two lines meet away from their shared point only by one running back along the other, + // which wraps no area, so the rules fill the same. + if !a_cubic && !b_cubic { + return false; + } + // Both from the point they share. + let a = if a_cubic { cut(a, 1.0 - piece).1 } else { a }; + let a = [a[3], a[2], a[1], a[0]]; + let b = if b_cubic { cut(b, piece).0 } else { b }; + // Turned about the shared point so that `b` leaves it along x: two cubics leaving it along + // one tangent then have boxes thin across it, which part as soon as the cubics do. + let o = b[0]; + let lead = b[1..].iter().map(|q| (q.x - o.x, q.y - o.y)).find(|v| v.0 != 0.0 || v.1 != 0.0).unwrap_or((1.0, 0.0)); + let (sin, cos) = lead.1.atan2(lead.0).sin_cos(); + let turn = |c: Bez| c.map(|q| Pt { x: (q.x - o.x) * cos + (q.y - o.y) * sin, y: (q.y - o.y) * cos - (q.x - o.x) * sin }); + meet_away_from_start(turn(a), turn(b), NEAR_HALVINGS, budget) + }) +} + +/// A rectangle from the origin to (`w`, `h`) with its corners rounded by `radii`, counterclockwise +/// from the corner at (`w`, 0), as [`Geometry::Rect`] gives them. On each edge a corner's radius +/// reaches no further than where its neighbor's begins, unless that leaves it less than half the +/// edge. +fn rect_path(w: f64, h: f64, radii: [f64; 4]) -> Path { + // A quarter circle as a cubic: the control points lie this share of the radius from the ends. + const K: f64 = 0.552_284_749_830_793_6; + // A negative or NaN radius leaves its corner square. + let radii = radii.map(|r| if r.is_finite() { r.max(0.0) } else { 0.0 }); + // Edge i runs from corner i to corner i + 1: the height, the width, the height, the width. + let len = |i: usize| if i.is_multiple_of(2) { h.abs() } else { w.abs() }; + // On each of its edges a corner reaches up to where its neighbor's corner begins, and at + // least halfway. + let room = |len: f64, other: f64| (len - other).max(len / 2.0); + let radii: [f64; 4] = std::array::from_fn(|i| { + let (next, prev) = ((i + 1) % 4, (i + 3) % 4); + radii[i].min(room(len(i), radii[next])).min(room(len(prev), radii[prev])) + }); + let corners = [Pt { x: w, y: 0.0 }, Pt { x: w, y: h }, Pt { x: 0.0, y: h }, Pt { x: 0.0, y: 0.0 }]; + // `r` along the edge from `c` toward `to`. + let sign = |d: f64| { + if d > 0.0 { + 1.0 + } else if d < 0.0 { + -1.0 + } else { + 0.0 + } + }; + let toward = |c: Pt, to: Pt, r: f64| Pt { x: c.x + sign(to.x - c.x) * r, y: c.y + sign(to.y - c.y) * r }; + let mut segments = Vec::new(); + let mut start = None; + for (i, (&c, r)) in corners.iter().zip(radii).enumerate() { + let (prev, next) = (corners[(i + 3) % 4], corners[(i + 1) % 4]); + // The corner is entered along the edge from the previous corner and left toward the next. + let (a, b) = (toward(c, prev, r), toward(c, next, r)); + match start { + None => start = Some(a), + Some(_) => segments.push(Segment::Line(a)), + } + if r > 0.0 { + let c1 = Pt { x: a.x + (c.x - a.x) * K, y: a.y + (c.y - a.y) * K }; + let c2 = Pt { x: b.x + (c.x - b.x) * K, y: b.y + (c.y - b.y) * K }; + segments.push(Segment::Cubic(c1, c2, b)); + } + } + let start = start.unwrap_or(corners[0]); + segments.push(Segment::Line(start)); + Path { subpaths: vec![SubPath { start, segments, closed: true }] } +} + +/// The ellipse in the box from the origin to (`w`, `h`) as four cubics. +fn ellipse_path(w: f64, h: f64) -> Path { + const K: f64 = 0.552_284_749_830_793_6; + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let p = |x: f64, y: f64| Pt { x: cx + x, y: cy + y }; + let start = p(rx, 0.0); + let segments = vec![ + Segment::Cubic(p(rx, ry * K), p(rx * K, ry), p(0.0, ry)), + Segment::Cubic(p(-rx * K, ry), p(-rx, ry * K), p(-rx, 0.0)), + Segment::Cubic(p(-rx, -ry * K), p(-rx * K, -ry), p(0.0, -ry)), + Segment::Cubic(p(rx * K, -ry), p(rx, -ry * K), start), + ]; + Path { subpaths: vec![SubPath { start, segments, closed: true }] } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 5c358d2f04..4c9ee11bb7 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -11,7 +11,7 @@ //! panic. //! //! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the -//! reader reads it. Nothing here writes `.cmx` files. +//! reader reads it. [`write_cmx`] writes `.cmx` files in the layouts the reader reads. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -20,6 +20,7 @@ use std::fmt; mod build; mod bytes; mod cmx; +mod cmx_write; mod geometry; mod inline; mod layout; @@ -38,6 +39,7 @@ mod wl; mod write; mod zip; +pub use cmx_write::{MAX_CURVE_POINTS, Written}; pub use limits::Limits; pub use model::{Drawing, Warning}; pub use preview::{Preview, PreviewFormat, preview}; @@ -66,7 +68,8 @@ pub enum Error { Version(u16), /// A container structure that doesn't parse. Damaged(&'static str), - /// Past one of the [`Limits`]. + /// Past one of the [`Limits`]; from [`write_cmx`], also past what a `.cmx` file holds, or an + /// outline width that is negative or NaN. Limit(&'static str), /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a @@ -118,3 +121,40 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { let mut budget = limits::Budget::new(limits); cmx::drawing(bytes, &mut budget) } + +/// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts +/// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and +/// outlines. [`read_cmx`] reading the file within `limits` leaves nothing out because of them; +/// what the file holds differently from the drawing, such as a name the reader shortens, is +/// reported in [`Written`]. +/// +/// It fails with [`Error::Limit`], and writes nothing, for: +/// - a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline +/// width, or a page side that rounds to 0; +/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash +/// patterns or outlines, or a dash pattern of more than 32,765 lengths; +/// - groups nested deeper than the depth of `limits`, a depth of 0, at which the reader leaves out +/// the index list, more than 65,535 groups directly inside one group, or more chunks, objects, +/// coordinates or dashes than a read within `limits` takes; +/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds. +/// +/// [`Written`] reports what the file holds differently from the drawing; its fields name each +/// case. A rounded rectangle under a scale that keeps right angles but differs along its sides is +/// written with round corners of its radii times the square root of the scales' product, not with +/// stretched corners, and is not reported. +/// +/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the +/// model and value fields that other readers read. In those fields a spot color is written as its +/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black. +/// +/// The file holds an index, so that a reader that finds the tables and pages through it, rather +/// than by their chunk ids, opens it: the header gives where the master index starts, the index +/// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the +/// page, layer and group records give their instruction counts. A page's record also gives where +/// its end-page instruction starts, and a group's record gives where the instruction after its +/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of +/// its curves, or of the page when it has none. The header's bounds and instruction count are not +/// written. +pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { + cmx_write::write(drawing, limits) +} diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index 49adcedc7e..49000468c9 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -15,7 +15,7 @@ const MAX_SKIPPED: usize = 4; const MAX_OUTLINE_RECORDS: usize = 16; /// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of /// a layer's. -const MAX_NAME: usize = 256; +pub(crate) const MAX_NAME: usize = 256; /// A header field: u16 in short files, u32 otherwise. fn word(r: &mut Rd, p: &Profile) -> Option { @@ -260,7 +260,7 @@ fn b_tint(b: &[u8]) -> Option { } /// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). -fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { +pub(crate) fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { if tint <= 0.0 { return rgb; } @@ -486,7 +486,7 @@ fn with_hash(name: String, hash: Option) -> String { /// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes /// are Latin-1. -const CP1252_HIGH: [char; 32] = [ +pub(crate) const CP1252_HIGH: [char; 32] = [ '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', ]; diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs new file mode 100644 index 0000000000..f25ed11fe2 --- /dev/null +++ b/crates/cdr/tests/it/cmx_write.rs @@ -0,0 +1,1558 @@ +//! Writing `.cmx` files: what [`write_cmx`] writes reads back through [`read_cmx`] as the same +//! drawing, and what it can't hold is refused or reported. + +use craft_cdr::model::{ + Cap, Color, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; +use craft_cdr::{Error, Limits, MAX_CURVE_POINTS, Written, is_cmx, read_cmx}; +use proptest::prelude::*; + +/// [`craft_cdr::write_cmx`] within the default limits. +fn write_cmx(d: &Drawing) -> Result { + craft_cdr::write_cmx(d, Limits::default()) +} + +fn layer(name: &str, objects: Vec) -> Layer { + Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } +} + +fn drawing(pages: Vec) -> Drawing { + Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() } +} + +fn square(x: f64, y: f64, side: f64) -> Geometry { + let p = |x, y| Pt { x, y }; + Geometry::Path(Path { + subpaths: vec![SubPath { + start: p(x, y), + segments: vec![Segment::Line(p(x + side, y)), Segment::Line(p(x + side, y + side)), Segment::Line(p(x, y + side))], + closed: true, + }], + }) +} + +fn outline(color: Color) -> Outline { + Outline { width: 2.0, color, cap: Cap::Round, join: Join::Bevel, dashes: Vec::new(), behind_fill: false, scale_with: false } +} + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// Every point (anchors and controls) of a geometry that is a path. +fn points(g: &Geometry) -> Vec { + let Geometry::Path(p) = g else { panic!("not a path: {g:?}") }; + let mut out = Vec::new(); + for sp in &p.subpaths { + out.push(sp.start); + for s in &sp.segments { + match s { + Segment::Line(a) => out.push(*a), + Segment::Cubic(a, b, c) => out.extend([*a, *b, *c]), + } + } + } + out +} + +fn bounds(g: &Geometry) -> (f64, f64, f64, f64) { + points(g).iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.x), b.1.min(p.y), b.2.max(p.x), b.3.max(p.y))) +} + +/// Within a coordinate unit of 0.1 µm (0.000283 pt), in points. +fn near(a: f64, b: f64) -> bool { + (a - b).abs() <= 0.0003 +} + +fn near_color(a: &Color, b: &Color) -> bool { + let close = |x: &[f32], y: &[f32], tol: f32| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (p - q).abs() <= tol); + match (a, b) { + (Color::Rgb(x), Color::Rgb(y)) => close(x, y, 1.0 / 255.0), + (Color::Cmyk(x), Color::Cmyk(y)) => close(x, y, 0.005), + (Color::Gray(x), Color::Gray(y)) => (x - y).abs() <= 1.0 / 255.0, + (Color::Registration, Color::Registration) => true, + (Color::Spot { name: n, tint: t, look: l }, Color::Spot { name: m, tint: u, look: k }) => { + n == m && (t - u).abs() <= 0.005 && close(&l.unwrap_or_default(), &k.unwrap_or_default(), 2.0 / 255.0) + } + _ => false, + } +} + +fn round_trip(d: &Drawing) -> Drawing { + let w = write_cmx(d).unwrap(); + assert!(is_cmx(&w.bytes)); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + back +} + +#[test] +fn a_drawing_reads_back_as_written() { + let red = Color::Rgb([1.0, 0.2, 0.0]); + let cyan = Color::Cmyk([0.6, 0.0, 0.13, 0.05]); + let spot = Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }; + let dashed = + Outline { dashes: vec![3.0, 1.0], behind_fill: true, scale_with: true, cap: Cap::Square, join: Join::Miter, ..outline(Color::Gray(0.75)) }; + let back_layer = layer( + "Art", + vec![ + Object::Shape(Box::new(Shape::new(square(-50.0, -50.0, 100.0), Matrix::IDENTITY, Some(red.clone()), Some(outline(Color::Registration))))), + Object::Group { + objects: vec![ + Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(cyan.clone()), Some(dashed.clone())))), + Object::Shape(Box::new(Shape::new(square(20.0, 0.0, 10.0), Matrix::IDENTITY, Some(spot.clone()), None))), + ], + flags: Flags::default(), + }, + ], + ); + let front_layer = + layer("Über", vec![Object::Shape(Box::new(Shape::new(square(5.0, 5.0, 1.0), Matrix::IDENTITY, None, Some(outline(cyan.clone())))))]); + let d = drawing(vec![ + Page { size: Some((595.0, 842.0)), layers: vec![front_layer, back_layer] }, + Page { + size: Some((200.0, 100.0)), + layers: vec![layer( + "Second", + vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.3)), None)))], + )], + }, + ]); + let back = round_trip(&d); + assert_eq!(back.pages.len(), 2); + let (w, h) = back.pages[0].size.unwrap(); + assert!(near(w, 595.0) && near(h, 842.0)); + let names: Vec<&str> = back.pages[0].layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Über", "Art"], "layers keep their order and names"); + let art = &back.pages[0].layers[1].objects; + let s = shape(&art[0]); + assert!(near_color(s.fill.as_ref().unwrap(), &red)); + assert_eq!(s.outline.as_ref().unwrap().color, Color::Registration); + let (x0, y0, x1, y1) = bounds(&s.geometry); + assert!(near(x0, -50.0) && near(y0, -50.0) && near(x1, 50.0) && near(y1, 50.0)); + let Object::Group { objects, .. } = &art[1] else { panic!("not a group: {:?}", art[1]) }; + let o = shape(&objects[0]).outline.clone().unwrap(); + assert!(near_color(shape(&objects[0]).fill.as_ref().unwrap(), &cyan)); + assert!(near(o.width, 2.0) && near_color(&o.color, &Color::Gray(0.75))); + assert_eq!((o.cap, o.join, o.dashes, o.behind_fill, o.scale_with), (Cap::Square, Join::Miter, vec![3.0, 1.0], true, true)); + assert!(near_color(shape(&objects[1]).fill.as_ref().unwrap(), &spot), "{:?}", shape(&objects[1]).fill); + assert!(shape(&objects[1]).outline.is_none()); + let front = shape(&back.pages[0].layers[0].objects[0]); + assert!(front.fill.is_none() && front.outline.as_ref().is_some_and(|o| o.cap == Cap::Round && o.join == Join::Bevel)); + let (w, h) = back.pages[1].size.unwrap(); + assert!(near(w, 200.0) && near(h, 100.0)); +} + +#[test] +fn rectangles_and_ellipses_are_written_as_curves_in_their_place() { + let m = Matrix([1.0, 0.0, 0.0, 1.0, 10.0, -20.0]); + let rect = Shape::new(Geometry::Rect { w: 40.0, h: -30.0, radii: [5.0, 0.0, 50.0, 2.0] }, m, Some(Color::Gray(1.0)), None); + let ellipse = Shape::new(Geometry::Ellipse { w: 20.0, h: 10.0 }, m, Some(Color::Gray(1.0)), None); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(rect)), Object::Shape(Box::new(ellipse))])] }]); + let back = round_trip(&d); + let objects = &back.pages[0].layers[0].objects; + let (x0, y0, x1, y1) = bounds(&shape(&objects[0]).geometry); + assert!(near(x0, 10.0) && near(y0, -50.0) && near(x1, 50.0) && near(y1, -20.0), "{:?}", (x0, y0, x1, y1)); + let Geometry::Path(p) = &shape(&objects[1]).geometry else { panic!() }; + assert!(p.subpaths[0].closed && p.subpaths[0].segments.iter().all(|s| matches!(s, Segment::Cubic(..)))); + let (x0, y0, x1, y1) = bounds(&shape(&objects[1]).geometry); + assert!(near(x0, 10.0) && near(x1, 30.0) && near(y0, -20.0) && near(y1, -10.0)); +} + +#[test] +fn a_path_past_the_points_a_curve_holds_is_written_as_a_group_of_curves() { + let n = MAX_CURVE_POINTS * 2 + 10; + let segments = (1..n).map(|i| Segment::Line(Pt { x: i as f64 * 0.01, y: (i % 2) as f64 })).collect(); + let long = Shape::new( + Geometry::Path(Path { subpaths: vec![SubPath { start: Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), + Matrix::IDENTITY, + None, + Some(outline(Color::Gray(1.0))), + ); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(long))])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.split_paths && w.cut_subpaths, "an outline gets caps where the pieces meet"); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert!(objects.len() >= 3); + // The pieces meet end to start, so every point is kept, the joins twice. + let total: usize = objects.iter().map(|o| points(&shape(o).geometry).len()).sum(); + assert_eq!(total, n + objects.len() - 1); + // A filled shape cut into pieces is reported. + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!() }; + let filled = Shape { fill: Some(Color::Gray(0.5)), ..(**s).clone() }; + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(filled))])] }]); + assert!(write_cmx(&d).unwrap().cut_subpaths); +} + +#[test] +fn names_the_reader_shortens_are_reported() { + // A name as long as the reader keeps whole reads back whole. + let kept = "k".repeat(256); + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, None))); + let d = drawing(vec![Page { size: None, layers: vec![layer(&kept, vec![plain])] }]); + let w = write_cmx(&d).unwrap(); + assert!(!w.long_names); + assert_eq!(read_cmx(&w.bytes, Limits::default()).unwrap().pages[0].layers[0].name, kept); + let long = "n".repeat(257); + let spot = |name: &str| Color::Spot { name: name.into(), tint: 1.0, look: None }; + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(spot(&long)), None); + let short = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s.clone()))])] }]); + assert!(write_cmx(&short).unwrap().long_names, "a long spot name"); + let named = drawing(vec![Page { size: None, layers: vec![layer(&long, vec![Object::Shape(Box::new(Shape { fill: None, ..s.clone() }))])] }]); + assert!(write_cmx(&named).unwrap().long_names, "a long layer name"); + // Two long spot names that differ only past what the reader keeps still read back apart. + let other = format!("{}m", "n".repeat(256)); + let t = Shape { fill: Some(spot(&other)), ..s.clone() }; + let both = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s)), Object::Shape(Box::new(t))])] }]); + let back = read_cmx(&write_cmx(&both).unwrap().bytes, Limits::default()).unwrap(); + let names: Vec = back.pages[0].layers[0] + .objects + .iter() + .filter_map(|o| match shape(o).fill.as_ref() { + Some(Color::Spot { name, .. }) => Some(name.clone()), + _ => None, + }) + .collect(); + assert!(names.len() == 2 && names[0] != names[1], "{names:?}"); +} + +#[test] +fn a_spot_color_at_no_tint_is_reported() { + let spot = |tint| Color::Spot { name: "Ink".into(), tint, look: Some([0.0, 0.0, 1.0]) }; + let file = |c| { + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None); + drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]) + }; + assert!(write_cmx(&file(spot(0.0))).unwrap().zero_tints); + assert!(!write_cmx(&file(spot(0.05))).unwrap().zero_tints); +} + +#[test] +fn coordinates_past_the_32_bit_range_are_refused() { + let far = Shape::new(square(1e6, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(1.0)), None); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(far))])] }]); + assert_eq!(write_cmx(&d), Err(Error::Limit("coordinate range"))); +} + +#[test] +fn dash_lengths_are_rounded_to_whole_outline_widths() { + let o = Outline { dashes: vec![2.4, 0.2], ..outline(Color::Gray(1.0)) }; + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(s))])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.rounded_dashes); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![2.0, 0.0]); +} + +fn one_shape(s: Shape) -> Drawing { + drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]) +} + +#[test] +fn a_page_without_its_own_size_takes_the_drawings() { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.page_size = Some((300.0, 200.0)); + let (w, h) = round_trip(&d).pages[0].size.unwrap(); + assert!(near(w, 300.0) && near(h, 200.0), "{w} {h}"); +} + +#[test] +fn pages_are_numbered_in_their_order() { + let page = |side| Page { + size: Some((100.0, 100.0)), + layers: vec![layer("L", vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, side), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))])], + }; + let bytes = write_cmx(&drawing(vec![page(1.0), page(2.0)])).unwrap().bytes; + // Each page chunk starts with its begin-page instruction: a u16 size, the code 9, then field 1 + // (a tag and a u16 length) whose first u16 is the page number. + let numbers: Vec = bytes + .windows(4) + .enumerate() + .filter(|(_, w)| *w == b"page") + .map(|(i, _)| { + let body = &bytes[i + 8..]; + assert_eq!(i16::from_le_bytes([body[2], body[3]]), 9); + u16::from_le_bytes([body[7], body[8]]) + }) + .collect(); + assert_eq!(numbers, [1, 2]); +} + +/// Field 1 of each entry of the table chunk `id`. +fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { + table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect() +} + +/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and +/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header +/// bytes, the data; 0xff after the last field). +fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec)>> { + let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8; + // The chunk's body runs for the size after its id. + let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize; + assert!(end <= bytes.len(), "{id:?} chunk ends at {end}, past the file"); + let count = usize::from(u16::from_le_bytes([bytes[at], bytes[at + 1]])); + let mut p = at + 2; + let mut out = Vec::new(); + for _ in 0..count { + let mut entry = Vec::new(); + loop { + assert!(p < end, "entry runs past the {id:?} chunk at {p}"); + if bytes[p] == 0xff { + break; + } + assert!(p + 3 <= end, "field header at {p} runs past the {id:?} chunk"); + let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]])); + // A length shorter than its header, or past the chunk, would stop the walk. + assert!(len >= 3 && p + len <= end, "field at {p} has length {len}"); + entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec())); + p += len; + } + p += 1; + out.push(entry); + } + // The size counts the u16 count and the entries; the pad byte comes after it. + assert_eq!(p, end, "{id:?} chunk has bytes left after its entries"); + out +} + +#[test] +fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() { + let solid = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let dashed = Shape::new(square(2.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(Outline { dashes: vec![3.0, 1.0], ..outline(Color::Gray(1.0)) })); + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(solid)), Object::Shape(Box::new(dashed))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let (screens, dashes) = (table_entries(&bytes, b"rscr"), table_entries(&bytes, b"rdot")); + let (line_types, outlines) = (table_entries(&bytes, b"rott"), table_entries(&bytes, b"rotl")); + assert_eq!(outlines.len(), 2); + let mut patterns: Vec<(bool, Vec)> = outlines + .iter() + .map(|o| { + let entry = |i: usize| usize::from(u16::from_le_bytes([o[2 * i], o[2 * i + 1]])); + assert!((1..=screens.len()).contains(&entry(1)), "the screen entry exists"); + let line = entry(0); + assert!((1..=line_types.len()).contains(&line), "the line type entry exists"); + let dash = entry(5); + assert!((1..=dashes.len()).contains(&dash), "the dash entry exists"); + let pattern = &dashes[dash - 1]; + let count = usize::from(u16::from_le_bytes([pattern[0], pattern[1]])); + assert_eq!(pattern.len(), 2 + 2 * count); + let lengths = pattern[2..].chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + // The outline's own line type says whether it is dashed. + (line_types[line - 1][0] & 4 != 0, lengths) + }) + .collect(); + patterns.sort(); + // The solid outline names an empty pattern; the dashed one names its two lengths. + assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]); +} + +#[test] +fn colors_are_also_written_in_the_model_and_value_fields() { + let colors = [ + Color::Rgb([1.0, 0.2, 0.0]), + Color::Cmyk([0.6, 0.0, 0.13, 0.05]), + Color::Gray(0.75), + Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }, + Color::Registration, + ]; + let objects = colors + .iter() + .enumerate() + .map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None)))) + .collect(); + let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]); + let mut bytes = write_cmx(&d).unwrap().bytes; + let entries = table_fields(&bytes, b"rclr"); + // Each entry holds the model and the palette 5 in field 1 and four values in field 2, before + // the property list of field 10. + let mut older: Vec<(Vec, Vec)> = entries + .iter() + .map(|e| { + assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::>(), [1, 2, 10]); + (e[0].2.clone(), e[1].2.clone()) + }) + .collect(); + older.sort(); + let mut want = vec![ + // Red, green and blue. + (vec![5, 5], vec![255, 51, 0, 0]), + // Cyan, magenta, yellow and black in percent. + (vec![2, 5], vec![60, 0, 13, 5]), + // Gray, 255 white. + (vec![9, 5], vec![64, 0, 0, 0]), + // The spot color's look at its tint of 40 percent. + (vec![5, 5], vec![153, 194, 235, 0]), + // The registration color as every ink at 100 percent. + (vec![2, 5], vec![100, 100, 100, 100]), + ]; + want.sort(); + assert_eq!(older, want); + // With field 10 retagged, the reader takes each color from fields 1 and 2. + for e in &entries { + bytes[e[2].1] = 11; + } + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let fills: Vec = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect(); + let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])]; + assert_eq!(fills.len(), opened.len()); + for (got, want) in fills.iter().zip(&opened) { + assert!(near_color(got, want), "{got:?} for {want:?}"); + } +} + +#[test] +fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() { + let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]); + let width = |scale_with| { + let o = Outline { scale_with, dashes: vec![2.0, 1.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), m, None, Some(o)))); + let o = shape(&back.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert_eq!(o.dashes, vec![2.0, 1.0], "dashes stay in outline widths"); + o.width + }; + assert!(near(width(true), 6.0) && near(width(false), 2.0)); +} + +#[test] +fn a_dash_pattern_of_zero_lengths_stays_solid() { + let o = Outline { dashes: vec![0.0, 0.0], ..outline(Color::Gray(1.0)) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap(); + assert!(!w.rounded_dashes); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes.is_empty()); +} + +#[test] +fn a_spot_color_at_a_low_tint_keeps_its_ink() { + let black = Color::Spot { name: "Ink".into(), tint: 0.0051, look: Some([0.0, 0.0, 0.0]) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(black), None))); + let Some(Color::Spot { look: Some(look), .. }) = shape(&back.pages[0].layers[0].objects[0]).fill.clone() else { panic!("not a spot color") }; + assert!(look.iter().all(|v| *v < 0.1), "{look:?}"); +} + +#[test] +fn hidden_art_is_left_out_and_what_the_file_cant_hold_is_reported() { + let plain = || Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + assert!(!write_cmx(&one_shape(plain())).unwrap().left_out); + let hidden = Shape { flags: Flags { hidden: true, locked: false }, ..plain() }; + let mut hidden_layer = layer("Hidden", vec![Object::Shape(Box::new(plain()))]); + hidden_layer.flags.hidden = true; + let d = drawing(vec![Page { + size: None, + layers: vec![hidden_layer, layer("Shown", vec![Object::Shape(Box::new(hidden)), Object::Shape(Box::new(plain()))])], + }]); + let w = write_cmx(&d).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers.len(), 1); + assert_eq!(back.pages[0].layers[0].objects.len(), 1); + assert!(write_cmx(&one_shape(Shape { opacity: 0.5, ..plain() })).unwrap().left_out, "transparency"); + let mut master = one_shape(plain()); + master.master = vec![layer("Master", vec![Object::Shape(Box::new(plain()))])]; + assert!(write_cmx(&master).unwrap().left_out, "a master layer"); +} + +#[test] +fn a_clipping_containers_outline_is_drawn_over_what_it_clips() { + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.2)), Some(outline(Color::Gray(1.0)))); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.left_out, "the clip itself is not written"); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + // Front to back: the container's outline, the clipped shape, the container's fill. + let kinds: Vec<(bool, bool)> = objects.iter().map(|o| (shape(o).fill.is_some(), shape(o).outline.is_some())).collect(); + assert_eq!(kinds, [(false, true), (true, false), (true, false)]); + assert!(near_color(shape(&objects[2]).fill.as_ref().unwrap(), &Color::Gray(0.2))); +} + +#[test] +fn a_hidden_clipping_container_hides_what_it_clips() { + let mut container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.2)), None); + container.flags.hidden = true; + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let shown = Object::Shape(Box::new(Shape::new(square(20.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip, shown])] }])).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].objects.len(), 1); + assert!(matches!(back.pages[0].layers[0].objects[0], Object::Shape(_))); +} + +#[test] +fn guide_and_grid_layers_are_left_out() { + let art = || vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))]; + let kinds = [LayerKind::Guides, LayerKind::Grid]; + let mut layers: Vec = kinds.iter().map(|k| Layer { kind: *k, ..layer("Construction", art()) }).collect(); + layers.push(layer("Art", art())); + let w = write_cmx(&drawing(vec![Page { size: None, layers }])).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let names: Vec<&str> = back.pages[0].layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Art"]); +} + +#[test] +fn locked_art_is_reported() { + let mut s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + s.flags.locked = true; + assert!(write_cmx(&one_shape(s)).unwrap().left_out); +} + +#[test] +fn nonzero_fills_that_may_fill_differently_are_reported() { + let p = |x, y| Pt { x, y }; + // Two squares turning the same way, one inside the other: nonzero fills the inner one, + // even-odd leaves it a hole. + let ring = |cw: bool, x: f64, side: f64| { + let corners = [p(x, x), p(x + side, x), p(x + side, x + side), p(x, x + side)]; + let pts: Vec = if cw { corners.into_iter().rev().collect() } else { corners.to_vec() }; + SubPath { start: pts[0], segments: pts[1..].iter().map(|q| Segment::Line(*q)).collect(), closed: true } + }; + let filled = |inner_cw: bool, nonzero: bool| { + let geometry = Geometry::Path(Path { subpaths: vec![ring(false, 0.0, 10.0), ring(inner_cw, 2.0, 5.0)] }); + let s = Shape { nonzero, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + write_cmx(&one_shape(s)).unwrap().nonzero_fills + }; + assert!(filled(false, true), "same turn, nested"); + assert!(!filled(true, true), "a counter turning the other way fills the same"); + assert!(!filled(false, false), "an even-odd fill is written as it is"); +} + +#[test] +fn a_subpath_crossing_itself_with_one_net_turn_is_reported() { + let p = |x, y| Pt { x, y }; + // One net turn, but the inside around (1.25, 2.5) is wound twice. + let pts = [p(4.0, 1.0), p(3.0, 1.0), p(0.0, 4.0), p(0.0, 1.0), p(4.0, 4.0), p(0.0, 3.0)]; + let sub = SubPath { start: pts[0], segments: pts[1..].iter().map(|q| Segment::Line(*q)).collect(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A plain square crosses nothing. + let plain = Shape { nonzero: true, ..Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(plain)).unwrap().nonzero_fills); +} + +#[test] +fn a_curve_crossing_where_its_control_points_dont_is_reported() { + let p = |x, y| Pt { x, y }; + // M0 0 C0 10 10 10 10 0 L12 16 -4 11 -4 -1 12 -6 2 9 Z winds twice around (2.5, 7.5). + let mut segments = vec![Segment::Cubic(p(0.0, 10.0), p(10.0, 10.0), p(10.0, 0.0))]; + segments.extend([p(12.0, 16.0), p(-4.0, 11.0), p(-4.0, -1.0), p(12.0, -6.0), p(2.0, 9.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_closing_line_back_to_the_start_is_no_crossing() { + let p = |x, y| Pt { x, y }; + // Clockwise, with the closing line written out. + let segments = [p(0.0, 10.0), p(10.0, 10.0), p(10.0, 0.0), p(0.0, 0.0)].map(Segment::Line).to_vec(); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn an_ink_takes_its_look_from_its_strongest_tint_and_from_master_layers() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look }; + let filled = |c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))); + let red = Some([1.0, 0.0, 0.0]); + // The 0% use, whose look is white, is met first. + let d = drawing(vec![Page { + size: None, + layers: vec![layer("L", vec![filled(ink(1.0, None)), filled(ink(1.0, red)), filled(ink(0.0, Some([1.0; 3])))])], + }]); + let back = round_trip(&d); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(1.0, red))); + let mut d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![filled(ink(1.0, None))])] }]); + d.master = vec![layer("Master", vec![filled(ink(1.0, red))])]; + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(1.0, red))); +} + +#[test] +fn an_empty_layer_and_a_name_ending_in_nul_are_reported() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let empty = drawing(vec![Page { size: None, layers: vec![layer("Empty", Vec::new()), layer("L", vec![plain()])] }]); + assert!(write_cmx(&empty).unwrap().left_out); + let padded = drawing(vec![Page { size: None, layers: vec![layer("L\0", vec![plain()])] }]); + assert!(write_cmx(&padded).unwrap().long_names); +} + +#[test] +fn a_subpath_going_over_its_edges_again_is_reported() { + let p = |x, y| Pt { x, y }; + // The square right of the start twice counterclockwise, then the square left of it once + // clockwise: one net turn, and the right square wound twice. + let pts = [(1, 0), (1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0), (-1, 0), (-1, 1), (0, 1)].map(|(x, y)| p(f64::from(x), f64::from(y))); + let sub = SubPath { start: p(0.0, 0.0), segments: pts.map(Segment::Line).to_vec(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_shape_with_no_segments_is_reported() { + let empty = Shape::new(Geometry::Path(Path::default()), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let w = write_cmx(&one_shape(empty)).unwrap(); + assert!(w.left_out); +} + +#[test] +fn a_page_side_that_rounds_to_nothing_is_refused() { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.pages[0].size = Some((0.000_01, 720.0)); + assert_eq!(write_cmx(&d), Err(Error::Limit("page size"))); +} + +#[test] +fn layer_names_the_reader_cuts_or_drops_are_reported() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let named = |name: &str| write_cmx(&drawing(vec![Page { size: None, layers: vec![layer(name, vec![plain()])] }])).unwrap().long_names; + assert!(named("Art\0backup"), "cut at the NUL"); + assert!(named(" "), "blank"); + assert!(!named("Art")); +} + +#[test] +fn an_unfilled_clipping_containers_outline_keeps_its_place() { + // Front to back, whether the outline comes first: over the clipped shape, as an outline with + // no fill to be behind is drawn over it too. + for behind_fill in [false, true] { + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, Some(o)); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + let outlined: Vec = objects.iter().map(|o| shape(o).outline.is_some()).collect(); + assert_eq!(outlined, vec![true, false], "behind_fill {behind_fill}"); + } +} + +#[test] +fn a_filled_clipping_containers_outline_goes_over_unless_behind_the_fill() { + // Front to back, as (fill, outline) of each curve: the outline alone over the clipped shape + // and the fill alone behind it, or the whole container behind it when the outline is behind + // the fill. + for behind_fill in [false, true] { + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.1)), Some(o)); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + let parts: Vec<(bool, bool)> = objects.iter().map(|o| (shape(o).fill.is_some(), shape(o).outline.is_some())).collect(); + let want = if behind_fill { vec![(true, false), (true, true)] } else { vec![(false, true), (true, false), (true, false)] }; + assert_eq!(parts, want, "behind_fill {behind_fill}"); + } +} + +#[test] +fn a_page_size_of_nothing_is_refused() { + for size in [(0.0, 720.0), (-10.0, 720.0), (f64::NAN, 720.0)] { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.pages[0].size = Some(size); + assert_eq!(write_cmx(&d), Err(Error::Limit("page size")), "{size:?}"); + } +} + +#[test] +fn an_ink_with_no_known_look_is_reported() { + let ink = |look| Color::Spot { name: "Ink".into(), tint: 1.0, look }; + let written = |c| write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))).unwrap().unknown_looks; + assert!(written(ink(None))); + assert!(!written(ink(Some([1.0, 0.0, 0.0])))); +} + +#[test] +fn loops_meeting_at_one_point_are_reported() { + let p = |x, y| Pt { x, y }; + let o = p(0.0, 0.0); + // Three triangles from the origin; the second, inside the first, is wound twice. + let pts = [p(5.0, 0.0), p(2.0, 5.0), o, p(3.0, 1.0), p(2.0, 3.0), o, p(-5.0, 1.0), p(-2.0, 4.0)]; + let sub = SubPath { start: o, segments: pts.map(Segment::Line).to_vec(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_very_thin_outline_stays_thinner_than_a_hairline() { + let o = Outline { width: 0.000_1, ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + let width = shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().width; + assert!(width > 0.0 && width < 0.01, "{width}"); +} + +#[test] +fn nested_contours_far_from_the_origin_are_still_compared() { + let p = |x, y| Pt { x, y }; + let ring = |x: f64, side: f64| SubPath { + start: p(x, x), + segments: [p(x + side, x), p(x + side, x + side), p(x, x + side)].map(Segment::Line).to_vec(), + closed: true, + }; + let far = 1.0e8; + let geometry = Geometry::Path(Path { subpaths: vec![ring(far, 10.0), ring(far + 2.0, 1.0)] }); + let back_home = Matrix([1.0, 0.0, 0.0, 1.0, -far, -far]); + let s = Shape { nonzero: true, ..Shape::new(geometry, back_home, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_without_a_size_still_writes_its_four_edges() { + let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + // The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length. + assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9); + let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]])); + assert_eq!(len - 3, 2 + 4 + 16 + 4 + 2 + 4, "the page number, the flags, four edges, the end, the layers and the instructions"); +} + +#[test] +fn spot_colors_with_no_name_share_no_look() { + let unnamed = |look| Color::Spot { name: String::new(), tint: 1.0, look }; + let shapes = [unnamed(None), unnamed(Some([1.0, 0.0, 0.0]))] + .map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap(); + assert!(w.unnamed_spots && w.unknown_looks); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let fill = shape(&back.pages[0].layers[0].objects[0]).fill.clone().unwrap(); + assert!(near_color(&fill, &Color::Rgb([0.0, 0.0, 0.0])), "{fill:?}"); +} + +#[test] +fn an_ink_used_with_different_looks_is_reported() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look: Some(look) }; + let written = |second| { + let shapes = + [ink(1.0, [1.0, 0.0, 0.0]), second].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap().merged_looks + }; + assert!(!written(ink(0.5, [1.0, 0.0, 0.0])), "one look"); + assert!(written(ink(0.5, [0.0, 1.0, 0.0])), "a second look"); + // At 1 % both looks store the same color, and only the tint changes it. + let gray = |tint, v| Color::Spot { name: "Gray".into(), tint, look: Some([v; 3]) }; + let shapes = + [gray(1.0, 0.5), gray(0.01, 0.501)].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap(); + assert!(w.zero_tints && !w.merged_looks); +} + +#[test] +fn a_cubic_looping_between_its_samples_is_reported() { + let p = |x, y| Pt { x, y }; + // (s² − 1, s³ − s) for s from −2 to 30 crosses itself at s = −1 and 1. + let mut segments = vec![Segment::Cubic(p(-119.0 / 3.0, 334.0 / 3.0), p(259.0, -5458.0 / 3.0), p(899.0, 26970.0))]; + segments.extend([p(-10.0, 26970.0), p(-10.0, -6.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(3.0, -6.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_gives_the_edges_of_its_art() { + // A small square off the center of a large page. + let d = drawing(vec![Page { + size: Some((600.0, 800.0)), + layers: vec![layer( + "L", + vec![Object::Shape(Box::new(Shape::new(square(100.0, 50.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))], + )], + }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + // Field 1 of the begin-page instruction: the page number, the flags, then the left, top, right + // and bottom edges as i32 in 0.1 µm. + let edge = |i: usize| f64::from(i32::from_le_bytes(bytes[at + 13 + 4 * i..at + 17 + 4 * i].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + let (l, t, r, b) = (edge(0), edge(1), edge(2), edge(3)); + assert!(near(l, 100.0) && near(t, 60.0) && near(r, 110.0) && near(b, 50.0), "{l} {t} {r} {b}"); +} + +#[test] +fn an_outline_width_that_is_not_a_width_is_refused() { + for width in [f64::NAN, -1.0] { + let o = Outline { width, ..outline(Color::Gray(1.0)) }; + assert_eq!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))), Err(Error::Limit("outline width"))); + } +} + +#[test] +fn a_dash_rounded_away_is_reported() { + let o = Outline { dashes: vec![0.000_000_5, 1.0], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn a_cubic_closing_on_its_start_is_no_crossing() { + let p = |x, y| Pt { x, y }; + let segments = vec![Segment::Cubic(p(1.0, 0.0), p(0.0, 1.0), p(0.0, 0.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_negative_width_is_refused_whatever_its_scale() { + let o = Outline { width: -1.0, scale_with: true, ..outline(Color::Gray(1.0)) }; + let flat = Matrix([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), flat, None, Some(o)))), Err(Error::Limit("outline width"))); +} + +#[test] +fn a_page_as_wide_as_the_size_field_holds_is_written() { + // A width that rounds to u32::MAX coordinate units of 0.1 µm, and whose half rounds past what + // an i32 holds. + let widest = (f64::from(u32::MAX) + 0.4) * 1e-7 / 0.0254 * 72.0; + let art = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + for layers in [vec![layer("L", vec![Object::Shape(Box::new(art))])], Vec::new()] { + let d = drawing(vec![Page { size: Some((widest, 100.0)), layers }]); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + let (w, _) = back.pages[0].size.unwrap(); + assert!((w - widest).abs() < 0.01, "{w}"); + } +} + +#[test] +fn a_page_gives_the_edges_its_curves_reach() { + let p = |x, y| Pt { x, y }; + // An arch whose control points reach 100 pt and whose curve reaches 75 pt. + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 100.0), p(100.0, 100.0), p(100.0, 0.0))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = f64::from(i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + assert!(near(top, 75.0), "{top}"); +} + +#[test] +fn dashes_too_short_to_store_keep_their_gaps_of_nothing() { + let o = Outline { dashes: vec![0.4, 0.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![1.0, 0.0]); +} + +#[test] +fn a_rounded_corner_beside_square_ones_keeps_its_radius() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [75.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + // The corner at (100, 0) is entered from (100 − 75, 0) and left toward (100, 75). + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + assert!(pts.iter().any(|q| near(q.x, 25.0) && near(q.y, 0.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 75.0)), "{pts:?}"); +} + +#[test] +fn many_contours_apart_fill_the_same_either_way() { + let p = |x, y| Pt { x, y }; + let triangle = |i: u32| { + let x = f64::from(i) * 3.0; + SubPath { start: p(x, 0.0), segments: vec![Segment::Line(p(x + 1.0, 0.0)), Segment::Line(p(x, 1.0))], closed: true } + }; + let geometry = Geometry::Path(Path { subpaths: (0..1001).map(triangle).collect() }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_gives_the_top_of_a_nearly_flat_cubic() { + let p = |x, y| Pt { x, y }; + // The end one coordinate unit above the start keeps the y derivative quadratic. + let unit = 1e-7 / 0.0254 * 72.0; + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 10000.0), p(1.0, 10000.0), p(1.0, unit))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = f64::from(i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + assert!(near(top, 7500.0), "{top}"); +} + +#[test] +fn a_rounded_rectangle_scaled_unevenly_keeps_round_corners() { + // 100 pt square, 10 pt corners, stretched 4 times across: 400 by 100 pt with 20 pt corners. + let rect = + Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [10.0; 4] }, Matrix([4.0, 0.0, 0.0, 1.0, 0.0, 0.0]), Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // The corner at (400, 0) is entered 20 pt along the bottom edge and left 20 pt up the side. + assert!(pts.iter().any(|q| near(q.x, 380.0) && near(q.y, 0.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 400.0) && near(q.y, 20.0)), "{pts:?}"); +} + +#[test] +fn a_dash_length_off_a_whole_width_by_a_little_is_reported() { + let o = Outline { dashes: vec![1.000_000_5, 1.0], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn only_overlapping_corners_shrink() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [80.0, 80.0, 10.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // The corner at (0, 100) keeps its 10 pt: it is left toward (0, 90). + assert!(pts.iter().any(|q| near(q.x, 0.0) && near(q.y, 90.0)), "{pts:?}"); + // The two 80 pt corners on the right edge meet at its middle. + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 50.0)), "{pts:?}"); +} + +#[test] +fn a_closed_contour_that_fits_one_curve_stays_one_curve() { + let p = |x, y| Pt { x, y }; + // MAX_CURVE_POINTS anchors, the last away from the start: the closing bit closes it. + let n = MAX_CURVE_POINTS; + let segments = (1..n).map(|i| Segment::Line(p(i as f64 * 0.01, if i % 2 == 0 { 0.0 } else { 1.0 }))).collect(); + let s = Shape::new( + Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }), + Matrix::IDENTITY, + None, + Some(outline(Color::Gray(1.0))), + ); + let w = write_cmx(&one_shape(s)).unwrap(); + assert!(!w.split_paths && !w.cut_subpaths); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Geometry::Path(path) = &shape(&back.pages[0].layers[0].objects[0]).geometry else { panic!() }; + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); +} + +#[test] +fn a_page_gives_the_edges_of_the_curve_as_written() { + let p = |x, y| Pt { x, y }; + // Controls 0.6 units up round to 1 unit, so the written curve peaks at 0.75 units. + let unit = 1e-7 / 0.0254 * 72.0; + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 0.6 * unit), p(1.0, 0.6 * unit), p(1.0, 0.0))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap()); + assert!(top >= 1, "{top}"); +} + +#[test] +fn a_blank_layer_name_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("\u{2003}", vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn a_larger_corner_reaches_where_its_smaller_neighbor_begins() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [80.0, 40.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // On the right edge the 80 pt corner is held to 60 pt and the 40 pt one keeps its radius. + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 60.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 60.0) && near(q.y, 100.0)), "{pts:?}"); +} + +#[test] +fn a_long_blank_layer_name_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer(&" ".repeat(257), vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn a_spot_color_with_no_name_at_no_tint_is_reported() { + let unnamed = Color::Spot { name: String::new(), tint: 0.0, look: Some([0.0, 0.0, 1.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(unnamed), None))).unwrap(); + assert!(w.unnamed_spots && w.zero_tints); +} + +#[test] +fn a_drawing_with_no_pages_keeps_its_page_size() { + let mut d = drawing(Vec::new()); + d.page_size = Some((300.0, 200.0)); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + let (w, h) = back.pages[0].size.unwrap(); + assert!(near(w, 300.0) && near(h, 200.0)); +} + +#[test] +fn layers_give_their_page_and_their_number() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let page = || Page { size: None, layers: vec![layer("A", vec![plain()]), layer("B", vec![plain()])] }; + let bytes = write_cmx(&drawing(vec![page(), page()])).unwrap().bytes; + // Each begin-layer instruction: a u16 size, the code 11, field 1 (a tag and a u16 length), then + // the page number and the layer number. + let mut numbers = Vec::new(); + let mut at = 0; + while let Some(i) = bytes[at..].windows(4).position(|w| w == b"page") { + let start = at + i + 8; + let end = start + u32::from_le_bytes(bytes[at + i + 4..start].try_into().unwrap()) as usize; + let mut p = start; + while p < end { + let size = usize::from(u16::from_le_bytes([bytes[p], bytes[p + 1]])); + assert!(size >= 4 && p + size <= end, "an instruction of {size} bytes at {p}"); + if i16::from_le_bytes([bytes[p + 2], bytes[p + 3]]) == 11 { + numbers.push((u16::from_le_bytes([bytes[p + 7], bytes[p + 8]]), u16::from_le_bytes([bytes[p + 9], bytes[p + 10]]))); + } + p += size; + } + at = end; + } + assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]); +} + +fn u16_at(b: &[u8], at: usize) -> usize { + usize::from(u16::from_le_bytes([b[at], b[at + 1]])) +} + +fn u32_at(b: &[u8], at: usize) -> usize { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize +} + +/// The id of each chunk of a written file by where it starts, those inside lists included. +fn chunk_ids(b: &[u8]) -> std::collections::HashMap { + let mut ids = std::collections::HashMap::new(); + let mut stack = vec![(12, b.len())]; + while let Some((mut at, end)) = stack.pop() { + while at + 8 <= end { + let id: [u8; 4] = b[at..at + 4].try_into().unwrap(); + let size = u32_at(b, at + 4); + ids.insert(at, id); + if id == *b"LIST" { + stack.push((at + 12, at + 8 + size)); + } + at += 8 + size + size % 2; + } + } + ids +} + +/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where +/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test. +fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> { + let mut out = Vec::new(); + while b[at] != 0xff { + let len = u16_at(b, at + 1); + assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}"); + out.push((b[at], at + 3)); + at += len; + } + out +} + +#[test] +#[should_panic(expected = "a field of length 0")] +fn a_field_of_length_0_fails_the_check() { + field_starts(&[1, 0, 0, 0xff], 0, 4); +} + +#[test] +#[should_panic(expected = "a field of length 9")] +fn a_field_past_its_instruction_fails_the_check() { + field_starts(&[1, 9, 0, 0, 0xff], 0, 5); +} + +#[test] +fn the_index_and_the_records_give_where_everything_is() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let inner = Object::Group { objects: vec![plain(20.0)], flags: Flags::default() }; + let outer = Object::Group { objects: vec![plain(0.0), inner, plain(50.0)], flags: Flags::default() }; + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![outer]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0), plain(2.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let page_entries = page_index(&b); + let layer_starts = layer_tables(&b, &page_entries, &[&["Back", "Front"], &["Only"]]); + let (seen_layers, groups) = page_records(&b, &page_entries); + assert_eq!(seen_layers, layer_starts); + // The inner group: itself and a curve; the outer: two curves and the inner group. + assert_eq!(groups, [(0, 3), (1, 7)]); +} + +/// The page index of a written file of two pages, each entry's page chunk, layer table, picture +/// and reference list, checked through the header and the master index. +fn page_index(b: &[u8]) -> Vec<[usize; 4]> { + let ids = chunk_ids(b); + let id = |at: usize| ids.get(&at).map(|i| String::from_utf8_lossy(i).into_owned()).unwrap_or_default(); + // The header names the master index, and no information list or picture. + let cont = 12 + 8; + let ixmr = u32_at(b, cont + 84); + assert_eq!(id(ixmr), "ixmr"); + assert_eq!((u32_at(b, cont + 88), u32_at(b, cont + 92)), (u32::MAX as usize, u32::MAX as usize)); + // The master index names itself, the page index, the table of layer tables and each table. + let m = ixmr + 8; + assert_eq!((u16_at(b, m), u16_at(b, m + 2)), (1, 24)); + let entries: Vec<(usize, String)> = (0..u16_at(b, m + 4)).map(|i| (u16_at(b, m + 6 + 6 * i), id(u32_at(b, m + 8 + 6 * i)))).collect(); + let want = + [(1, "ixmr"), (2, "ixpg"), (3, "ixtl"), (15, "rotl"), (16, "rott"), (17, "rota"), (18, "rscr"), (19, "rpen"), (20, "rdot"), (21, "rclr")]; + assert_eq!(entries, want.map(|(n, s)| (n, s.to_string()))); + let at_of = |n: usize| u32_at(b, m + 8 + 6 * entries.iter().position(|(k, _)| *k == n).unwrap()); + // The page index: each page chunk, its layer table, no picture and its reference list. + let pg = at_of(2) + 8; + assert_eq!(u16_at(b, pg), 2); + let page_entries: Vec<[usize; 4]> = (0..2) + .map(|i| { + let e = pg + 2 + 18 * i; + assert_eq!(u16_at(b, e), 16); + [0, 1, 2, 3].map(|k| u32_at(b, e + 2 + 4 * k)) + }) + .collect(); + for [page, layers, picture, refs] in &page_entries { + assert_eq!((id(*page), id(*layers), *picture, id(*refs)), ("page".into(), "ixlr".into(), u32::MAX as usize, "rlst".into())); + } + // The table of layer tables lists each page's. + let tl = at_of(3) + 8; + assert_eq!([u16_at(b, tl), u16_at(b, tl + 2), u16_at(b, tl + 4)], [2, 4, 3]); + assert_eq!([u32_at(b, tl + 6), u32_at(b, tl + 10)], [page_entries[0][1], page_entries[1][1]]); + page_entries +} + +/// Where each layer table of `page_entries` says the layers named `names` start, checking each +/// table and each reference list: a layer table holds its count, the page number, then each +/// layer's begin-layer instruction and name, back to front; a reference list a count, and 2, 9 and +/// the number of each layer. +fn layer_tables(b: &[u8], page_entries: &[[usize; 4]], names: &[&[&str]]) -> Vec { + let mut layer_starts = Vec::new(); + for (n, (entry, names)) in page_entries.iter().zip(names).enumerate() { + let t = entry[1] + 8; + assert_eq!((u16_at(b, t), u16_at(b, t + 2)), (names.len(), n + 1)); + let mut at = t + 4; + for name in *names { + let size = u16_at(b, at); + let start = u32_at(b, at + 2); + let len = u16_at(b, at + 6); + assert_eq!((size, &b[at + 8..at + 8 + len]), (8 + name.len(), name.as_bytes())); + assert_eq!(u32_at(b, at + 8 + len), u32::MAX as usize); + assert_eq!(u16_at(b, start + 2), 11, "a begin-layer instruction"); + layer_starts.push(start); + at += size + 4; + } + let r = entry[3] + 8; + let refs: Vec = (0..1 + 3 * names.len()).map(|i| u16_at(b, r + 2 * i)).collect(); + let want: Vec = std::iter::once(names.len()).chain((1..=names.len()).flat_map(|k| [2, 9, k])).collect(); + assert_eq!(refs, want); + } + layer_starts +} + +/// An open begin-page, begin-layer or begin-group record: its code, where its field 1 starts, the +/// instructions before it, the records found directly inside it and the edges of its curves. +type Open = (usize, usize, usize, usize, Option<[i32; 4]>); + +/// Check what the record `open` gives, now closed by the instruction of `code` and `size` at `at` +/// after `count` instructions of its page: begin page where the page ends, its layers and its +/// instructions; begin layer its instructions; begin group the edges of its curves, then its +/// groups and instructions, which are returned, and where the instruction after it starts. +fn closed_record(b: &[u8], open: Open, code: usize, at: usize, size: usize, count: usize) -> Option<(usize, usize)> { + let (opened, f1, before, inside, edges) = open; + assert_eq!(opened + 1, code); + let instructions = count - before; + match code { + 10 => { + assert_eq!(u32_at(b, f1 + 22), at, "where the page ends"); + assert_eq!(u16_at(b, f1 + 26), inside, "the page's layers"); + assert_eq!(u32_at(b, f1 + 28), instructions); + None + } + 12 => { + assert_eq!(u32_at(b, f1 + 8), instructions); + None + } + _ => { + let [x0, y0, x1, y1] = edges.unwrap(); + let stored: Vec = (0..4).map(|k| u32_at(b, f1 + 4 * k) as i32).collect(); + assert_eq!(stored, [x0, y1, x1, y0], "left, top, right and bottom"); + assert_eq!(u32_at(b, f1 + 22), at + size, "where the group ends"); + Some((u16_at(b, f1 + 16), u32_at(b, f1 + 18))) + } + } +} + +/// Walk the instructions of each page of `page_entries`, checking the begin-page, begin-layer and +/// begin-group records, and give where each begin-layer instruction starts and each group's +/// groups and instructions, in the order the groups end. +fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usize, usize)>) { + let mut seen_layers = Vec::new(); + let mut groups = Vec::new(); + for entry in page_entries { + let end = entry[0] + 8 + u32_at(b, entry[0] + 4); + let mut at = entry[0] + 8; + let mut open: Vec = Vec::new(); + let mut count = 0; + while at < end { + let size = instruction_size(b, at, end); + let code = u16_at(b, at + 2); + count += 1; + match code { + 9 | 11 | 13 => { + let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1; + if code == 11 { + seen_layers.push(at); + } + // A page counts its layers and a group the groups directly inside it. + if code != 9 { + open.last_mut().unwrap().3 += 1; + } + open.push((code, f1, count - 1, 0, None)); + } + 67 => { + let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1; + for i in 0..u16_at(b, f2) { + let p = f2 + 2 + 8 * i; + let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32); + for o in open.iter_mut().filter(|o| o.0 == 13) { + let e = o.4.get_or_insert([x, y, x, y]); + *e = [e[0].min(x), e[1].min(y), e[2].max(x), e[3].max(y)]; + } + } + } + 10 | 12 | 14 => groups.extend(closed_record(b, open.pop().unwrap(), code, at, size, count)), + _ => {} + } + at += size; + } + } + (seen_layers, groups) +} + +/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold +/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or +/// one past `end` fails the test. +fn instruction_size(b: &[u8], at: usize, end: usize) -> usize { + let size = u16_at(b, at); + assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}"); + size +} + +#[test] +#[should_panic(expected = "an instruction of size 0")] +fn an_instruction_of_size_0_fails_the_check() { + instruction_size(&[0, 0, 67, 0], 0, 4); +} + +#[test] +#[should_panic(expected = "an instruction of size 65535")] +fn a_long_instruction_fails_the_check() { + instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8); +} + +#[test] +#[should_panic(expected = "an instruction of size 8")] +fn an_instruction_past_its_page_fails_the_check() { + instruction_size(&[8, 0, 67, 0], 0, 4); +} + +#[test] +fn a_uniform_fill_names_the_screen_the_file_holds() { + let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; + // The fill's field 1: a tag, a length of 7, the color entry 1 and the screen entry 1. + assert!(bytes.windows(7).any(|w| w == [1, 7, 0, 1, 0, 1, 0])); + assert_eq!(table_entries(&bytes, b"rscr").len(), 1); +} + +#[test] +fn an_unpainted_clipping_container_is_not_written() { + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, None); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert_eq!(objects.len(), 1, "only the clipped shape"); +} + +#[test] +fn groups_nested_deeper_than_the_reader_reads_are_refused() { + let nest = |depth: usize| { + let mut o = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + drawing(vec![Page { size: None, layers: vec![layer("L", vec![o])] }]) + }; + let deepest = Limits::default().depth; + assert!(round_trip(&nest(deepest)).pages[0].layers.len() == 1, "as deep as the reader reads"); + assert_eq!(write_cmx(&nest(deepest + 1)), Err(Error::Limit("nesting depth"))); +} + +#[test] +fn a_file_the_reader_would_not_take_whole_within_the_limits_is_refused() { + let dashed = Outline { dashes: vec![2.0, 1.0, 3.0], ..outline(Color::Gray(0.0)) }; + let art = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), Some(dashed.clone())))); + let group = Object::Group { objects: vec![art(0.0), art(20.0)], flags: Flags::default() }; + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![group, art(40.0)])] }]); + let whole = write_cmx(&d).unwrap().bytes; + let fields: [fn(&mut Limits) -> &mut usize; 5] = + [|l| &mut l.chunks, |l| &mut l.objects, |l| &mut l.coordinates, |l| &mut l.dashes, |l| &mut l.depth]; + for (i, field) in fields.into_iter().enumerate() { + let (mut written, mut refused) = (false, false); + for v in 0..=80 { + let mut limits = Limits::default(); + *field(&mut limits) = v; + // What the reader takes from the file written within the default limits. + let opens_whole = read_cmx(&whole, limits).is_ok_and(|back| back.warnings.is_empty()); + match craft_cdr::write_cmx(&d, limits) { + Ok(w) => { + written = true; + assert!(opens_whole, "field {i} at {v}: written but not read whole"); + assert_eq!(w.bytes, whole, "field {i} at {v}"); + } + Err(e) => { + refused = true; + assert!(matches!(e, Error::Limit(_)), "field {i} at {v}: {e:?}"); + assert!(!opens_whole, "field {i} at {v}: refused but read whole"); + } + } + } + assert!(written && refused, "field {i}: both outcomes within 0 to 80"); + } + let input = |n: usize| craft_cdr::write_cmx(&d, Limits { input: n, ..Limits::default() }); + assert!(input(whole.len()).is_ok()); + assert_eq!(input(whole.len() - 1), Err(Error::Limit("input size"))); + // A pattern with no positive length is solid, and the reader takes no dashes for it. + let solid = Outline { dashes: vec![f64::NAN, 0.0], ..outline(Color::Gray(0.0)) }; + let one = one_shape(Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, Some(solid))); + let w = craft_cdr::write_cmx(&one, Limits { dashes: 0, ..Limits::default() }).unwrap(); + assert!(w.rounded_dashes, "the length that is not a number"); + assert!(read_cmx(&w.bytes, Limits { dashes: 0, ..Limits::default() }).unwrap().warnings.is_empty()); +} + +#[test] +fn a_negative_radius_leaves_its_corner_square() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [-20.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 0.0)), "{pts:?}"); +} + +#[test] +fn every_use_of_an_ink_takes_the_look_of_its_strongest_tint() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look: Some(look) }; + let filled = |c, hidden| { + let mut s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None); + s.flags.hidden = hidden; + Object::Shape(Box::new(s)) + }; + let d = drawing(vec![Page { + size: None, + layers: vec![layer("L", vec![filled(ink(0.5, [0.0, 1.0, 0.0]), false), filled(ink(1.0, [1.0, 0.0, 0.0]), true)])], + }]); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(0.5, [1.0, 0.0, 0.0]))); +} + +#[test] +fn a_name_that_is_only_nuls_as_written_is_reported() { + let name = format!("{}Ink", "\0".repeat(4096)); + let c = Color::Spot { name, tint: 1.0, look: Some([1.0, 0.0, 0.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))).unwrap(); + assert!(w.unnamed_spots && w.long_names); +} + +#[test] +fn a_tint_too_low_to_keep_the_look_is_reported() { + let pale = Color::Spot { name: "Pale".into(), tint: 0.01, look: Some([1.0, 0.85, 0.85]) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(pale), None))).unwrap().zero_tints); +} + +#[test] +fn a_shape_split_into_curves_paints_its_fill_before_its_outline() { + let p = |x, y| Pt { x, y }; + // A long polyline, then a square: two curves. + let segments = (1..MAX_CURVE_POINTS).map(|i| Segment::Line(p(i as f64 * 0.01, 5.0))).collect(); + let long = SubPath { start: p(0.0, 0.0), segments, closed: false }; + let Geometry::Path(sq) = square(2.0, 2.0, 5.0) else { panic!() }; + for behind_fill in [false, true] { + let geometry = Geometry::Path(Path { subpaths: vec![long.clone(), sq.subpaths[0].clone()] }); + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.2)), Some(o)))); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + // Each curve carries the fill or the outline, the outlines all on one side of the fills. + let outlines: Vec = objects.iter().map(|o| shape(o).outline.is_some()).collect(); + assert!(objects.iter().all(|o| shape(o).fill.is_some() != shape(o).outline.is_some()), "{outlines:?}"); + assert!(outlines.windows(2).all(|w| w[0] >= w[1]) || outlines.windows(2).all(|w| w[0] <= w[1]), "{outlines:?}"); + // Front to back: the outline is in front unless it is drawn behind the fill. + assert_eq!(outlines[0], !behind_fill, "{outlines:?}"); + } +} + +#[test] +fn a_dash_pattern_past_one_table_entry_is_refused() { + let file = |n: usize| { + let o = Outline { dashes: vec![1.0; n], ..outline(Color::Gray(1.0)) }; + write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))) + }; + assert!(file(32_765).is_ok()); + assert_eq!(file(32_766), Err(Error::Limit("table entry size"))); +} + +#[test] +fn a_contour_whose_area_sums_to_nothing_counts_as_either_turn() { + let p = |x, y| Pt { x, y }; + let tri = |pts: [Pt; 3]| SubPath { start: pts[0], segments: vec![Segment::Line(pts[1]), Segment::Line(pts[2])], closed: true }; + let (a, b, c) = (p(0.0, 0.0), p(100_000_000.0, 99_999_999.0), p(100_000_001.0, 100_000_000.0)); + let geometry = Geometry::Path(Path { subpaths: vec![tri([a, b, c]), tri([b, c, a])] }); + let m = Matrix([16.0, -299_999_997.0, -16.0, 300_000_000.0, 0.0, 0.0]); + let s = Shape { nonzero: true, ..Shape::new(geometry, m, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_cubic_looping_from_its_start_is_reported() { + let p = |x, y| Pt { x, y }; + let mut segments = vec![Segment::Cubic(p(-10.0, 0.0), p(150.0, -10.0), p(480.0, 480.0))]; + segments.extend([p(-1.0, 480.0), p(-1.0, -1.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_cubic_crossing_an_edge_between_its_flattened_points_is_reported() { + let p = |x, y| Pt { x, y }; + // The arch (16 t, 9 t (1 − t)) is flattened at whole x; at x = 7.5 its line is at y = 2.2324 + // and the arch at y = 2.2412. A notch down to `tip` stays clear of the line, and crosses the + // arch when the tip is below it. + let filled = |tip: f64| { + let mut segments = vec![Segment::Cubic(p(16.0 / 3.0, 3.0), p(32.0 / 3.0, 3.0), p(16.0, 0.0))]; + segments.extend([p(16.0, 6.0), p(7.5, tip), p(0.0, 6.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + write_cmx(&one_shape(s)).unwrap().nonzero_fills + }; + assert!(filled(2.237)); + assert!(!filled(2.3)); +} + +#[test] +fn a_cubic_crossing_the_next_edge_near_their_shared_point_is_reported() { + let p = |x: f64, y: f64| Pt { x: x * 1000.0, y: y * 1000.0 }; + // The arch (16 t, 9 t (1 − t)) ends at (16, 0) heading back at a slope of 9/16, and the line + // from there to (0, 8.8) leaves at a slope of 0.55: the arch starts above the line and crosses + // it. The arch's last flattened piece, at a slope of 0.527, stays below the line. + let segments = vec![Segment::Cubic(p(16.0 / 3.0, 3.0), p(32.0 / 3.0, 3.0), p(16.0, 0.0)), Segment::Line(p(0.0, 8.8))]; + let arch = SubPath { start: p(0.0, 0.0), segments, closed: true }; + // A clockwise square apart from it. + let square = SubPath { start: p(20.0, 0.0), segments: [p(20.0, 1.0), p(21.0, 1.0), p(21.0, 0.0)].map(Segment::Line).to_vec(), closed: true }; + let geometry = Geometry::Path(Path { subpaths: vec![arch, square] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A square whose bottom edge is a straight cubic that eases in and out, so its first and last + // flattened pieces are short beside the lines next to them, crosses nothing. + let eased = vec![Segment::Cubic(p(0.0, 0.0), p(10.0, 0.0), p(10.0, 0.0)), Segment::Line(p(10.0, 10.0)), Segment::Line(p(0.0, 10.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments: eased, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A crescent: two arcs that leave each tip along the same tangent and part at once. + let arcs = vec![Segment::Cubic(p(2.0, 4.0), p(8.0, 4.0), p(10.0, 0.0)), Segment::Cubic(p(9.0, 2.0), p(1.0, 2.0), p(0.0, 0.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments: arcs, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_blank_layer_name_before_a_nul_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("\u{2003}\0", vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn marks_too_short_to_store_stay_visible() { + let o = Outline { dashes: vec![0.4, 2.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![1.0, 2.0]); +} + +#[test] +fn a_spot_color_without_a_look_takes_the_look_of_its_ink() { + let ink = |look| Color::Spot { name: "Ink".into(), tint: 1.0, look }; + let shapes = + [ink(None), ink(Some([1.0, 0.0, 0.0]))].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])); + for o in &back.pages[0].layers[0].objects { + assert!(near_color(shape(o).fill.as_ref().unwrap(), &ink(Some([1.0, 0.0, 0.0]))), "{:?}", shape(o).fill); + } +} + +#[test] +fn art_on_a_desktop_layer_is_reported() { + let art = vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))]; + let desktop = Layer { kind: LayerKind::Desktop, ..layer("Desktop", art) }; + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![desktop] }])).unwrap(); + assert!(w.left_out); + assert_eq!(read_cmx(&w.bytes, Limits::default()).unwrap().pages[0].layers[0].objects.len(), 1, "the art is kept"); +} + +#[test] +fn dashes_too_short_to_store_are_reported() { + let o = Outline { dashes: vec![0.0, 0.000_000_5], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn a_spot_color_with_no_name_is_reported() { + let unnamed = Color::Spot { name: String::new(), tint: 0.5, look: Some([0.0, 0.0, 1.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(unnamed), None))).unwrap(); + assert!(w.unnamed_spots && !w.zero_tints); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let fill = shape(&back.pages[0].layers[0].objects[0]).fill.clone().unwrap(); + assert!(near_color(&fill, &Color::Rgb([0.5, 0.5, 1.0])), "{fill:?}"); +} + +#[test] +fn a_layer_name_keeps_its_windows_1252_characters_in_the_8_bit_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("€ ‰ 中", vec![plain])] }])).unwrap().bytes; + // The 8-bit name: a u16 count, then the bytes. + let narrow = [5u8, 0, 0x80, b' ', 0x89, b' ', b'?']; + assert!(bytes.windows(narrow.len()).any(|w| w == narrow), "the euro and per-mille signs have bytes; the last character has none"); +} + +#[test] +fn more_layers_than_the_layer_number_holds_are_refused() { + let layers = (0..=usize::from(u16::MAX)).map(|_| layer("", Vec::new())).collect(); + assert_eq!(write_cmx(&drawing(vec![Page { size: None, layers }])), Err(Error::Limit("layers"))); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + /// Paths of lines and curves read back with every point within a coordinate unit. + #[test] + fn paths_read_back_point_for_point( + pts in prop::collection::vec((-1.0e5f64..1.0e5, -1.0e5f64..1.0e5), 4..60), + closed in any::(), + curves in any::(), + ) { + let p = |(x, y): (f64, f64)| Pt { x, y }; + let start = p(pts[0]); + let segments: Vec = if curves { + pts[1..].as_chunks::<3>().0.iter().map(|[a, b, c]| Segment::Cubic(p(*a), p(*b), p(*c))).collect() + } else { + pts[1..].iter().map(|q| Segment::Line(p(*q))).collect() + }; + prop_assume!(!segments.is_empty()); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start, segments, closed }] }); + let s = Shape::new(geometry.clone(), Matrix::IDENTITY, Some(Color::Rgb([0.5, 0.5, 0.5])), None); + let d = drawing(vec![Page { size: Some((612.0, 792.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let back = round_trip(&d); + let read = &shape(&back.pages[0].layers[0].objects[0]).geometry; + let Geometry::Path(path) = read else { panic!() }; + prop_assert_eq!(path.subpaths[0].closed, closed); + let (want, got) = (points(&geometry), points(read)); + prop_assert_eq!(got.len(), want.len()); + for (a, b) in want.iter().zip(&got) { + prop_assert!(near(a.x, b.x) && near(a.y, b.y), "{:?} {:?}", a, b); + } + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs index 23419e0936..6057491186 100644 --- a/crates/cdr/tests/it/main.rs +++ b/crates/cdr/tests/it/main.rs @@ -4,6 +4,7 @@ mod bench; mod cmx; +mod cmx_write; mod provenance; mod read; mod write; diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index 8a1426be37..03b6257ed8 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -282,6 +282,58 @@ fn a_late_reply_from_before_sign_out_is_dropped() { ); } +/// File › Open calls `start` on every frame. A sign-out has no answer, so nothing orders it +/// before a request the next frame sends. A provider that still holds the session answers that +/// request with the departed account, and the window must not show that account or its files. +#[test] +fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() { + let (mut app, held, _log) = two_tabs(); + start(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap(); + post.send(Event::Account(Ok(account("Previous Person")))); + held.take(|j| matches!(j, Job::List(_))).unwrap(); + drain(&mut app, &egui::Context::default()); + sign_out(&mut app); + start(&mut app); + // Whatever the frame asked is answered as a provider that has not yet ended the session would. + while let Some((job, post)) = held.take(|j| matches!(j, Job::Account | Job::List(_))) { + match job { + Job::Account => post.send(Event::Account(Ok(account("Previous Person")))), + Job::List(path) => post.send(Event::Listed { path, entries: Ok(vec![entry("/Payroll 2026.note", "p1")]) }), + _ => {} + } + } + drain(&mut app, &egui::Context::default()); + let r = report(&app); + assert!( + r["account"].is_null() && r["entries"].as_array().is_some_and(Vec::is_empty), + "signed out, yet account={} entries={}", + r["account"], + r["entries"] + ); + sign_in(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::SignIn)).unwrap(); + post.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + start(&mut app); + assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again"); +} + +/// Save As while signed out has no account to land in. A provider that has not ended the session +/// yet would create the file in the account that is leaving. +#[test] +fn save_as_after_sign_out_is_refused_until_the_next_sign_in() { + let (mut app, held, _log) = two_tabs(); + start(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap(); + post.send(Event::Account(Ok(account("Previous Person")))); + drain(&mut app, &egui::Context::default()); + sign_out(&mut app); + let refused = save_as(&mut app, "", "Plan"); + assert!(refused.is_err(), "signed out, yet Save As went ahead: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none(), "nothing is created while signed out"); +} + /// Save as a copy, then the first click on the Save As page is refused (no name typed yet). The /// second click, with a name, must still copy the conflicted document A, not the active tab B. #[test] diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index fb3f0a5541..b99ea2f612 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -191,6 +191,11 @@ pub struct CloudFiles { pub account_fault: Option, /// The account is asked for once per run. A frame never asks again. asked_account: bool, + /// Set by [`sign_out`] and cleared by [`sign_in`]. While it is set, the + /// pages ask the service nothing. [`Job::SignOut`] has no answer and no + /// order against a later job, so a provider that still holds the session + /// could answer an account or listing request with the departed account. + signed_out: bool, /// The folder being browsed. Shared by the Open and Save As pages, which /// are never on screen together. pub mine: Folder, @@ -249,6 +254,7 @@ impl CloudFiles { account: None, account_fault: None, asked_account: false, + signed_out: false, mine: Folder::default(), shared: Folder::default(), source: Source::default(), @@ -344,8 +350,10 @@ pub fn submit(app: &A, job: Job) { } /// Asks who is signed in, once per run, and lists the root folder. +/// +/// After [`sign_out`] it asks nothing until the next [`sign_in`]. pub fn start(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().signed_out { return; } if !app.cloud().asked_account { @@ -375,6 +383,7 @@ pub fn sign_in(app: &mut A) { // would then be swallowed by the guard that stops a frame asking twice. A // button that does nothing the second time reads as a broken button. cloud.asked_account = true; + cloud.signed_out = false; cloud.link = None; cloud.status = Some(working); // A new session. A job the previous one left outstanding may never @@ -402,6 +411,10 @@ pub fn sign_out(app: &mut A) { cloud.account = None; cloud.account_fault = None; cloud.asked_account = false; + // File › Open and Save As call `start` on every frame. Without this, the + // next frame would ask who is signed in and list the root folder while + // the sign-out may still be on its way. + cloud.signed_out = true; cloud.link = None; cloud.mine = Folder::default(); cloud.shared = Folder::default(); @@ -413,8 +426,13 @@ pub fn sign_out(app: &mut A) { // that never heard back does not refuse every one after it forever. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.sharing_save = false; cloud.relist_after_sign_in = false; cloud.save_as_target = None; + // Sharing went with the account: Share is not offered on the old + // account's answer, and a sheet open on one of its documents closes. The + // next sign-in asks the provider again. + app.sharing().signed_out(); submit(app, Job::SignOut); } @@ -630,6 +648,9 @@ pub fn save_as(app: &mut A, folder: &str, name: &str) -> Result(app: &mut A, ui: &mut Ui) { let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() }; dim(ui, &style, &line); } + // Nothing is asked after a sign-out, so there is nothing to wait for. + (None, None) if app.cloud().signed_out => { + let signed_out = app.tr("Signed out"); + dim(ui, &style, &signed_out); + } (None, None) => { let waiting = app.tr("Connecting to your cloud account…"); dim(ui, &style, &waiting); diff --git a/crates/cloud-ui/src/cloud/tests.rs b/crates/cloud-ui/src/cloud/tests.rs index 82f818db01..951535eda2 100644 --- a/crates/cloud-ui/src/cloud/tests.rs +++ b/crates/cloud-ui/src/cloud/tests.rs @@ -435,6 +435,49 @@ fn signing_out_forgets_everything_this_window_knew() { assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too"); } +/// A sharing service that says it can share and answers nothing else. +struct Shares; + +impl crate::share::ShareBackend for Shares { + fn submit(&self, request: crate::share::Request, reply: crate::share::Replier) { + if request == crate::share::Request::Capabilities { + reply.answer(crate::share::Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: true }); + } + } +} + +#[test] +fn signing_out_takes_sharing_with_it() { + let (mut app, _jobs, ctx) = wired(); + app.share.connect(Shares); + // Enough frames for an account answer to land, the provider to be asked, + // and its answer to be read. + let frames = |app: &mut Notebook| { + for _ in 0..3 { + ctx.begin_pass(Default::default()); + app.share.show(&ctx); + pump(app, &ctx); + ctx.end_pass().textures_delta.clear(); + } + }; + frames(&mut app); + assert!(app.share.available()); + app.share.open("/Minutes.note", "Minutes"); + assert!(app.share.is_open()); + + sign_out(&mut app); + assert!(!app.share.is_open(), "a sheet open on the old account's document closes"); + assert!(!app.share.available(), "Share is not offered on the old account's answer"); + // The provider is not asked again while the sign-out may still be on its + // way, so a service that still has the old account cannot offer it back. + frames(&mut app); + assert!(!app.share.available(), "nobody is signed in"); + + sign_in(&mut app); + frames(&mut app); + assert!(app.share.available(), "the next sign-in asks again"); +} + #[test] fn an_answer_queued_before_the_session_changed_is_dropped() { let (mut app, _jobs, ctx) = wired(); diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index b4739909fc..9d03472e50 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -338,6 +338,10 @@ pub struct ShareDialog { provider: Option, /// When the capability question was last asked. asked: Option, + /// The last request number issued before the latest [`ShareDialog::refresh`] + /// or [`ShareDialog::connect`]. A capabilities answer to that request or an + /// earlier one describes the account as it was, and is ignored. + capabilities_after: u64, open: Option, /// Keyed by the URL the contact carried, so reopening the dialog does not /// fetch the same faces again. @@ -370,6 +374,7 @@ impl ShareDialog { seq: 0, provider: None, asked: None, + capabilities_after: 0, open: None, avatars: HashMap::new(), wants_save: None, @@ -387,6 +392,7 @@ impl ShareDialog { self.backend = Some(Box::new(backend)); self.provider = None; self.asked = None; + self.capabilities_after = self.seq; } pub fn connected(&self) -> bool { @@ -413,10 +419,25 @@ impl ShareDialog { /// The answer is kept once it arrives, so a host that signs somebody /// in after the first answer has to say so. Without this the dialog /// keeps the answer it got while nobody was signed in, and Share - /// stays unavailable for the rest of the run. + /// stays unavailable for the rest of the run. An answer to a question + /// asked before the refresh is ignored when it arrives. pub fn refresh(&mut self) { self.provider = None; self.asked = None; + self.capabilities_after = self.seq; + } + + /// Forget sharing for an account that signed out. + /// + /// Closes the sheet and offers nothing until [`ShareDialog::refresh`], + /// which the next sign-in calls. The provider is not asked again here: a + /// question asked before the sign-out reaches the service would describe + /// the account that is leaving. Answers to earlier questions are ignored. + pub fn signed_out(&mut self) { + self.close(); + self.provider = Some(Provider { sharing: false, contacts: false, mail: false, links: false, key: false, key_required: false }); + self.asked = None; + self.capabilities_after = self.seq; } pub fn available(&self) -> bool { @@ -639,6 +660,8 @@ impl ShareDialog { // once the open sheet is no longer borrowed. let mut reload = None; match answer { + // Asked before the account changed: it describes the old one. + Answer::Capabilities { .. } if seq <= self.capabilities_after => {} Answer::Capabilities { capabilities, linked } => { self.provider = Some(Provider { sharing: linked && capabilities.contains(&Capability::Sharing), @@ -717,13 +740,16 @@ impl ShareDialog { } } Answer::Linked => { - // An account arrived, so the list is stale. - if let Some(sheet) = &mut self.open { - sheet.destinations = None; - } - let seq = self.issue(Request::Destinations); - if let Some(sheet) = &mut self.open { - sheet.destinations_seq = Some(seq); + // An account arrived, so the list is stale. With no sheet open + // there is no list to reload. + if self.open.is_some() { + if let Some(sheet) = &mut self.open { + sheet.destinations = None; + } + let seq = self.issue(Request::Destinations); + if let Some(sheet) = &mut self.open { + sheet.destinations_seq = Some(seq); + } } } Answer::Withdrawn { share_id } => { diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index eba1a23551..283ce0274b 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -113,6 +113,24 @@ fn nothing_is_offered_until_the_service_says_sharing_exists() { assert!(dialog.is_open()); } +#[test] +fn a_capabilities_answer_asked_before_a_refresh_is_ignored() { + let ctx = Context::default(); + let backend = Silent::default(); + let mut dialog = ShareDialog::new(); + dialog.connect(backend.clone()); + dialog.collect(&ctx); + dialog.refresh(); + dialog.collect(&ctx); + assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Capabilities], "the refresh asks again"); + + // The first question was about the account before the refresh. + dialog.receive(&ctx, 1, Ok(everything())); + assert!(!dialog.available(), "the old account's answer must not offer Share"); + dialog.receive(&ctx, 2, Ok(everything())); + assert!(dialog.available()); +} + #[test] fn an_unlinked_account_cannot_share_even_where_the_provider_can() { let ctx = Context::default(); @@ -580,6 +598,15 @@ fn a_closed_dialog_still_collects_and_reports_nothing() { assert!(shared.is_empty() && failed.is_empty()); } +#[test] +fn a_link_answer_arriving_with_no_sheet_open_asks_for_nothing() { + let (ctx, mut dialog, backend) = ready(); + dialog.signed_out(); + let before = backend.seen().len(); + dialog.receive(&ctx, 99, Ok(Answer::Linked)); + assert_eq!(backend.seen().len(), before); +} + #[test] fn pressing_return_takes_the_first_match_or_an_address() { let (_ctx, mut dialog, _) = ready(); diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 2d4864a990..90b7bee271 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -10,9 +10,8 @@ fn opts() -> TransformOptions { TransformOptions::default() } -/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it. -fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 { - let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap(); +/// L* of a CMYK colour, measured by the prebuilt transform. +fn lightness(t: &Transform, cmyk: [f32; 4]) -> f32 { let mut lab = [0.0f32; 3]; t.eval(&cmyk, &mut lab).unwrap(); lab[0] * 100.0 @@ -70,18 +69,22 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; + let coated_lab = Transform::with_options(coated(), Builtin::LabD50.profile(), o).unwrap(); + let fogra_lab = Transform::with_options(fogra(), Builtin::LabD50.profile(), o).unwrap(); // Both directions for one setting; the other settings in the forward one. let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { + for (src, dst, src_lab, dst_lab) in + [(coated(), fogra(), &coated_lab, &fogra_lab), (fogra(), coated(), &fogra_lab, &coated_lab)].into_iter().take(directions) + { let bp = BlackPreserving::new(src, dst, o).unwrap(); - let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); + let dst_black = lightness(dst_lab, [0.0, 0.0, 0.0, 1.0]); for k in [0.1f32, 0.5, 0.9, 1.0] { - let want = lightness(src, o, [0.0, 0.0, 0.0, k]); + let want = lightness(src_lab, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); continue; } - let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]); + let got = lightness(dst_lab, [0.0, 0.0, 0.0, bp.map_k(k)]); assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}"); } assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper"); diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 1705f64002..c026896980 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -901,7 +901,7 @@ mod tests { #[test] fn oklab_profile_has_three_tables() { - let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; + let p = CmykParams { grid_a2b: 3, grid_b2a: 3, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; let profile = cmyk_profile(&p).unwrap(); let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") }; assert!(b0 != b1 && b0 != b2, "perceptual shares a table"); diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index 9c81d3d68b..a38b1f9827 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -7,3 +7,8 @@ Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, sample Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`). The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`. + +`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components, +even when the host renders the colour through a different working-space transform. Current host components take +precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening +colour, including its display colour, alpha and native components. diff --git a/crates/color-ui/src/ui/choice.rs b/crates/color-ui/src/ui/choice.rs index 0cd393e88e..0af3dfc6ec 100644 --- a/crates/color-ui/src/ui/choice.rs +++ b/crates/color-ui/src/ui/choice.rs @@ -59,7 +59,7 @@ pub enum ChosenColor { pub struct ColorChoiceOutput { /// The choice's response. pub response: Response, - /// The row chosen this pass; the host stores it. + /// The row committed this pass; the host stores it. Navigating an open popup reports no choice. pub chosen: Option, /// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key /// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses @@ -151,7 +151,7 @@ impl<'a> ColorChoice<'a> { entries.push(Entry::separator()); entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned())); let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui); - let picked = shown.value().cloned(); + let picked = shown.events.committed().cloned(); let mut pick_color = None; let chosen = match picked { Some(Row::Named(id)) => Some(ChosenColor::Named(id)), diff --git a/crates/color-ui/src/ui/eyedropper.rs b/crates/color-ui/src/ui/eyedropper.rs index 9a238c2863..4e17c7b572 100644 --- a/crates/color-ui/src/ui/eyedropper.rs +++ b/crates/color-ui/src/ui/eyedropper.rs @@ -61,7 +61,7 @@ craft_ui::words! { } /// How many pixels around the pointer the eyedropper averages: Photoshop's Sample Size list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSize { @@ -115,7 +115,7 @@ impl SampleSize { } /// Which layers the eyedropper reads: Photoshop's Sample list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSource { @@ -172,7 +172,7 @@ impl SampleSource { } /// The Eyedropper's options bar values. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct EyedropperOptions { diff --git a/crates/color-ui/src/ui/gradient/editor/bar.rs b/crates/color-ui/src/ui/gradient/editor/bar.rs index ba55ee2823..394dcdfeab 100644 --- a/crates/color-ui/src/ui/gradient/editor/bar.rs +++ b/crates/color-ui/src/ui/gradient/editor/bar.rs @@ -845,7 +845,7 @@ impl Component for GradientBar<'_, P> { let edge_of = |m: StopRef| { if self.selected_marker == Some(m) { style.selected - } else if !dragging && cx.hover_pos(part_of(m)).is_some() { + } else if !dragging && cx.part_if_declared(part_of(m)).is_some_and(|result| result.hovered) { style.hovered } else { cx.resolve(&style.edge) diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index a153276ada..254d30f628 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> { Variation::WarmCool => (&words.cool, &words.warm), Variation::VividMuted => (&words.muted, &words.vivid), }; - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(left.clone()).show(ui); Text::new(right.clone()).show(ui); }); diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index 28de7cc7b1..64213ce9a8 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter; use craft_keymap::Mods; use craft_theme::Srgba; use craft_ui::buttons::{Button, PopupMark}; -use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring}; +use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band}; use craft_ui::contract::{ Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, @@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra if style.ring { let ground = ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) }); - ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground); + ui.draw().surface_styled(well.shrink(ring_band(well)), &ground); } else { ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge); } diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 8cb8cda739..5504a5a901 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -440,8 +440,13 @@ impl Component for SwatchPair<'_, P> { flags.set(Flags::MIXED, self.wells[i].paint.same().is_none()); flags.set(Flags::CHECKED, well == active); let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) }; - let part = - cx.part(WELL.at(i as u64), shape).sense(sense).priority(HitPriority::new(HitLevel::Body, u8::from(front))).flags(flags).focusable(); + let part = cx + .part(WELL.at(i as u64), shape) + .sense(sense) + .priority(HitPriority::new(HitLevel::Body, u8::from(front))) + .flags(flags) + .focusable() + .tooltip(self.wells[i].label.clone()); // Focus arrives at the active well, so arriving makes no other well active. let part = if well == active { part.selected() } else { part }; if self.popover { @@ -449,10 +454,10 @@ impl Component for SwatchPair<'_, P> { } } let buttons = self.button_rects(cx.style); - for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] { - if shown { + for (key, button, name) in [(DEFAULT, buttons[0], &self.default_button), (SWAP, buttons[1], &self.swap_button)] { + if let Some(name) = name { let at = flow.to_physical(button.translate(rect.min.to_vec2())); - cx.part(key, at).sense(Sense::CLICK).pointer_only("The host's Default Colours and Swap Colours commands"); + cx.part(key, at).sense(Sense::CLICK).tooltip(name.clone()).pointer_only("The host's Default Colours and Swap Colours commands"); } } cx.roving(Roving::new(NavShape::Flat)); diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index 000e8ca818..b5d35ac5c0 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -3,15 +3,15 @@ use craft_behavior::{EditEvent, IconId, Mixed, Selection}; use craft_theme::Srgba; -use craft_ui::choice::{SwatchSpacing, SwatchTable}; -use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _}; +use craft_ui::choice::{SwatchSpacing, SwatchTable, SwatchTableOutput}; +use craft_ui::contract::{ActivateOn, Bind, Held, LeadOnOpen, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _, SpaceAction}; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::Label; use craft_ui::runtime::memory::StageAccess; use craft_ui::runtime::requests::ColorRequest; use craft_ui::style::TypeRole; -use egui::{Response, Ui}; +use egui::{PointerButton, Response, Ui}; use std::sync::Arc; #[cfg(feature = "suite")] @@ -35,6 +35,9 @@ pub struct SwatchPaletteOutput { pub pick_color: Option, /// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`. pub picked: Option, + /// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour. + /// The recent row and the Other… cell do not report a swatch index. + pub picked_swatch: Option, } impl Outcome for SwatchPaletteOutput { @@ -65,6 +68,7 @@ pub struct SwatchPalette<'a> { label: Label, color: PaletteColor<'a>, swatches: &'a [(Label, Srgba)], + selected_swatch: Option, spacing: SwatchSpacing, drag: Option, /// The Other… cell: the key of its colour request and its name. @@ -109,7 +113,7 @@ impl PaletteColor<'_> { #[derive(Clone, Copy)] enum Pick { /// A swatch or a recent colour. - Color(Srgba), + Color { color: Srgba, swatch: Option }, /// The Other… cell. Other, } @@ -119,6 +123,15 @@ fn cell_of(swatches: &[(Label, Srgba)], color: Option) -> Selection Option { + table.open.or_else(|| { + table.selected.filter(|_| { + ui.input(|input| input.pointer.button_pressed(PointerButton::Secondary) || input.pointer.button_released(PointerButton::Secondary)) + }) + }) +} + impl<'a> SwatchPalette<'a> { /// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`. pub fn new(label: impl Into