diff --git a/.config/cargo-ci.toml b/.config/cargo-ci.toml new file mode 100644 index 0000000000..93a48332ff --- /dev/null +++ b/.config/cargo-ci.toml @@ -0,0 +1,37 @@ +# The Workspace gate's additions to .config/cargo-dev.toml (scripts/ci-workspace-tests.sh passes both). The gate runs +# every test of these crates, and their tests spend nearly all their time in sample and pixel loops, which run several +# times faster at opt-level 1; locally they stay at 0, so an edit to them rebuilds fast. craft-pdf (R6 hash and AES-CBC +# loops), craft-pkcs7 and craft-odf (PBKDF2 rounds, monomorphised in the crate) and craft-cms (CLUT builds) run their +# own hot loops in tests, so they take part too. +[profile.dev.package.craft-audio-dsp] +opt-level = 1 + +[profile.dev.package.craft-audio] +opt-level = 1 + +[profile.dev.package.craft-media] +opt-level = 1 + +[profile.dev.package.craft-image-codecs] +opt-level = 1 + +[profile.dev.package.craft-imaging] +opt-level = 1 + +[profile.dev.package.craft-pdf] +opt-level = 1 + +[profile.dev.package.craft-pkcs7] +opt-level = 1 + +[profile.dev.package.craft-odf] +opt-level = 1 + +[profile.dev.package.craft-cms] +opt-level = 1 + +# The runtime under every screen test: each frame of a fixture runs its pass, layout, focus and access tree. At +# opt-level 2 a suite trial runs about 40 percent fewer instructions than at 0 (Table activation 19.8 G to 11.9 G); +# opt-level 1 gives about 30 percent. Every UI crate waits for its compile, which grows by about a minute. +[profile.dev.package.craft-ui-contract] +opt-level = 2 diff --git a/.config/cargo-dev.toml b/.config/cargo-dev.toml new file mode 100644 index 0000000000..cec2fbc4fd --- /dev/null +++ b/.config/cargo-dev.toml @@ -0,0 +1,25 @@ +# The dev-build tuning every craft-libs test build uses: `tools/cl` passes it to each cargo command locally, and +# scripts/ci-workspace-tests.sh passes it (`--config .config/cargo-dev.toml`) to the Workspace gate's builds, so local +# and CI builds are the same. It lives here and not in Cargo.toml's `[profile]` table, which the CI cache key hashes; +# the per-crate levels Cargo.toml sets (craft-video, craft-affinity) still apply. +# +# lto off: with cargo's default, rustc runs thin-local LTO across every optimised crate's codegen units on each rebuild; +# off, a one-line edit re-optimises only the changed units. Dependencies build at opt-level 2, once per target dir and +# cache entry: egui, text shaping, hashing and codecs run in nearly every test. +# craft-theme, craft-behavior and craft-proof run in every screen-test frame or in dictionary-sized tests and are rarely +# edited, so they build at opt-level 1; every other workspace crate stays at 0, where rustc shares generic +# instantiations across crates and an edit to the runtime (craft-ui-contract) rebuilds in seconds. +[profile.dev] +lto = "off" + +[profile.dev.package."*"] +opt-level = 2 + +[profile.dev.package.craft-theme] +opt-level = 1 + +[profile.dev.package.craft-behavior] +opt-level = 1 + +[profile.dev.package.craft-proof] +opt-level = 1 diff --git a/.config/nextest.toml b/.config/nextest.toml index 0bc679e473..17eb6c07b6 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -26,11 +26,7 @@ print = { max-threads = 1 } video-integration = { max-threads = 1 } [[profile.default.overrides]] -filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))' -test-group = 'gpu' - -[[profile.default.overrides]] -filter = 'package(craft-video) & binary(h264_decode)' +filter = 'package(craft-video) & binary(it) & test(/^h264_decode::/)' test-group = 'video-fixtures' [[profile.default.overrides]] @@ -45,7 +41,6 @@ fail-fast = false slow-timeout = { period = "60s" } failure-output = "immediate-final" - # Linux and macOS (the resource audit in craft-libs#2058): every GPU consumer shares the one `gpu` # slot, and the craft-video integration binaries share their fixture directories. Conservative on # purpose: the in-process mutexes these tests rely on do not reach across nextest's processes. @@ -59,3 +54,30 @@ test-group = 'gpu' platform = 'cfg(unix)' filter = 'package(craft-video) & kind(test)' test-group = 'video-integration' + +# Slowest tests first (priority runs higher values earlier), so the longest ones start at the +# beginning of the run instead of holding the tail. Every test that took over 30 s in the gate's +# run on next (run 44318177438, Linux); the first tier is the one over 60 s. +[[profile.ci.overrides]] +filter = '(package(craft-media) & test(=mxf::tests::hostile::hostile_input_never_panics)) | (package(craft-table) & test(/CellGrid.*::drives$/)) | (package(craft-proto) & test(=imap::gmail_labels_tests::a_mailbox_claimed_huge_cant_fill_memory_with_flags))' +priority = 20 + +[[profile.ci.overrides]] +filter = ''' +(package(craft-design-lint) & test(=mapped_crates_have_no_findings)) +| (package(craft-ui-widgets) & test(/SwatchTable.*::activation$/)) +| (package(craft-table) & test(/CellGrid.*::activation$/)) +| (package(craft-pkcs7) & test(=crypto::new_digital_ids_are_self_signed_and_survive_a_p12_round_trip)) +| (package(craft-image-codecs) & test(=tiff_bands::a_blank_fax_page_wider_than_4096_px_passes_the_bomb_guard)) +| (package(craft-image-codecs) & test(=codecs::png::streamed_tests::streamed_rows_match_the_whole_image_encoder)) +| (package(craft-image-codecs) & test(=codecs::png::parallel_tests::the_parallel_encoder_gives_the_same_bytes_on_any_thread_count)) +| (package(craft-image-codecs) & test(=limits::highly_compressible_jpeg_and_gif_still_decode)) +| (package(craft-color-ui) & test(=integration::sampling::an_invalid_capture_ends_the_pick_with_a_status)) +| (package(craft-docx) & test(=read::chart::tests::hostile_radar_charts_never_panic)) +| (package(craft-drawingml) & test(=chart::chartex_tests::large_box_hierarchy_and_stacked_charts_take_linear_work)) +| (package(craft-audio) & test(=integration::flac_decode::hostile_input_is_an_error_not_a_panic)) +| (package(craft-docx) & test(=comment_save_cost::many_comments_save_without_quadratic_id_searches)) +| (package(craft-ui-widgets) & test(/menu::popup::Menu.*::activation$/)) +| (package(craft-scraft-format) & test(=b64::tests::size_cap_counts_the_partial_quartet)) +''' +priority = 10 diff --git a/.gitattributes b/.gitattributes index 0c35cf7c56..00c1fc2492 100644 --- a/.gitattributes +++ b/.gitattributes @@ -17,3 +17,16 @@ crates/fonts-build/tests/fixture/craft-fonts/fonts/**/OFL.txt -text # DXF drawing goldens assert exact writer bytes, including LF on every platform. crates/dxf/tests/data/drawing_*.dxf -text + +# The generated components index is compared byte for byte with the generator's LF output (craft-ui test +# components_index): a Windows checkout must not convert its line endings. +docs/components-index.md text eol=lf + +# The built-in size files are compared byte for byte with the writer's LF output (craft-theme sizes_tests), and the +# token dumps with the dump writer's (craft-theme dumps test): a Windows checkout must not convert their line endings. +crates/theme/sizes/*.json text eol=lf +crates/theme/tests/dumps/** text eol=lf + +# The facade's [features] table is compared with the table the craft features test writes, with LF (craft test +# integration::features): a Windows checkout must not convert its line endings. +crates/craft/Cargo.toml text eol=lf diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index bc20b8e392..01b258e23c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -33,6 +33,10 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/docs.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/rust-cache@v2.9.2' '.github/workflows/ecproj-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -65,7 +69,8 @@ workflows: '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - '.github/workflows/nightly.yml': [] + '.github/workflows/nightly.yml': + - 'step-security/harden-runner@v2.22.4' '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -81,6 +86,9 @@ workflows: - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' '.github/workflows/sonarcloud.yml': [] + '.github/workflows/theme.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' '.github/workflows/update.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -142,6 +150,11 @@ dependencies: commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' owner_id: 88700172 repo_id: 422287306 + 'step-security/rust-cache@v2.9.2': + ref: 'v2.9.2' + commit: 'sha1-8871c8ba063416da7c32246932ea6ae08700453e' + owner_id: 88700172 + repo_id: 822636713 'step-security/taiki-e-install-action@v2.87.32': ref: 'v2.87.32' commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index 2be123b233..6f5b34e892 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] + branches: [main, next] 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 6afdafc290..b8bcc8b8ea 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] + branches: [main, next] 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 5fd971c629..6063c4e4dc 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -2,7 +2,7 @@ name: Shared audio on: push: - branches: [main] + branches: [main, next] 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 c1737392da..b13dd82d14 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -3,7 +3,7 @@ name: Colour management on: workflow_dispatch: push: - branches: [main] + branches: [main, next] 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 466b6c05d7..3e9b430d67 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -2,7 +2,7 @@ name: Shared CRW on: push: - branches: [main] + branches: [main, next] 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,14 +52,23 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - name: Cache the CC0 sample files - uses: actions/cache@v6.1.0 + # Pull requests restore the entry main or next 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 + uses: actions/cache/restore@v6.1.0 with: path: ${{ runner.temp }}/crw-samples key: crw-samples-${{ hashFiles('crates/crw/tests/samples.json') }} - name: Fetch the pinned CC0 sample files (raw.pixls.us) run: python scripts/fetch-crw-samples.py "$RUNNER_TEMP/crw-samples" - - run: cargo test -p craft-crw --release --locked --test samples -- --nocapture + - name: Save the CC0 sample files + if: github.event_name != 'pull_request' && steps.samples.outputs.cache-hit != 'true' + uses: actions/cache/save@v6.1.0 + with: + path: ${{ runner.temp }}/crw-samples + key: ${{ steps.samples.outputs.cache-primary-key }} + - run: cargo test -p craft-crw --release --locked --lib -- integration::samples --nocapture env: CRAFT_CRW_SAMPLES: ${{ runner.temp }}/crw-samples CRAFT_CRW_REQUIRE_SAMPLES: "1" diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index 23def9feb0..f9ab8fe56e 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -3,7 +3,7 @@ name: Dialogs on: workflow_dispatch: push: - branches: [main] + branches: [main, next] 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 6275433817..00b8336db1 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -3,7 +3,7 @@ name: Craft documents on: workflow_dispatch: push: - branches: [main] + branches: [main, next] 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 new file mode 100644 index 0000000000..fc51a0da51 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,49 @@ +name: Docs + +# Builds the documentation of every workspace crate with warnings as errors, so a public item +# without a doc comment or a broken doc link fails, including crates no other workflow covers. + +on: + workflow_dispatch: + push: + branches: [main, next] + paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] + pull_request: + paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] + +permissions: + contents: read + +jobs: + docs: + timeout-minutes: 30 + name: Workspace docs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + with: + # The token isn't needed after checkout; cargo runs build scripts and proc macros from + # dependencies, so don't leave it in .git/config for that third-party code to read. + persist-credentials: false + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 + with: + toolchain: stable + components: clippy + # Pull requests restore the cache but never save one (a 1.1 GB entry per open PR otherwise). + - uses: step-security/rust-cache@v2.9.2 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} + # A lib build selects no dev-dependency, so craft-ui's `testing` stays off as in an app's + # build: warnings that show only without it fail here. + - name: Facade as an app builds it + run: cargo clippy -p craft --lib --locked --features ui,layers,color,draw,imaging -- -D warnings + - name: Docs (links and missing docs) + run: cargo doc --workspace --no-deps --locked --keep-going + env: + RUSTDOCFLAGS: -D warnings + # The crates whose features add public items document with every feature too; the + # per-crate workflows document the media, audio and video crates. + - name: Docs with all features + run: cargo doc -p craft-ui -p craft-ui-contract -p craft-ui-widgets -p craft-ui-panels -p craft-ui-canvas -p craft-ui-patterns -p craft-ui-shell -p craft-doc -p craft-pdf --all-features --no-deps --locked --keep-going + env: + RUSTDOCFLAGS: -D warnings diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index 048c897b3c..bec96fed5c 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] + branches: [main, next] 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 e655697b3d..fd599d207c 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] + branches: [main, next] 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 a40d96d9ca..37796f6816 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -2,7 +2,7 @@ name: Shared format crates on: push: - branches: [main] + branches: [main, next] paths: - "crates/xml/**" - "crates/mime/**" diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml index de64ad3ee4..7ee967c65b 100644 --- a/.github/workflows/house-rules.yml +++ b/.github/workflows/house-rules.yml @@ -2,7 +2,7 @@ name: House rules on: push: - branches: [main] + branches: [main, next] paths: - AGENTS.md - CLAUDE.md diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index 495af8b232..ebb27bafde 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -2,7 +2,7 @@ name: Shared JPEG on: push: - branches: [main] + branches: [main, next] 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 bd4ef280a3..bfce473788 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -2,10 +2,10 @@ name: Keymap on: push: - branches: [main] - paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] + branches: [main, next] + 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/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] + 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"] workflow_dispatch: permissions: @@ -46,14 +46,12 @@ jobs: toolchain: stable components: clippy - run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings - # `snapshot` covers `ui` and `egui` and compiles the dialog screenshots, which need a GPU - # to run, so the test steps leave them out. - - run: cargo clippy -p craft-keymap --all-targets --features snapshot --locked -- -D warnings - # Doctests run once, in the `ui` step. + - run: cargo clippy -p craft-keymap --all-targets --features egui --locked -- -D warnings + # Doctests run once, in the `egui` step. - name: Test core run: cargo test -p craft-keymap --no-default-features --lib --tests --locked - - name: Test egui dispatch and the shortcuts dialog - run: cargo test -p craft-keymap --features ui --locked + - name: Test egui dispatch + run: cargo test -p craft-keymap --features egui --locked wasm: timeout-minutes: 10 name: Keymap WASM @@ -70,4 +68,4 @@ jobs: with: toolchain: stable targets: wasm32-unknown-unknown - - run: cargo check -p craft-keymap --features ui --locked --target wasm32-unknown-unknown + - run: cargo check -p craft-keymap --features egui --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 1b5afaebdf..090ad84da9 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -2,7 +2,7 @@ name: Shared media on: push: - branches: [main] + branches: [main, next] 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"] @@ -46,6 +46,10 @@ jobs: - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features matroska -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features ogg -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features serde -- -D warnings + - name: Docs (links and missing docs) + run: cargo doc -p craft-media -p craft-media-testkit --all-features --no-deps --locked + env: + RUSTDOCFLAGS: -D warnings - run: cargo check -p craft-media --all-features --locked --target wasm32-unknown-unknown test: timeout-minutes: 15 diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index b12c8bcc6a..80b6678cd3 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -2,7 +2,7 @@ name: Menu on: push: - branches: [main] + branches: [main, next] 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 ed9d361279..5cc8032668 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -31,4 +31,32 @@ jobs: cache-paths: .test-inputs/photocraft/corpus cache-key: photocraft-corpus cache-key-files: scripts/ci-test-inputs.sh - command: cargo nextest run --workspace --all-features --locked --profile ci + # 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/pcraft-format.yml b/.github/workflows/pcraft-format.yml index 0e4feabc92..cefa5360c4 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] + branches: [main, next] 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 34c7ea0224..1550512ac5 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -2,7 +2,7 @@ name: Shared PDF on: push: - branches: [main] + branches: [main, next] 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"] @@ -48,7 +48,7 @@ jobs: python scripts/test-fetch-pdf-test-fonts.py python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" - - run: cargo test -p craft-pdf --all-features --locked --test unicode_writing --test upstream_compatibility --test upstream_reading + - run: cargo test -p craft-pdf --all-features --locked --lib -- integration::unicode_writing integration::upstream_compatibility - run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked backends: name: PDF vendored contracts diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index ea5edb8a56..0f5b869a4a 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -2,7 +2,7 @@ name: Proofing on: push: - branches: [main] + branches: [main, next] 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 new file mode 100644 index 0000000000..213a74b147 --- /dev/null +++ b/.github/workflows/theme.yml @@ -0,0 +1,43 @@ +name: Suite themes + +on: + workflow_dispatch: + push: + branches: [main, next] + 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'] + +permissions: + contents: read + +jobs: + theme: + timeout-minutes: 15 + name: Theme lint, tests, WASM + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + with: + # The token isn't needed after checkout; cargo runs build scripts and proc macros from + # dependencies, so don't leave it in .git/config for that third-party code to read. + persist-credentials: false + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 + with: + toolchain: stable + components: rustfmt, clippy + targets: wasm32-unknown-unknown + - run: cargo fmt -p craft-theme --check + - run: cargo clippy -p craft-theme --all-targets --all-features --locked -- -D warnings + - run: cargo clippy -p craft-theme --all-targets --locked -- -D warnings + - run: cargo test -p craft-theme --all-features --locked + - run: cargo check -p craft-theme --all-features --locked --target wasm32-unknown-unknown + - run: cargo check -p craft-ui --lib --locked + - run: cargo fmt -p craft-theme-store --check + - run: cargo clippy -p craft-theme-store --all-targets --all-features --locked -- -D warnings + - name: Docs (links and missing docs) + run: cargo doc -p craft-theme -p craft-theme-store --all-features --no-deps --locked + env: + RUSTDOCFLAGS: -D warnings + - run: cargo test -p craft-theme-store --all-features --locked + - run: cargo check -p craft-theme-store --all-features --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 96ab4d6ad2..0ea3b8c1bb 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -3,7 +3,7 @@ name: App updates on: workflow_dispatch: push: - branches: [main] + branches: [main, next] 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'] @@ -18,10 +18,10 @@ concurrency: cancel-in-progress: true # fmt, clippy and the tests with default and with all features run in the Workspace gate on every -# OS; this runs the egui feature alone. +# OS; this runs the ui feature alone. jobs: update: - name: Update with egui alone + name: Update with ui alone timeout-minutes: 15 runs-on: ubuntu-latest steps: @@ -38,5 +38,5 @@ jobs: with: toolchain: stable components: clippy - - run: cargo clippy -p craft-update --all-targets --locked --features egui -- -D warnings - - run: cargo test -p craft-update --locked --features egui -- --nocapture + - run: cargo clippy -p craft-update --all-targets --locked --features ui -- -D warnings + - run: cargo test -p craft-update --locked --features ui -- --nocapture diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index cd66615a50..0ca15636df 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] + branches: [main, next] 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 20afe0d700..03b59cc427 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -2,7 +2,7 @@ name: Shared video on: push: - branches: [main] + branches: [main, next] 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 f0f8e22da7..0ad01e28fd 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] + branches: [main, next] 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 dc0254850a..055303bc26 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] + branches: [main, next] 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 c13b1ac3fe..a534393fdc 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -3,7 +3,7 @@ name: Window decorations on: workflow_dispatch: push: - branches: [main] + branches: [main, next] paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] pull_request: paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] @@ -17,11 +17,11 @@ concurrency: group: window-${{ github.ref }} cancel-in-progress: true -# fmt, clippy and the tests with default and with all features (egui and restore together) run in -# the Workspace gate on every OS; this runs each feature alone. +# fmt, clippy and the tests with default and with all features run in the Workspace gate on every +# OS; this runs the ui feature alone. jobs: window: - name: Window with each feature alone + name: Window with ui alone timeout-minutes: 15 runs-on: ubuntu-latest steps: @@ -38,7 +38,5 @@ jobs: with: toolchain: stable components: clippy - - run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings - - run: cargo test -p craft-window --locked --features egui -- --nocapture - - run: cargo clippy -p craft-window --all-targets --locked --features restore -- -D warnings - - run: cargo test -p craft-window --locked --features restore -- --nocapture + - run: cargo clippy -p craft-window --all-targets --locked --features ui -- -D warnings + - run: cargo test -p craft-window --locked --features ui -- --nocapture diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 7fdd316f1d..5c802e799e 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -2,7 +2,7 @@ name: Workspace on: push: - branches: [main] + branches: [main, next] tags: ["v*"] pull_request: workflow_dispatch: @@ -16,19 +16,20 @@ permissions: contents: read concurrency: - # 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' }} + # 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' }} jobs: # Whether this run needs the macOS and Windows legs, and which tests every leg runs - # (craft-common-actions' select-platforms). On a pull request the macOS and Windows legs run only - # when it can change platform behaviour: a crate with platform cfg code or one that depends on - # it, the build setup, or a file outside the crates. The tests are those of the crates a change - # reaches: the crates that own a changed file, the crates whose Cargo.toml declares a read of it + # (craft-common-actions' select-platforms). A pull request runs the Linux legs only, unless it + # has the full-ci label (see native-platforms); every other event runs the macOS and Windows legs + # too. The tests are those of the crates a change reaches: the crates that own a changed file, + # the crates whose Cargo.toml declares a read of it # (`[package.metadata.craft] reads`, which this job checks is complete), and every crate that # depends on those. The build setup, a crate's own Cargo.toml or a file outside the crates other # than documentation runs every test; documentation alone runs none. The full-ci label runs @@ -41,6 +42,9 @@ jobs: platform: ${{ steps.select.outputs.platform }} tests: ${{ steps.select.outputs.tests }} filter: ${{ steps.select.outputs.filter }} + audit: ${{ steps.audit.outputs.audit }} + profile: ${{ steps.audit.outputs.profile }} + deps-profile: ${{ steps.audit.outputs.deps-profile }} steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -59,14 +63,54 @@ jobs: select-os: '["windows-latest","macos-latest"]' select-tests: true label: full-ci + # Whether the selection reaches a replay-audit crate, which runs the Linux leg as a build job + # and three test shards (see `native`), and the hash of the profile overrides every test build + # passes (scripts/ci-workspace-tests.sh), which names the Workspace legs' cache entries: + # rust-cache's key does not hash these files, and an entry built with other overrides would be + # rebuilt in full on every run. Other events than a pull request check out only these files. + # 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. + - uses: actions/checkout@v7.0.1 + if: github.event_name != 'pull_request' + with: + persist-credentials: false + sparse-checkout: | + scripts/ci-workspace-tests.sh + .config/cargo-*.toml + sparse-checkout-cone-mode: false + - id: audit + env: + CRAFT_TESTS: ${{ steps.select.outputs.tests }} + CRAFT_TEST_FILTER: ${{ steps.select.outputs.filter }} + CRAFT_TEST_SKIP: ${{ steps.select.outputs.skip }} + run: | + echo "audit=$(bash scripts/ci-workspace-tests.sh audit)" >> "$GITHUB_OUTPUT" + echo "profile=$(cat .config/cargo-dev.toml .config/cargo-ci.toml | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT" + # An assignment, so a failure stops the step (`bash -e`) instead of naming every entry `v2-`. + deps=$(python3 -I - <<'PY' + import hashlib, json, tomllib + kept = [] + for path in (".config/cargo-dev.toml", ".config/cargo-ci.toml"): + with open(path, "rb") as file: + dev = tomllib.load(file)["profile"]["dev"] + kept.append([dev, dev.pop("package", {}).get("*", {})]) + print(hashlib.sha256(json.dumps(kept, sort_keys=True).encode()).hexdigest()[:12]) + PY + ) + echo "deps-profile=$deps" >> "$GITHUB_OUTPUT" # 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. 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. 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. native: name: Workspace needs: platforms @@ -74,17 +118,16 @@ jobs: with: os: '["ubuntu-latest"]' cache-workspace-crates: true - cold-build: ${{ github.event.schedule == '17 0 * * *' }} + 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' }} lint-cache: false - # Vendored PDF/graphics backends are excluded from the workspace (Cargo.toml) and - # compile in scripts/test-pdf-backends.sh. The unreached-rs diff check would - # otherwise fail any edit under vendor/ as a file no workspace module reaches. + # 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. unreached-rs-allow: | **/fixtures/** - vendor/hayro*/** - vendor/krilla/** - vendor/linesweeper/** - vendor/vello_*/** + vendor/** + crates/pdf/read-only-contract/** timeout-minutes: &timeout 120 # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). tools: &tools cargo-nextest@0.9.150 @@ -124,34 +167,33 @@ jobs: fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - command: &command | - # The tests run once, with every feature, in parallel across test binaries; nextest skips - # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose - # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's - # first clippy run; the last command runs the crates whose tests check behaviour with a - # feature off, which an all-features build cannot reach. - # Every build is the whole workspace's, as on main; the filter narrows only the run. The - # doctests run for the whole workspace: `cargo test -p ` would resolve features - # over the selected crates only and rebuild the dependencies whose features differ. - if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 - fi - cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench - cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests + # A selection that reaches a replay-audit crate builds once in a `build` job, which writes + # three nextest archives and then runs the doctests; three shard legs run them in parallel: + # every selected test outside the replay audit's crates and craft-draw, those crates (run plainly, + # then the audit crates with the audit), and craft-image-codecs with default features. Any other selection + # (and every macOS and Windows leg) builds and runs in one leg. scripts/ci-workspace-tests.sh + # holds every step. + test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }} + shard-archives: ${{ needs.platforms.outputs.audit == 'true' }} + archive-command: ${{ needs.platforms.outputs.audit == 'true' && 'bash scripts/ci-workspace-tests.sh archive' || '' }} + after-archive-command: bash scripts/ci-workspace-tests.sh doctest + shard-command: bash scripts/ci-workspace-tests.sh shard + command: &command bash scripts/ci-workspace-tests.sh run - # The macOS and Windows legs, when `platforms` says this run needs them, with the Linux leg's - # inputs. + # 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. + # A pull request that needs them before it merges gets the full-ci label. native-platforms: name: Workspace needs: platforms - if: needs.platforms.outputs.platform == 'true' + if: needs.platforms.outputs.platform == 'true' && (github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'full-ci')) uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: os: '["windows-latest","macos-latest"]' lint-cache: false + # Named by the dependency settings alone (`deps-profile`), so next restores main's entries. + cache-version: v2-${{ needs.platforms.outputs.deps-profile }} timeout-minutes: *timeout tools: *tools craft-fonts-ref: *craft-fonts @@ -169,25 +211,16 @@ jobs: cache-key-files: *cache-key-files lint-command: *lint command: *command - windows-command: | - if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 - fi - powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench - cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - # 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. + # 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. cache-prune: name: cache prune needs: native - if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -201,10 +234,11 @@ 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 refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref "$REF" --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/.gitignore b/.gitignore index 3c25188721..7583fcbc21 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ target/ /.claude/ .idea/ /vendor/*/target +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index ff4606fd5f..2fd1513b85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,7 +65,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 Shared Rust libraries for the Craft Apps: a Cargo workspace (edition 2024, resolver 3) of crates under `crates/`. See `README.md` for layout and released versions. -- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true`. +- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true` (`crates/font-os-windows` is the one exception; see `unsafe` below). - **No app code.** A crate here is useful to more than one app and does not depend on any app. -- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, and no crate in `crates/` allows it, so no module here may use `unsafe`. The one exception is vendored upstream code in `vendor/hayro-syntax`. +- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, so no module here may use `unsafe`, with two exceptions: vendored upstream code in `vendor/hayro-syntax`, and `crates/font-os-windows`, because loading a font into the running Windows session needs `AddFontResourceW`, which the Windows crates offer only as an unsafe call. That crate copies the workspace lints with `unsafe_code = "deny"` instead of `[lints] workspace = true`, and allows `unsafe` only on the functions that make Win32 calls. - **Checks for the crates you changed:** `cargo fmt --check`, `cargo clippy -p --all-targets -- -D warnings`, `cargo test -p `. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f1c183aea4..34e0bcd6f3 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,6 +19,8 @@ author, source and license. Library code and original assets are under the repos | `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) | | `vendor/linesweeper/tests/regression/`, `vendor/linesweeper/proptest-regressions/`, the `.snap` files under `vendor/linesweeper/src/` and the path data in `vendor/linesweeper/benches/painted_dreams.rs` (all unmodified; hashes in `vendor/linesweeper/SOURCE.json`) | As published in the package, whose manifest names Joe Neeman as author and records no other source | [linesweeper 0.5.0](https://crates.io/crates/linesweeper/0.5.0) | MIT OR Apache-2.0 (the package's `license` field) | | `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 | +| `crates/i18n/data/numbers.postcard` | Unicode, Inc. (CLDR 48.2.1 decimal symbols, digits and plural rules); generated by `crates/i18n/data/generate.sh` with `icu4x-datagen` 2.3.0 | [CLDR 48.2.1](https://cldr.unicode.org/) | Unicode-3.0 | +| `crates/i18n/data/dates.postcard` | Unicode, Inc. (CLDR 48.2.1 Gregorian date and time patterns, month and weekday names, week data); generated by `crates/i18n/data/generate.sh` with `icu4x-datagen` 2.3.0 | [CLDR 48.2.1](https://cldr.unicode.org/) | Unicode-3.0 | | `crates/text/assets/hyphen/en-us.dic` | Grady Ward (Moby Hyphenator II), converted by DesignCraft | [Project Gutenberg eBook #3204](https://www.gutenberg.org/ebooks/3204) | Public domain | | `crates/proof/data/en-words.dic` | Grady Ward (Moby Hyphenator II word list); break points dropped by craft-proof contributors with `crates/proof/examples/en_words.rs` | [Project Gutenberg eBook #3204](https://www.gutenberg.org/ebooks/3204), via craft-i18n `language-data/en-us/en-us.dic` | Public domain | | `crates/proof/data/en-extra.txt` | WordCraft contributors (original list, no other dictionary copied) | craft-i18n `language-data/en-us/en-extra.txt` | MIT OR Apache-2.0 | @@ -27,15 +29,16 @@ author, source and license. Library code and original assets are under the repos | Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 | | `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | | `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) | -| `crates/ui/tests/fonts/NotoSansArabic-screens.ttf` (instance at weight 400 and width 100, subset to the screen test strings) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | -| `crates/ui/tests/fonts/NotoSansCJKsc-screens.otf` (subset to printable ASCII and the screen test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) | -| `crates/ui/tests/fonts/NotoSansThai-screens.ttf` (instance at weight 400 and width 100, subset to the screen test strings) | The Noto Project Authors | [google/fonts@8b0a1d0 `ofl/notosansthai`](https://github.com/google/fonts/tree/8b0a1d0f5983c89bc2b93f1b5fb55f9e252744b5/ofl/notosansthai), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansThai.txt`) | +| `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | | `crates/crw/tests/samples.json` (manifest only; the 11 raw files are not bundled, `scripts/fetch-crw-samples.py` downloads them outside the checkout) | The photographers who contributed each file to raw.pixls.us (Canon EOS D30, D60, 10D ×3, 300D ×2, Digital Rebel, PowerShot G1, G5, G6) | [raw.pixls.us](https://raw.pixls.us/), each file's `getfile.php` URL and SHA-256 in the manifest | CC0-1.0 (as published by raw.pixls.us for each file) | | `crates/crw/src/tables.rs`, `crates/crw/clean-room/logs/table_sel*.json` | craft-crw contributors (derived in LightCraft, 2026-10, by known-plaintext alignment of the sample files' entropy streams; `crates/crw/clean-room/02-crw-format.md`) | this repository | MIT OR Apache-2.0 | | `crates/crw/clean-room/logs/private-corpus.tsv` (file names, sizes and SHA-256 of the maintainer's own EOS D60 files; no image content) | craft-crw contributors (LightCraft derivation record) | this repository | MIT OR Apache-2.0 | | `crates/prc/src/acof/table.rs` (the rows of the PRC `Double` prefix-code table, reformatted as Rust tuples) | Kristof Ralovich (prc-rs); the table is defined by ISO 14739-1 | [ralovich/prc-rs@287b671](https://github.com/ralovich/prc-rs/blob/287b671bb5b31b05efb5ec1b98f7c359b9e4dd7d/src/double.rs), through [PdfCraft `crates/prc`](https://github.com/storytold/pdfcraft/tree/80e26e674d1aa33078e83c8139875047f3289eb6/crates/prc) | MIT (`licenses/prc-rs/LICENSE.txt`; the notice is also in the file header) | | `crates/math/tests/corpus/equations.tsv`, `crates/math/tests/corpus/latex.tsv` (unmodified) | shuff57 (equaSHion) | [storytold/craft-libs#29](https://github.com/storytold/craft-libs/pull/29) at `7a6ef6b9`, `corpus/` | MIT OR Apache-2.0 | | `crates/math/tests/corpus/omml/*.xml` (unmodified) | WordCraft and DeckCraft contributors, collected by shuff57 (equaSHion) | [storytold/craft-libs#29](https://github.com/storytold/craft-libs/pull/29) at `7a6ef6b9`, `corpus/omml/` | MIT OR Apache-2.0 | +| `crates/font-subset/tests/data/{abeezee,abel,bbhbartle,librefranklin,orbitron,sarabun}/` (unmodified; each with its `OFL.txt`) | The ABeeZee, Abel, BBH, Libre Franklin, Orbitron and Sarabun Project Authors | [google/fonts@e7db6ca `ofl/`](https://github.com/google/fonts/tree/e7db6ca/ofl) | OFL-1.1 | +| `crates/font-subset/tests/data/ubuntu/Ubuntu-Regular.ttf` (unmodified; with `LICENCE.txt`) | Canonical Ltd. (Dalton Maag) | [google/fonts@e7db6ca `ufl/ubuntu`](https://github.com/google/fonts/tree/e7db6ca/ufl/ubuntu) | Ubuntu-font-1.0 | +| `crates/font-subset/tests/data/notosanscjk/NotoSansCJKsc-test.otf` (subset to the test strings; with `OFL.txt`) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via storytold/font-preview-service | OFL-1.1 | Original assets are covered by the repository licence. diff --git a/Cargo.lock b/Cargo.lock index a7e2b62777..7ce18795f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,8 +32,6 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" dependencies = [ - "enumn", - "serde", "uuid", ] @@ -226,6 +224,66 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -249,6 +307,27 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + [[package]] name = "arg_enum_proc_macro" version = "0.3.4" @@ -408,7 +487,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -439,7 +518,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -465,7 +544,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -603,6 +682,25 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -737,6 +835,12 @@ dependencies = [ "cpufeatures 0.3.1", ] +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + [[package]] name = "block-buffer" version = "0.10.4" @@ -985,6 +1089,16 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "calloop" version = "0.13.0" @@ -1079,7 +1193,7 @@ dependencies = [ "io-lifetimes 3.0.1", "ipnet", "maybe-owned", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-linux-procfs", "windows-sys 0.61.2", "winx", @@ -1094,7 +1208,7 @@ dependencies = [ "cap-primitives", "io-extras", "io-lifetimes 3.0.1", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1139,7 +1253,16 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", ] [[package]] @@ -1162,6 +1285,16 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -1239,6 +1372,66 @@ dependencies = [ "inout 0.2.6", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + [[package]] name = "cmac" version = "0.7.2" @@ -1337,14 +1530,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] -name = "colored" -version = "2.2.0" +name = "colorchoice" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" -dependencies = [ - "lazy_static", - "windows-sys 0.59.0", -] +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "combine" @@ -1418,6 +1607,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "cookie_store" version = "0.22.1" @@ -1486,6 +1681,19 @@ dependencies = [ "libc", ] +[[package]] +name = "core-graphics2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" +dependencies = [ + "bitflags 2.13.2", + "block", + "cfg-if", + "core-foundation 0.10.1", + "libc", +] + [[package]] name = "core_detect" version = "1.0.0" @@ -1525,6 +1733,229 @@ dependencies = [ "libc", ] +[[package]] +name = "craft" +version = "0.1.0" +dependencies = [ + "craft-aaf", + "craft-aep", + "craft-affinity", + "craft-ai", + "craft-ai-core", + "craft-android-res", + "craft-anicraft-format", + "craft-assuan", + "craft-atomic", + "craft-audio", + "craft-audio-dsp", + "craft-automation", + "craft-behavior", + "craft-ber", + "craft-browse", + "craft-captions", + "craft-cdr", + "craft-cfb", + "craft-cloud", + "craft-cloud-local", + "craft-cloud-ui", + "craft-cms", + "craft-codepage", + "craft-color", + "craft-color-transform", + "craft-color-ui", + "craft-control", + "craft-control-protocol", + "craft-crs", + "craft-crw", + "craft-csv", + "craft-dav", + "craft-dds", + "craft-deckcraft-format", + "craft-designcraft-format", + "craft-develop", + "craft-develop-model", + "craft-dex", + "craft-dialogs", + "craft-doc", + "craft-doc-binary", + "craft-docpath", + "craft-document-bundle", + "craft-docx", + "craft-dpx", + "craft-draw", + "craft-drawingml", + "craft-dwg", + "craft-dxf", + "craft-ecproj-format", + "craft-elf", + "craft-eps", + "craft-epub", + "craft-esign", + "craft-evm", + "craft-ews", + "craft-exr", + "craft-fcproj-format", + "craft-fig", + "craft-figcraft-format", + "craft-figma-rest", + "craft-file-formats", + "craft-file-import", + "craft-flags", + "craft-flow", + "craft-font-catalog", + "craft-font-manager", + "craft-font-os-windows", + "craft-font-store", + "craft-font-subset", + "craft-format", + "craft-frame", + "craft-gainmap", + "craft-gcode", + "craft-geom", + "craft-gif", + "craft-gpu", + "craft-gpu-null", + "craft-gpu-providers", + "craft-gpu-wgpu", + "craft-gridcraft-format", + "craft-gzip", + "craft-har", + "craft-hdr", + "craft-heif", + "craft-host", + "craft-html", + "craft-http-url", + "craft-i18n", + "craft-ical", + "craft-idml", + "craft-image-codecs", + "craft-imaging", + "craft-indd", + "craft-ipc", + "craft-ipp", + "craft-java-class", + "craft-jmap", + "craft-jpeg", + "craft-jsonc", + "craft-jsonrpc", + "craft-jxl", + "craft-keymap", + "craft-kiwi", + "craft-kra", + "craft-latex", + "craft-layers", + "craft-lottie", + "craft-macho", + "craft-markdown", + "craft-material-graph", + "craft-materialx", + "craft-math", + "craft-mcmat", + "craft-mcp", + "craft-mcp-server", + "craft-media", + "craft-media-source", + "craft-menu", + "craft-mesh", + "craft-metadata", + "craft-metafile", + "craft-midi", + "craft-mime", + "craft-odf", + "craft-ods", + "craft-offcrypto", + "craft-opc", + "craft-openpgp", + "craft-ora", + "craft-pages", + "craft-palette", + "craft-pcap", + "craft-pcraft-bundle", + "craft-pcraft-format", + "craft-pdf 0.1.0", + "craft-pdn", + "craft-pe", + "craft-penpot", + "craft-pkcs7", + "craft-platform", + "craft-plist", + "craft-plotter", + "craft-png", + "craft-ppt-binary", + "craft-pptx", + "craft-prc", + "craft-prepress", + "craft-press-print", + "craft-print", + "craft-proof", + "craft-proto", + "craft-ps", + "craft-psd", + "craft-pst", + "craft-quit", + "craft-raster-codecs", + "craft-raw", + "craft-review", + "craft-rtf", + "craft-sbs", + "craft-score", + "craft-scraft-format", + "craft-settings", + "craft-sf2", + "craft-sheet", + "craft-shx", + "craft-silhouette-studio", + "craft-sketch", + "craft-smime", + "craft-sniff", + "craft-sourcemap", + "craft-sqlite", + "craft-ssip", + "craft-stencilcraft-document", + "craft-stencilcraft-format", + "craft-stream-codecs", + "craft-suite-account", + "craft-svg", + "craft-table", + "craft-tar", + "craft-tcraft", + "craft-text", + "craft-texture", + "craft-tga", + "craft-theme", + "craft-theme-editor", + "craft-theme-store", + "craft-tiff", + "craft-time", + "craft-timeline", + "craft-tracked", + "craft-ui", + "craft-update", + "craft-usd", + "craft-vcard", + "craft-vectorcraft-format", + "craft-vectordrawable", + "craft-video", + "craft-wasm", + "craft-wayland", + "craft-web-api", + "craft-web-host", + "craft-webp", + "craft-window", + "craft-wordmodel", + "craft-xcf", + "craft-xfa", + "craft-xfdf", + "craft-xfl", + "craft-xls", + "craft-xlsx", + "craft-xml", + "craft-y4m", + "craft-zip", + "egui", + "toml", +] + [[package]] name = "craft-aaf" version = "0.1.0" @@ -1591,6 +2022,7 @@ dependencies = [ name = "craft-android-res" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "thiserror 2.0.21", ] @@ -1603,6 +2035,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +dependencies = [ + "block2 0.6.2", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "craft-assuan" version = "0.1.0" @@ -1615,7 +2056,7 @@ dependencies = [ name = "craft-atomic" version = "0.1.0" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1637,17 +2078,82 @@ dependencies = [ [[package]] name = "craft-audio-dsp" version = "0.1.0" +dependencies = [ + "craft-testkit", +] + +[[package]] +name = "craft-automation" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "craft-behavior", + "craft-control", + "craft-host", + "craft-keymap", + "craft-platform", + "craft-theme", + "craft-ui", + "egui", + "getrandom 0.3.4", + "hmac 0.12.1", + "log", + "png 0.17.16", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "thiserror 2.0.21", + "web-time", +] + +[[package]] +name = "craft-behavior" +version = "0.1.0" +dependencies = [ + "accesskit", + "bitflags 2.13.2", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "emath", + "kurbo", + "serde", + "serde_json", + "smallvec", +] [[package]] name = "craft-ber" version = "0.1.0" +[[package]] +name = "craft-browse" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", + "tempfile", +] + [[package]] name = "craft-captions" version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-testkit", "craft-timeline", "craft-xml", "proptest", @@ -1670,6 +2176,7 @@ name = "craft-cfb" version = "0.1.0" dependencies = [ "craft-media-testkit", + "craft-testkit", ] [[package]] @@ -1691,10 +2198,23 @@ dependencies = [ "tempfile", ] +[[package]] +name = "craft-cloud-ui" +version = "0.1.0" +dependencies = [ + "craft-cloud", + "craft-esign", + "egui", + "egui_kittest", + "image", + "serde_json", +] + [[package]] name = "craft-cms" version = "0.1.0" dependencies = [ + "craft-testkit", "md-5 0.10.6", "moxcms", "rayon", @@ -1725,6 +2245,26 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-color-ui" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-cms", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "craft-window", + "egui", + "egui_kittest", + "serde", + "serde_json", +] + [[package]] name = "craft-control" version = "0.1.0" @@ -1762,7 +2302,7 @@ dependencies = [ name = "craft-crw" version = "0.1.0" dependencies = [ - "proptest", + "craft-testkit", "serde", "serde_json", "sha2 0.10.9", @@ -1802,6 +2342,20 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-design-lint" +version = "0.1.0" +dependencies = [ + "dunce", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "toml", + "toml_edit", +] + [[package]] name = "craft-designcraft-format" version = "0.1.0" @@ -1823,6 +2377,7 @@ dependencies = [ "craft-geom", "craft-raw", "craft-render-parity", + "craft-testkit", "proptest", "rayon", "serde", @@ -1855,11 +2410,23 @@ name = "craft-dialogs" version = "0.1.0" dependencies = [ "block2 0.6.2", + "craft-atomic", + "craft-behavior", + "craft-browse", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-ui", + "egui", + "futures-lite", + "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "raw-window-handle", "rfd", + "serde_json", + "zbus", ] [[package]] @@ -1869,9 +2436,9 @@ dependencies = [ "blake3", "craft-ecproj-format", "craft-pcraft-format", + "craft-testkit", "craft-vectorcraft-format", "flate2", - "proptest", "ruzstd", "serde", "serde_json", @@ -1900,6 +2467,9 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" +dependencies = [ + "serde", +] [[package]] name = "craft-document-bundle" @@ -1922,6 +2492,7 @@ dependencies = [ "craft-math", "craft-offcrypto", "craft-opc", + "craft-testkit", "craft-wordmodel", "craft-xml", "image", @@ -1942,13 +2513,32 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-draw" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-color-ui", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-settings", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-drawingml" version = "0.1.0" dependencies = [ "chrono", + "craft-testkit", "craft-xml", - "kurbo 0.13.1", + "kurbo", "log", "serde", "serde_json", @@ -1968,7 +2558,7 @@ version = "0.1.0" dependencies = [ "craft-codepage", "encoding_rs", - "kurbo 0.13.1", + "kurbo", "log", "thiserror 2.0.21", ] @@ -1995,7 +2585,7 @@ dependencies = [ name = "craft-eps" version = "0.1.0" dependencies = [ - "kurbo 0.13.1", + "kurbo", "thiserror 2.0.21", "vectorcraft-doc", "vectorcraft-eps", @@ -2043,6 +2633,7 @@ dependencies = [ name = "craft-exr" version = "0.1.0" dependencies = [ + "craft-testkit", "exr", "flate2", "half", @@ -2067,7 +2658,7 @@ dependencies = [ "craft-kiwi", "craft-zip", "flate2", - "kurbo 0.13.1", + "kurbo", "ruzstd", "serde_json", "thiserror 2.0.21", @@ -2122,7 +2713,7 @@ dependencies = [ "craft-pdf 0.1.0", "craft-raster-codecs", "craft-svg", - "kurbo 0.13.1", + "kurbo", "thiserror 2.0.21", "vectorcraft-geom", ] @@ -2152,7 +2743,7 @@ version = "0.1.0" dependencies = [ "fontique", "harfrust 0.13.3", - "kurbo 0.13.1", + "kurbo", "skrifa 0.47.0", "thiserror 2.0.21", "unicode-bidi", @@ -2165,20 +2756,29 @@ dependencies = [ name = "craft-font-manager" version = "0.1.0" dependencies = [ + "craft-behavior", "craft-font-catalog", + "craft-font-manager", "craft-font-store", + "craft-fonts-build", + "craft-host", "craft-i18n", + "craft-theme", "craft-ui", "egui", - "egui_kittest", - "egui_system_font_provider", "epaint_default_fonts", - "image", "log", "serde", "serde_json", "skrifa 0.47.0", - "wuff", +] + +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", ] [[package]] @@ -2188,6 +2788,7 @@ dependencies = [ "cap-primitives", "craft-atomic", "craft-font-catalog", + "craft-font-os-windows", "flate2", "log", "ruzstd", @@ -2200,15 +2801,31 @@ dependencies = [ "toml", "ureq", "write-fonts 0.54.1", + "wuff", +] + +[[package]] +name = "craft-font-subset" +version = "0.1.0" +dependencies = [ + "brotli 9.1.1", + "craft-testkit", + "harfbuzz-subset-sys", + "rustybuzz", + "serde_json", + "skrifa 0.49.0", + "thiserror 2.0.21", + "unicode-normalization", + "write-fonts 0.55.0", + "wuff", ] [[package]] name = "craft-fonts-build" version = "0.1.0" dependencies = [ + "craft-font-subset", "craft-fonts-build-consumer", - "skera", - "skrifa 0.48.0", ] [[package]] @@ -2272,8 +2889,12 @@ dependencies = [ name = "craft-gpu" version = "0.1.0" dependencies = [ + "egui-wgpu", + "log", + "pollster 1.0.1", "serde", "serde_json", + "tempfile", "thiserror 2.0.21", ] @@ -2337,11 +2958,24 @@ dependencies = [ name = "craft-heif" version = "0.1.0" dependencies = [ + "craft-testkit", "heic-rs", "proptest", "rayon", ] +[[package]] +name = "craft-host" +version = "0.1.0" +dependencies = [ + "bitflags 2.13.2", + "craft-i18n", + "egui", + "serde", + "toml", + "web-time", +] + [[package]] name = "craft-html" version = "0.1.0" @@ -2363,8 +2997,11 @@ version = "0.1.0" name = "craft-i18n" version = "0.1.0" dependencies = [ + "chrono", "fixed_decimal", + "icu_calendar", "icu_collator", + "icu_datetime", "icu_decimal", "icu_locale_core", "icu_locale_fallback", @@ -2374,6 +3011,7 @@ dependencies = [ "icu_provider", "icu_provider_adapters", "icu_provider_blob", + "icu_time", "log", "objc2-foundation 0.3.2", "sys-locale", @@ -2436,6 +3074,26 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-imaging" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-color-ui", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui", + "craft-ui-test-kit", + "craft-window", + "egui", + "egui_kittest", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-indd" version = "0.1.0" @@ -2483,6 +3141,7 @@ dependencies = [ name = "craft-jpeg" version = "0.1.0" dependencies = [ + "craft-testkit", "jpeg-decoder", "jpeg-encoder 0.6.1", "rayon", @@ -2520,15 +3179,15 @@ dependencies = [ name = "craft-keymap" version = "0.1.0" dependencies = [ + "craft-host", "craft-i18n", "craft-settings", - "craft-ui", + "craft-tracked", + "craft-ui-macros", + "craft-xml", "egui", - "egui_kittest", - "image", "serde", "serde_json", - "sha2 0.10.9", "tempfile", ] @@ -2554,10 +3213,25 @@ dependencies = [ "craft-markdown", "craft-math", "craft-mime", + "craft-testkit", "craft-wordmodel", "proptest", ] +[[package]] +name = "craft-layers" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "serde", + "serde_json", +] + [[package]] name = "craft-lottie" version = "0.1.0" @@ -2589,6 +3263,7 @@ dependencies = [ name = "craft-material-graph" version = "0.1.0" dependencies = [ + "craft-testkit", "libm", "rayon", ] @@ -2676,12 +3351,20 @@ dependencies = [ name = "craft-menu" version = "0.1.0" dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", "craft-keymap", "craft-quit", + "craft-theme", + "craft-ui", + "craft-window", "egui", - "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "serde", + "serde_json", ] [[package]] @@ -2689,6 +3372,7 @@ name = "craft-mesh" version = "0.1.0" dependencies = [ "craft-opc", + "craft-testkit", "craft-xml", "craft-zip", "miniz_oxide 0.9.1", @@ -2715,7 +3399,7 @@ version = "0.1.0" dependencies = [ "encoding_rs", "image", - "kurbo 0.13.1", + "kurbo", "thiserror 2.0.21", ] @@ -2736,6 +3420,7 @@ dependencies = [ "chardetng", "chrono", "craft-codepage", + "craft-testkit", "encoding_rs", "proptest", ] @@ -2807,6 +3492,7 @@ dependencies = [ name = "craft-openpgp" version = "0.1.0" dependencies = [ + "craft-testkit", "ed25519-dalek 2.2.0", "pgp", "proptest", @@ -2828,6 +3514,22 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-pages" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-i18n", + "craft-keymap", + "craft-text", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-palette" version = "0.1.0" @@ -2873,6 +3575,7 @@ dependencies = [ "chrono", "craft-stream-codecs", "craft-svg", + "craft-testkit", "flate2", "hayro", "hayro-cmap", @@ -2881,10 +3584,11 @@ dependencies = [ "js-sys", "krilla", "krilla-svg", - "kurbo 0.13.1", + "kurbo", "md-5 0.11.0", "proptest", "roxmltree 0.21.2", + "serde", "serde_json", "sha2 0.11.1", "stringprep", @@ -2984,16 +3688,37 @@ dependencies = [ name = "craft-platform" version = "0.1.0" dependencies = [ + "arboard", "async-channel", "async-io", "async-process", - "egui", + "clipboard-win", + "core-graphics", + "core-graphics2", + "craft-atomic", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-theme", + "fmv-macos-events", "futures-lite", "js-sys", + "log", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "rfd", + "serde", + "serde_json", + "sysinfo", "wasm-bindgen", "wasm-bindgen-futures", "wasm-bindgen-test", "web-sys", + "web-time", + "windows", + "wl-clipboard-rs", + "x11rb", + "xcap", "zbus", ] @@ -3008,7 +3733,7 @@ dependencies = [ name = "craft-plotter" version = "0.1.0" dependencies = [ - "kurbo 0.13.1", + "kurbo", "serde", "thiserror 2.0.21", ] @@ -3042,7 +3767,7 @@ dependencies = [ "craft-drawingml", "craft-opc", "craft-xml", - "kurbo 0.13.1", + "kurbo", "log", "serde", "serde_json", @@ -3065,7 +3790,8 @@ dependencies = [ "craft-cms", "craft-pdf 0.1.0", "craft-plate-test", - "kurbo 0.13.1", + "craft-testkit", + "kurbo", "linesweeper", "thiserror 2.0.21", "ttf-parser", @@ -3085,11 +3811,21 @@ dependencies = [ name = "craft-print" version = "0.1.0" dependencies = [ + "craft-behavior", + "craft-host", + "craft-theme", + "craft-ui", "craft-winprint-gdi", + "egui", + "js-sys", "log", "miniz_oxide 0.9.1", "roxmltree 0.21.2", + "serde", + "serde_json", "tempfile", + "wasm-bindgen", + "web-sys", "winprint", "winsafe", ] @@ -3098,6 +3834,7 @@ dependencies = [ name = "craft-proof" version = "0.1.0" dependencies = [ + "craft-testkit", "log", "miniz_oxide 0.9.1", "proptest", @@ -3110,6 +3847,7 @@ name = "craft-proto" version = "0.1.0" dependencies = [ "base64 0.23.1", + "craft-testkit", "log", "proptest", "zeroize", @@ -3120,8 +3858,9 @@ name = "craft-ps" version = "0.1.0" dependencies = [ "craft-eps", + "craft-testkit", "flate2", - "kurbo 0.13.1", + "kurbo", "miniz_oxide 0.8.9", "pdf-writer", "skrifa 0.47.0", @@ -3133,6 +3872,7 @@ name = "craft-psd" version = "0.1.0" dependencies = [ "craft-psd", + "craft-testkit", "encoding_rs", "flate2", "proptest", @@ -3146,6 +3886,7 @@ name = "craft-pst" version = "0.1.0" dependencies = [ "craft-pst", + "craft-testkit", "proptest", ] @@ -3155,9 +3896,10 @@ version = "0.1.0" dependencies = [ "dispatch2", "egui", - "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "wasm-bindgen", + "web-sys", ] [[package]] @@ -3178,6 +3920,7 @@ dependencies = [ "chrono", "craft-crw", "craft-metadata", + "craft-testkit", "craft-tiff", "jpeg-encoder 0.7.1", "jxl-oxide", @@ -3199,6 +3942,25 @@ dependencies = [ "craft-cms", ] +[[package]] +name = "craft-review" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pages", + "craft-theme", + "craft-ui", + "egui", + "image", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-rtf" version = "0.1.0" @@ -3238,6 +4000,7 @@ version = "0.1.0" dependencies = [ "craft-audio", "craft-midi", + "craft-testkit", "craft-time", "craft-zip", "proptest", @@ -3251,10 +4014,18 @@ name = "craft-settings" version = "0.1.0" dependencies = [ "craft-atomic", + "craft-host", + "craft-settings", "dirs", + "log", "serde", + "serde_json", "tempfile", + "toml", "toml_edit", + "wasm-bindgen-test", + "web-sys", + "web-time", ] [[package]] @@ -3277,7 +4048,7 @@ version = "0.1.0" name = "craft-silhouette-studio" version = "0.1.0" dependencies = [ - "kurbo 0.13.1", + "kurbo", "thiserror 2.0.21", ] @@ -3287,7 +4058,7 @@ version = "0.1.0" dependencies = [ "craft-figma-rest", "craft-zip", - "kurbo 0.13.1", + "kurbo", "serde_json", "thiserror 2.0.21", "zip 9.1.3", @@ -3352,7 +4123,7 @@ dependencies = [ "craft-atomic", "craft-stencilcraft-format", "craft-svg", - "kurbo 0.13.1", + "kurbo", "serde", "serde_json", "thiserror 2.0.21", @@ -3371,6 +4142,7 @@ dependencies = [ name = "craft-stream-codecs" version = "0.1.0" dependencies = [ + "craft-testkit", "fax", "hayro-ccitt", "hayro-jbig2", @@ -3404,7 +4176,7 @@ dependencies = [ "flate2", "gif", "image-webp", - "kurbo 0.13.1", + "kurbo", "quick-xml 0.41.0", "resvg 0.48.1", "roxmltree 0.21.2", @@ -3420,7 +4192,19 @@ name = "craft-svg-paths" version = "0.1.0" dependencies = [ "craft-svg", - "kurbo 0.13.1", + "kurbo", +] + +[[package]] +name = "craft-table" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-table", + "craft-theme", + "craft-ui", + "egui", ] [[package]] @@ -3449,10 +4233,21 @@ version = "0.1.0" name = "craft-text" version = "0.1.0" dependencies = [ + "craft-behavior", + "craft-font-manager", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", "hypher", "icu_segmenter", - "kurbo 0.13.1", + "kurbo", "miniz_oxide 0.8.9", + "regex", + "regex-syntax", + "serde", + "serde_json", "unicode-bidi", "unicode-bidi-mirroring", "unicode-general-category", @@ -3479,6 +4274,46 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-theme" +version = "0.1.0" +dependencies = [ + "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", + "ecolor", + "log", + "proptest", + "serde", + "serde_json", + "smallvec", +] + +[[package]] +name = "craft-theme-editor" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-theme", + "craft-ui", + "egui", +] + +[[package]] +name = "craft-theme-store" +version = "0.1.0" +dependencies = [ + "craft-atomic", + "craft-behavior", + "craft-theme", + "craft-ui", + "dirs", + "egui", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -3504,41 +4339,267 @@ dependencies = [ name = "craft-timeline" version = "0.1.0" dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-theme", "craft-time", + "craft-ui", "craft-xml", + "egui", "proptest", "serde", "serde_json", + "web-time", +] + +[[package]] +name = "craft-tracked" +version = "0.1.0" +dependencies = [ + "craft-ui-macros", + "serde", ] [[package]] name = "craft-ui" version = "0.1.0" dependencies = [ - "craft-cloud", - "craft-esign", - "craft-fonts-build", + "craft-behavior", + "craft-cloud-ui", "craft-i18n", - "eframe", + "craft-ui", + "craft-ui-canvas", + "craft-ui-contract", + "craft-ui-panels", + "craft-ui-patterns", + "craft-ui-shell", + "craft-ui-widgets", + "egui", + "syn 2.0.119", + "toml", +] + +[[package]] +name = "craft-ui-bench" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-ui", + "craft-window", "egui", - "egui_extras", - "egui_kittest", - "epaint", - "fontique", - "image", - "js-sys", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", "serde", "serde_json", +] + +[[package]] +name = "craft-ui-canvas" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui-canvas", + "craft-ui-macros", + "craft-ui-panels", + "craft-ui-test-kit", + "craft-window", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-contract" +version = "0.1.0" +dependencies = [ + "accesskit", + "craft-behavior", + "craft-codepage", + "craft-font-catalog", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-quit", + "craft-settings", + "craft-svg", + "craft-testkit", + "craft-theme", + "craft-tracked", + "craft-ui-contract", + "craft-ui-macros", + "craft-ui-test-kit", + "craft-window", + "egui", + "egui_kittest", + "epaint", + "epaint_default_fonts", + "flate2", + "fontique", + "image", + "inventory", + "libtest-mimic", + "log", + "proc-macro2", + "scoped-tls", + "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", - "unicode-script", - "wasm-bindgen", + "smallvec", + "syn 2.0.119", + "toml", + "typeid", "wasm-bindgen-futures", - "wasm-bindgen-test", - "web-sys", + "web-time", +] + +[[package]] +name = "craft-ui-gallery" +version = "0.1.0" +dependencies = [ + "craft-automation", + "craft-behavior", + "craft-browse", + "craft-color-ui", + "craft-dialogs", + "craft-draw", + "craft-font-manager", + "craft-i18n", + "craft-imaging", + "craft-layers", + "craft-menu", + "craft-pages", + "craft-print", + "craft-review", + "craft-settings", + "craft-table", + "craft-text", + "craft-theme", + "craft-theme-editor", + "craft-theme-store", + "craft-timeline", + "craft-ui", + "craft-update", + "craft-window", + "eframe", + "egui", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "toml", + "wasm-bindgen-futures", + "web-time", +] + +[[package]] +name = "craft-ui-macros" +version = "0.1.0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "craft-ui-panels" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-ui-widgets", + "egui", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "craft-ui-patterns" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pdf 0.1.0", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-ui-patterns", + "craft-ui-test-kit", + "egui", + "serde", + "serde_json", + "toml", + "toml_edit", + "zeroize", +] + +[[package]] +name = "craft-ui-shell" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-svg", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-ui-shell", + "craft-ui-test-kit", + "craft-window", + "eframe", + "egui", + "raw-window-handle", + "serde", + "serde_json", + "web-time", +] + +[[package]] +name = "craft-ui-test-kit" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-ui-contract", + "egui", +] + +[[package]] +name = "craft-ui-widgets" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-svg", + "craft-theme", + "craft-ui-contract", + "craft-ui-macros", + "craft-ui-test-kit", + "craft-ui-widgets", + "egui", + "log", + "serde", + "smallvec", ] [[package]] @@ -3546,16 +4607,16 @@ name = "craft-update" version = "0.1.0" dependencies = [ "chrono", + "craft-host", + "craft-theme", + "craft-ui", "dunce", "egui", - "egui_kittest", - "epaint_default_fonts", "flate2", - "getrandom 0.3.4", "image", "log", "plist", - "rustix 1.1.5", + "rustix 1.1.6", "semver", "serde", "serde_json", @@ -3603,7 +4664,7 @@ name = "craft-vectordrawable" version = "0.1.0" dependencies = [ "craft-xml", - "kurbo 0.13.1", + "kurbo", ] [[package]] @@ -3630,6 +4691,15 @@ dependencies = [ "wasmprinter", ] +[[package]] +name = "craft-wayland" +version = "0.1.0" +dependencies = [ + "raw-window-handle", + "wayland-backend", + "wayland-client", +] + [[package]] name = "craft-web-api" version = "0.1.0" @@ -3645,7 +4715,10 @@ dependencies = [ name = "craft-web-host" version = "0.1.0" dependencies = [ + "craft-host", + "craft-platform", "wasm-bindgen", + "wasm-bindgen-futures", "wasm-bindgen-test", "web-sys", ] @@ -3659,19 +4732,35 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-win32" +version = "0.1.0" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-window" version = "0.1.0" dependencies = [ + "craft-appkit", "craft-atomic", + "craft-behavior", + "craft-host", "craft-settings", + "craft-win32", "egui", + "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", "serde", "serde_json", "tempfile", "wayland-client", + "winsafe", + "x11rb", ] [[package]] @@ -3700,6 +4789,7 @@ dependencies = [ name = "craft-xcf" version = "0.1.0" dependencies = [ + "craft-testkit", "flate2", "thiserror 2.0.21", ] @@ -3723,6 +4813,7 @@ dependencies = [ name = "craft-xfl" version = "0.1.0" dependencies = [ + "craft-testkit", "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", @@ -3748,6 +4839,7 @@ dependencies = [ "craft-drawingml", "craft-opc", "craft-sheet", + "craft-testkit", "craft-xlsx", "craft-xml", "thiserror 2.0.21", @@ -3757,6 +4849,7 @@ dependencies = [ name = "craft-xml" version = "0.1.0" dependencies = [ + "craft-testkit", "quick-xml 0.41.0", "serde", "thiserror 2.0.21", @@ -4240,19 +5333,6 @@ dependencies = [ "cipher 0.5.2", ] -[[package]] -name = "dify" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ce0fb972943b4e88cd03b8f92953df0c71bb05e0bde8e5b684895d808013cc" -dependencies = [ - "anyhow", - "colored", - "getopts", - "image", - "rayon", -] - [[package]] name = "digest" version = "0.10.7" @@ -4363,6 +5443,61 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.6", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.6", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + [[package]] name = "dsa" version = "0.6.3" @@ -4446,11 +5581,10 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "emath", - "serde", ] [[package]] @@ -4503,7 +5637,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -4538,7 +5672,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit", "ahash", @@ -4549,7 +5683,6 @@ dependencies = [ "log", "nohash-hasher", "profiling", - "serde", "smallvec", "unicode-segmentation", "web-sys", @@ -4558,7 +5691,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -4577,7 +5710,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "block2 0.6.2", "bytemuck", @@ -4594,24 +5727,10 @@ dependencies = [ "winit", ] -[[package]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -dependencies = [ - "ahash", - "egui", - "enum-map", - "itertools 0.15.0", - "log", - "profiling", - "resvg 0.45.1", -] - [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "egui", @@ -4624,37 +5743,20 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ - "dify", "eframe", "egui", "egui-wgpu", "image", "kittest", "log", - "open", "pollster 1.0.1", "serde", - "tempfile", "toml", "wgpu", ] -[[package]] -name = "egui_system_font_provider" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -dependencies = [ - "epaint", - "fontique", - "log", - "poll-promise", - "skrifa 0.44.0", - "sys-locale", - "unicode-script", -] - [[package]] name = "either" version = "1.19.0" @@ -4718,10 +5820,9 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", - "serde", ] [[package]] @@ -4768,26 +5869,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "enum-map" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" -dependencies = [ - "enum-map-derive", -] - -[[package]] -name = "enum-map-derive" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - [[package]] name = "enumflags2" version = "0.7.12" @@ -4809,21 +5890,10 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "enumn" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -4837,7 +5907,6 @@ dependencies = [ "parking_lot", "profiling", "self_cell", - "serde", "skrifa 0.44.0", "smallvec", "unicode-bidi", @@ -4850,7 +5919,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[package]] name = "equator" @@ -4888,12 +5957,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "esaxx-rs" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" +[[package]] +name = "escape8259" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f0d310082fd5de539d4f41601182241147498444a7695c520288a0cdbead6" + [[package]] name = "euclid" version = "0.22.14" @@ -4994,6 +6075,31 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "feature-root" +version = "0.1.0" +dependencies = [ + "craft-automation", + "craft-browse", + "craft-color-ui", + "craft-dialogs", + "craft-draw", + "craft-font-manager", + "craft-imaging", + "craft-layers", + "craft-menu", + "craft-pages", + "craft-print", + "craft-review", + "craft-table", + "craft-text", + "craft-theme-store", + "craft-timeline", + "craft-ui-gallery", + "craft-update", + "epaint_default_fonts", +] + [[package]] name = "ff" version = "0.13.1" @@ -5054,6 +6160,12 @@ dependencies = [ "writeable", ] +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + [[package]] name = "flagset" version = "0.4.7" @@ -5125,6 +6237,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "fmv-macos-events" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55" +dependencies = [ + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "fnv" version = "1.0.7" @@ -5159,7 +6282,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", - "serde", ] [[package]] @@ -5272,7 +6394,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.59.0", ] @@ -5362,6 +6484,30 @@ dependencies = [ "slab", ] +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + [[package]] name = "gemm" version = "0.19.0" @@ -5498,19 +6644,10 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] -[[package]] -name = "getopts" -version = "0.2.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" -dependencies = [ - "unicode-width", -] - [[package]] name = "getrandom" version = "0.2.17" @@ -5572,6 +6709,15 @@ dependencies = [ "weezl 0.1.12", ] +[[package]] +name = "gl" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404" +dependencies = [ + "gl_generator", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -5623,6 +6769,12 @@ dependencies = [ "vello_common 0.2.0", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -5779,6 +6931,14 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "harfbuzz-subset-sys" +version = "0.1.0+harfbuzz-15.0.0" +source = "git+https://github.com/storytold/harfbuzz.git?rev=f32ed1e548eaa8852bff47e49a90629a013a2faa#f32ed1e548eaa8852bff47e49a90629a013a2faa" +dependencies = [ + "cc", +] + [[package]] name = "harfrust" version = "0.12.0" @@ -5844,7 +7004,7 @@ dependencies = [ "bytemuck", "hayro-interpret", "image", - "kurbo 0.13.1", + "kurbo", "log", "pic-scale", "vello_cpu 0.0.8", @@ -5871,7 +7031,7 @@ dependencies = [ "bitflags 2.13.2", "hayro-cmap", "hayro-syntax", - "kurbo 0.13.1", + "kurbo", "moxcms", "phf 0.13.1", "rustc-hash 2.1.3", @@ -6133,6 +7293,21 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_locale_core", + "icu_provider", + "serde", + "tinystr", + "zerovec", +] + [[package]] name = "icu_collator" version = "2.3.1" @@ -6166,6 +7341,30 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_datetime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44df99c4c5297b05653d1a1629f13bdc9fd4044acfbbaf30b15194a1eed4cd6" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "serde", + "smallvec", + "tinystr", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "icu_decimal" version = "2.3.0" @@ -6354,6 +7553,22 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" +[[package]] +name = "icu_time" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af37e1c3b9f3ab564b619fdf4b22de169f6381eb0f7048e3ca454290c438126b" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "serde", + "zerotrie", + "zerovec", +] + [[package]] name = "idea" version = "0.5.1" @@ -6422,12 +7637,6 @@ dependencies = [ "quick-error 2.0.1", ] -[[package]] -name = "imagesize" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" - [[package]] name = "imagesize" version = "0.14.0" @@ -6504,6 +7713,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -6533,22 +7751,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] -name = "is-docker" -version = "0.2.0" +name = "is_terminal_polyfill" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" -dependencies = [ - "once_cell", -] +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] -name = "is-wsl" -version = "0.4.0" +name = "itertools" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ - "is-docker", - "once_cell", + "either", ] [[package]] @@ -7023,7 +8237,7 @@ dependencies = [ "skrifa 0.42.1", "smallvec", "subsetter", - "tiny-skia-path 0.12.0", + "tiny-skia-path", "xmp-writer", "yoke", "zune-jpeg", @@ -7041,21 +8255,10 @@ dependencies = [ "resvg 0.47.0", "skrifa 0.42.1", "smallvec", - "tiny-skia 0.12.0", + "tiny-skia", "usvg 0.47.0", ] -[[package]] -name = "kurbo" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" -dependencies = [ - "arrayvec", - "euclid", - "smallvec", -] - [[package]] name = "kurbo" version = "0.13.1" @@ -7128,6 +8331,66 @@ dependencies = [ "redox_syscall 0.9.4", ] +[[package]] +name = "libspa" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.6", + "system-deps", +] + +[[package]] +name = "libspa-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924" +dependencies = [ + "bindgen", + "cc", + "system-deps", +] + +[[package]] +name = "libtest-mimic" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14e6ba06f0ade6e504aff834d7c34298e5155c6baca353cc6a4aaff2f9fd7f33" +dependencies = [ + "anstream", + "anstyle", + "clap", + "escape8259", +] + +[[package]] +name = "libwayshot-xcap" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5" +dependencies = [ + "drm 0.15.0", + "gbm", + "gl", + "image", + "khronos-egl", + "memmap2", + "rustix 1.1.6", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -7139,7 +8402,7 @@ name = "linesweeper" version = "0.5.0" dependencies = [ "arrayvec", - "kurbo 0.13.1", + "kurbo", "polycool", "rustc-hash 2.1.3", "smallvec", @@ -7151,6 +8414,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -7766,8 +9035,8 @@ dependencies = [ "block2 0.5.1", "libc", "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", "objc2-quartz-core 0.2.2", ] @@ -7780,8 +9049,48 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", + "objc2-cloud-kit 0.3.2", + "objc2-core-data 0.3.2", "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-avf-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-image-io", + "objc2-media-toolbox", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "objc2 0.6.5", "objc2-foundation 0.3.2", ] @@ -7798,6 +9107,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-contacts" version = "0.2.2" @@ -7809,6 +9129,28 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" @@ -7821,6 +9163,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -7828,7 +9181,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", ] @@ -7838,10 +9193,14 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -7856,6 +9215,16 @@ dependencies = [ "objc2-metal 0.2.2", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-location" version = "0.2.2" @@ -7868,6 +9237,22 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + [[package]] name = "objc2-core-text" version = "0.3.2" @@ -7875,7 +9260,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" dependencies = [ "bitflags 2.13.2", + "objc2 0.6.5", "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -7905,10 +9307,22 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", "objc2-core-foundation", ] +[[package]] +name = "objc2-image-io" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-io-kit" version = "0.3.2" @@ -7942,6 +9356,18 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-media-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd9fdde720df3da7046bb9097811000c1e7ab5cd579fa89d96b27d56781fb30" +dependencies = [ + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-media", +] + [[package]] name = "objc2-metal" version = "0.2.2" @@ -8023,9 +9449,9 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "objc2 0.5.3", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", + "objc2-cloud-kit 0.2.2", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-core-location", "objc2-foundation 0.2.2", "objc2-link-presentation", @@ -8107,6 +9533,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "onig" version = "6.5.3" @@ -8141,16 +9573,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" -[[package]] -name = "open" -version = "5.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" -dependencies = [ - "is-wsl", - "libc", -] - [[package]] name = "openssl-probe" version = "0.2.1" @@ -8201,6 +9623,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "outref" version = "0.5.2" @@ -8408,7 +9840,7 @@ checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" dependencies = [ "bytemuck", "color", - "kurbo 0.13.1", + "kurbo", "linebender_resource_handle", "smallvec", ] @@ -8419,6 +9851,17 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + [[package]] name = "pgp" version = "0.21.0" @@ -8603,6 +10046,31 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.6", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0" +dependencies = [ + "bindgen", + "libspa-sys", + "system-deps", +] + [[package]] name = "pkcs1" version = "0.7.5" @@ -8710,16 +10178,6 @@ dependencies = [ "miniz_oxide 0.8.9", ] -[[package]] -name = "poll-promise" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6a58fecbf9da8965bcdb20ce4fd29788d1acee68ddbb64f0ba1b81bccdb7df" -dependencies = [ - "document-features", - "static_assertions", -] - [[package]] name = "polling" version = "3.11.0" @@ -8730,7 +10188,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -9391,6 +10849,20 @@ dependencies = [ "yoke", ] +[[package]] +name = "read-fonts" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "font-types 0.12.7", + "once_cell", + "smallvec", + "yoke", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -9576,20 +11048,6 @@ dependencies = [ "rgb", ] -[[package]] -name = "resvg" -version = "0.45.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" -dependencies = [ - "log", - "pico-args", - "rgb", - "svgtypes 0.15.3", - "tiny-skia 0.11.4", - "usvg 0.45.1", -] - [[package]] name = "resvg" version = "0.47.0" @@ -9601,8 +11059,8 @@ dependencies = [ "log", "pico-args", "rgb", - "svgtypes 0.16.2", - "tiny-skia 0.12.0", + "svgtypes", + "tiny-skia", "usvg 0.47.0", "zune-jpeg", ] @@ -9619,8 +11077,8 @@ dependencies = [ "log", "pico-args", "rgb", - "svgtypes 0.16.2", - "tiny-skia 0.12.0", + "svgtypes", + "tiny-skia", "usvg 0.48.1", "zune-jpeg", ] @@ -9807,9 +11265,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -9825,7 +11283,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -9988,6 +11446,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + [[package]] name = "scopeguard" version = "1.2.0" @@ -10294,6 +11758,12 @@ dependencies = [ "sponge-cursor", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -10536,18 +12006,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" -[[package]] -name = "skera" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "531045338e36ad05b9652912a47ba38a935d0eaa0293c3e33d8112cfa414c14b" -dependencies = [ - "hashbrown 0.17.1", - "skrifa 0.48.0", - "thiserror 2.0.21", - "write-fonts 0.54.1", -] - [[package]] name = "skrifa" version = "0.42.1" @@ -10580,12 +12038,15 @@ dependencies = [ [[package]] name = "skrifa" -version = "0.48.0" +version = "0.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034" +checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d" dependencies = [ "bytemuck", - "read-fonts 0.45.1", + "once_cell", + "read-fonts 0.46.0", + "smallvec", + "yoke", ] [[package]] @@ -10717,6 +12178,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "story-render" +version = "0.1.0" +dependencies = [ + "craft-behavior", + "craft-ui", + "craft-ui-gallery", + "egui", + "image", +] + [[package]] name = "strict-num" version = "0.1.1" @@ -10780,7 +12252,7 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6" dependencies = [ - "kurbo 0.13.1", + "kurbo", "rustc-hash 2.1.3", "skrifa 0.42.1", "write-fonts 0.48.1", @@ -10792,23 +12264,13 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "svgtypes" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" -dependencies = [ - "kurbo 0.11.3", - "siphasher", -] - [[package]] name = "svgtypes" version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" dependencies = [ - "kurbo 0.13.1", + "kurbo", "siphasher", ] @@ -11134,6 +12596,19 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + [[package]] name = "tap" version = "1.0.1" @@ -11157,6 +12632,12 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.27.0" @@ -11166,7 +12647,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -11272,21 +12753,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-skia" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" -dependencies = [ - "arrayref", - "arrayvec", - "bytemuck", - "cfg-if", - "log", - "png 0.17.16", - "tiny-skia-path 0.11.4", -] - [[package]] name = "tiny-skia" version = "0.12.0" @@ -11299,18 +12765,7 @@ dependencies = [ "cfg-if", "log", "png 0.18.1", - "tiny-skia-path 0.12.0", -] - -[[package]] -name = "tiny-skia-path" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" -dependencies = [ - "arrayref", - "bytemuck", - "strict-num", + "tiny-skia-path", ] [[package]] @@ -11575,6 +13030,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom 8.0.0", + "petgraph", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -11620,6 +13086,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.1" @@ -11681,9 +13153,9 @@ checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -11806,28 +13278,6 @@ dependencies = [ "serde", ] -[[package]] -name = "usvg" -version = "0.45.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" -dependencies = [ - "base64 0.22.1", - "data-url", - "flate2", - "imagesize 0.13.0", - "kurbo 0.11.3", - "log", - "pico-args", - "roxmltree 0.20.0", - "simplecss", - "siphasher", - "strict-num", - "svgtypes 0.15.3", - "tiny-skia-path 0.11.4", - "xmlwriter", -] - [[package]] name = "usvg" version = "0.47.0" @@ -11839,7 +13289,7 @@ dependencies = [ "flate2", "fontdb 0.23.0", "imagesize 0.14.0", - "kurbo 0.13.1", + "kurbo", "log", "pico-args", "roxmltree 0.21.2", @@ -11847,8 +13297,8 @@ dependencies = [ "simplecss", "siphasher", "strict-num", - "svgtypes 0.16.2", - "tiny-skia-path 0.12.0", + "svgtypes", + "tiny-skia-path", "ttf-parser", "unicode-bidi", "unicode-script", @@ -11867,7 +13317,7 @@ dependencies = [ "fontdb 0.24.0", "harfrust 0.12.0", "imagesize 0.15.0", - "kurbo 0.13.1", + "kurbo", "log", "pico-args", "roxmltree 0.21.2", @@ -11875,8 +13325,8 @@ dependencies = [ "siphasher", "skrifa 0.44.0", "strict-num", - "svgtypes 0.16.2", - "tiny-skia-path 0.12.0", + "svgtypes", + "tiny-skia-path", "unicode-bidi", "unicode-script", "unicode-vo", @@ -11901,6 +13351,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.27.0" @@ -11938,7 +13394,7 @@ name = "vectorcraft-brush" version = "0.18.0" source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" dependencies = [ - "kurbo 0.13.1", + "kurbo", "serde", "serde_json", "vectorcraft-color", @@ -11951,7 +13407,7 @@ name = "vectorcraft-color" version = "0.18.0" source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" dependencies = [ - "kurbo 0.13.1", + "kurbo", "moxcms", "serde", "serde_json", @@ -11966,7 +13422,7 @@ dependencies = [ "chrono", "hayro-ccitt", "image", - "kurbo 0.13.1", + "kurbo", "serde", "serde_json", "thiserror 2.0.21", @@ -11982,7 +13438,7 @@ version = "0.18.0" source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" dependencies = [ "image", - "kurbo 0.13.1", + "kurbo", "serde_json", "vectorcraft-doc", "vectorcraft-geom", @@ -12000,7 +13456,7 @@ dependencies = [ "flate2", "hayro-ccitt", "image", - "kurbo 0.13.1", + "kurbo", "memchr", "ruzstd", "serde_json", @@ -12020,7 +13476,7 @@ name = "vectorcraft-geom" version = "0.18.0" source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" dependencies = [ - "kurbo 0.13.1", + "kurbo", "serde", "thiserror 2.0.21", ] @@ -12031,7 +13487,7 @@ version = "0.18.0" source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" dependencies = [ "image", - "kurbo 0.13.1", + "kurbo", "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", @@ -12045,7 +13501,7 @@ name = "vectorcraft-pathops" version = "0.18.0" source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" dependencies = [ - "kurbo 0.13.1", + "kurbo", "linesweeper", "thiserror 2.0.21", "vectorcraft-geom", @@ -12063,7 +13519,7 @@ dependencies = [ "getrandom 0.4.3", "image", "jpeg-encoder 0.6.1", - "kurbo 0.13.1", + "kurbo", "log", "md-5 0.10.6", "roxmltree 0.21.2", @@ -12125,7 +13581,7 @@ source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420 dependencies = [ "harfrust 0.13.3", "icu_segmenter", - "kurbo 0.13.1", + "kurbo", "log", "skrifa 0.47.0", "subsetter", @@ -12234,6 +13690,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -12464,7 +13926,8 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", + "scoped-tls", "smallvec", "wayland-sys", ] @@ -12476,11 +13939,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + [[package]] name = "wayland-scanner" version = "0.31.11" @@ -12492,6 +13980,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -12499,7 +14000,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -13105,6 +14608,24 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.6", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "wnaf" version = "0.14.1" @@ -13125,7 +14646,7 @@ checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8" dependencies = [ "font-types 0.11.3", "indexmap", - "kurbo 0.13.1", + "kurbo", "log", "read-fonts 0.39.2", ] @@ -13138,11 +14659,24 @@ checksum = "55716cfa7e8bcdb90289e07dfac478ccb2e3ec0f9a604fe682c7a03a7984d705" dependencies = [ "font-types 0.12.7", "indexmap", - "kurbo 0.13.1", + "kurbo", "log", "read-fonts 0.45.1", ] +[[package]] +name = "write-fonts" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e91ad74b39f48f456560ed1ccc75959efa19bf6f0817d1560751bb49db84f6c" +dependencies = [ + "font-types 0.12.7", + "indexmap", + "kurbo", + "log", + "read-fonts 0.46.0", +] + [[package]] name = "write16" version = "1.0.0" @@ -13166,6 +14700,7 @@ checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd" dependencies = [ "brotli-decompressor 6.3.1", "bytes", + "flate2", ] [[package]] @@ -13199,7 +14734,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -13282,7 +14817,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", +] + +[[package]] +name = "xcap" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da270fd7c8581d43d731cb690bcc791fc0a7b3bc96e131a4b6552d0379640a9e" +dependencies = [ + "dispatch2", + "image", + "libwayshot-xcap", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "percent-encoding", + "pipewire", + "rand 0.10.3", + "scopeguard", + "serde", + "thiserror 2.0.21", + "url", + "widestring", + "windows", + "xcb", + "zbus", +] + +[[package]] +name = "xcb" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" +dependencies = [ + "bitflags 2.13.2", + "libc", + "quick-xml 0.41.0", ] [[package]] @@ -13400,7 +14977,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -13674,9 +15251,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" + +[[patch.unused]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" + +[[patch.unused]] +name = "egui_system_font_provider" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" diff --git a/Cargo.toml b/Cargo.toml index 607c0a49dd..3608b63e20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,9 @@ craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } +craft-win32 = { path = "crates/win32" } +craft-appkit = { path = "crates/appkit" } +craft-wayland = { path = "crates/wayland" } craft-cdr = { path = "crates/cdr" } craft-ai = { path = "crates/ai" } craft-ai-core = { path = "crates/ai-core" } @@ -64,6 +67,7 @@ thiserror = "2" craft-gzip = { path = "crates/gzip" } craft-gridcraft-format = { path = "crates/gridcraft-format" } craft-aaf = { path = "crates/aaf" } +craft-behavior = { path = "crates/behavior" } craft-atomic = { path = "crates/atomic" } # The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/app/ai-agents). craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "d94a3593adcff504eaaad9e5aee4c84fd2f07a72" } @@ -75,13 +79,19 @@ craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } 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-color-ui = { path = "crates/color-ui" } craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } craft-csv = { path = "crates/csv" } craft-dav = { path = "crates/dav" } +craft-automation = { path = "crates/automation" } +craft-browse = { path = "crates/browse" } +craft = { path = "crates/craft" } +craft-design-lint = { path = "crates/design-lint" } craft-dialogs = { path = "crates/dialogs" } craft-doc-binary = { path = "crates/doc-binary" } craft-docx = { path = "crates/docx" } @@ -103,6 +113,7 @@ vectorcraft-pathops = { git = "https://github.com/storytold/vectorcraft.git", re craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } craft-dpx = { path = "crates/dpx" } +craft-draw = { path = "crates/draw" } craft-dwg = { path = "crates/dwg" } craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } @@ -112,6 +123,7 @@ craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } craft-font-catalog = { path = "crates/font-catalog" } craft-font-manager = { path = "crates/font-manager" } +craft-font-os-windows = { path = "crates/font-os-windows" } craft-font-store = { path = "crates/font-store" } craft-gainmap = { path = "crates/gainmap" } craft-flow = { path = "crates/flow" } @@ -124,6 +136,10 @@ craft-ipp = { path = "crates/ipp" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } +craft-font-subset = { path = "crates/font-subset" } +# The HarfBuzz subsetter from storytold's HarfBuzz fork (branch rust-subset-15.0.0: HarfBuzz 15.0.0 plus rust/harfbuzz-subset-sys). +harfbuzz-subset-sys = { git = "https://github.com/storytold/harfbuzz.git", rev = "f32ed1e548eaa8852bff47e49a90629a013a2faa" } +craft-host = { path = "crates/host" } craft-gpu = { path = "crates/gpu" } craft-gpu-null = { path = "crates/gpu-null" } craft-gpu-providers = { path = "crates/gpu-providers" } @@ -134,7 +150,9 @@ craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } craft-jmap = { path = "crates/jmap" } craft-ical = { path = "crates/ical" } +craft-imaging = { path = "crates/imaging" } craft-jpeg = { path = "crates/jpeg" } +craft-control = { path = "crates/control" } craft-control-protocol = { path = "crates/control-protocol" } craft-jsonrpc = { path = "crates/jsonrpc" } craft-mcp = { path = "crates/mcp" } @@ -143,6 +161,7 @@ craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } craft-assuan = { path = "crates/assuan" } craft-kra = { path = "crates/kra" } +craft-layers = { path = "crates/layers" } craft-audio = { path = "crates/audio" } craft-latex = { path = "crates/latex" } craft-markdown = { path = "crates/markdown" } @@ -175,6 +194,7 @@ craft-pcraft-bundle = { path = "crates/pcraft-bundle" } craft-pkcs7 = { path = "crates/pkcs7" } craft-plotter = { path = "crates/plotter" } craft-prepress = { path = "crates/prepress" } +craft-pages = { path = "crates/pages" } craft-press-print = { path = "crates/press-print" } craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } @@ -191,7 +211,9 @@ craft-develop = { path = "crates/develop" } craft-develop-model = { path = "crates/develop-model" } craft-sheet = { path = "crates/sheet" } craft-sketch = { path = "crates/sketch" } +craft-review = { path = "crates/review" } craft-settings = { path = "crates/settings" } +craft-figcraft-format = { path = "crates/figcraft-format" } craft-scraft-format = { path = "crates/scraft-format" } craft-time = { path = "crates/time" } craft-silhouette-studio = { path = "crates/silhouette-studio" } @@ -209,7 +231,20 @@ craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } craft-metadata = { path = "crates/metadata" } +craft-table = { path = "crates/table" } +craft-theme = { path = "crates/theme" } +craft-theme-editor = { path = "crates/theme-editor" } +craft-theme-store = { path = "crates/theme-store" } +craft-tracked = { path = "crates/tracked" } craft-ui = { path = "crates/ui" } +craft-ui-canvas = { path = "crates/ui-canvas" } +craft-ui-contract = { path = "crates/ui-contract" } +craft-ui-panels = { path = "crates/ui-panels" } +craft-ui-patterns = { path = "crates/ui-patterns" } +craft-ui-shell = { path = "crates/ui-shell" } +craft-ui-test-kit = { path = "crates/ui-test-kit" } +craft-ui-widgets = { path = "crates/ui-widgets" } +craft-ui-macros = { path = "crates/ui-macros" } craft-update = { path = "crates/update" } craft-vcard = { path = "crates/vcard" } craft-vectorcraft-format = { path = "crates/vectorcraft-format" } @@ -225,20 +260,28 @@ craft-zip = { path = "crates/zip" } craft-y4m = { path = "crates/y4m" } craft-sniff = { path = "crates/sniff" } craft-tar = { path = "crates/tar" } +craft-format = { path = "crates/format" } +craft-mcp-server = { path = "crates/mcp-server" } craft-epub = { path = "crates/epub" } craft-ews = { path = "crates/ews" } craft-video = { path = "crates/video" } craft-web-api = { path = "crates/web-api" } craft-window = { path = "crates/window" } +# egui's colour types alone, for crates that convert to and from them without egui. +ecolor = { version = "0.37", default-features = false } craft-web-host = { path = "crates/web-host" } craft-webp = { path = "crates/webp" } egui = { version = "0.37", default-features = false } +bitflags = "2" md5 = { package = "md-5", version = "0.10", default-features = false } jxl-oxide = { version = "0.12", default-features = false } jixel = "=0.3.4" rayon = "1" +scoped-tls = "1" +smallvec = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" +typeid = "1" proptest = "1" # Character sets of the WHATWG Encoding Standard (craft-mime). (Apache-2.0 OR MIT) AND BSD-3-Clause. encoding_rs = "0.8" @@ -274,20 +317,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 = "6d518fc799681571963842f95b55a6b68431b15a" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +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" } 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 84f9d4c549..c63edc0812 100644 --- a/NOTICE +++ b/NOTICE @@ -64,6 +64,12 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer. +crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists) + 2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/. + Permission to use, copy, modify, distribute and sell these word lists is granted without fee + provided the copyright and permission notice appears in all copies; the full notice, with the + notices of the lists SCOWL draws on, is in crates/text/assets/spell/LICENSE-SCOWL.txt and must + ship with any application that enables craft-text's `spell` feature. Hyphenation patterns for other languages, embedded through the hypher crate only when the matching craft-text feature is enabled (none are by default). They come from hyph-utf8, https://github.com/hyphenation/tex-hyphen, as packaged in https://github.com/typst/hypher diff --git a/README.md b/README.md index 9512980917..5cbfd01ab4 100644 --- a/README.md +++ b/README.md @@ -56,19 +56,21 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit ## Libraries - [`craft-platform`](crates/platform/README.md): optional native dialog lifecycle, Linux/BSD desktop appearance observation and browser download ownership; application policy stays in the apps. - - [`craft-aep`](crates/aep/README.md): After Effects projects: the `.aep` (RIFX) and `.aepx` container as a lossless chunk tree that writes back byte for byte, and a typed, read-only view of compositions, layers, properties, keyframes, effects, masks, shapes, text and footage. Clean room, from EffectCraft. Mapping onto an app's document stays in the app. + +- [`craft-ai`](crates/ai/README.md) *(spec)*: AI provider abstraction — BYO API keys (OpenAI-compatible) and one-click curated local models with capability probing, resumable checksummed downloads, and document segmentation that protects markup while translating prose; - [`craft-ai-core`](crates/ai-core/README.md): the data model and contract for AI in the Craft Apps (connections, models, tools, requests, jobs, consent, history, route spec). Pure, no I/O, wasm-safe. Contract in [docs/ai-shared-layer.md](docs/ai-shared-layer.md). - [`craft-pe`](crates/pe/src/lib.rs): PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`) from untrusted bytes, from Craft Anything: the COFF header, PE32/PE32+ optional header with its data directories bounded by the header's real size, the section table, RVA-to-file mapping and the decoded Rich header. - [`craft-pdf`](crates/pdf/README.md): independently optional PDF parsing, interpretation, rasterization and guarded authoring. Apps retain layout, fonts, editing and export policy; writer-only consumers do not enable the shared reader. - - [`craft-pdn`](crates/pdn/README.md): Paint.NET documents (`.pdn`, PDN3), read: the layer list, blend modes and chunked gzip pixel blocks, with a data-only MS-NRBF (.NET binary serialization) reader. From PhotoCraft. - [`craft-aaf`](crates/aaf/README.md): clean-room AAF (Edit Protocol, structured storage) and OMF Interchange 2.0 (Bento) readers and writers over one mob-style composition model with exact times, clip gain, markers, nested compositions and embedded PCM essence. From FilmCraft. - [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped. - [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app. + +- [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target). - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. - [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral @@ -81,11 +83,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-dav`](crates/dav/README.md): WebDAV multistatus documents (RFC 4918) with the CalDAV and CardDAV namespaces, from MailCraft: read fail-closed into a bounded `craft-xml` tree with fixed prefixes, and the successful properties of each response. No I/O. +- [`craft-browse`](crates/browse/README.md): browsing: standard folders, volumes and lazy folder + listings, linked-file statuses kept current, file thumbnails decoded by the app in jobs, and + (`ui` feature) the tile grid, media bin, places tree, compare tile, links list and relink dialog. - [`craft-cms`](crates/cms/README.md): pure-Rust ICC v2/v4 colour management: profile parsing and writing, transforms, rendering intents, black point compensation, soft proofing, gamut checks, 3D LUTs and built-in profiles (sRGB, Display P3, synthetic coated CMYK and others). - [`craft-crs`](crates/crs/README.md): Adobe Camera Raw settings (the `crs:` namespace of an XMP packet or `.xmp` sidecar, read through craft-metadata): the settings by name, numbers, tone curve points, local corrections and the crop, read and written. From PhotoCraft. - [`craft-codepage`](crates/codepage/README.md): legacy 8-bit code pages, one table each: the single-byte Windows pages, Mac OS Roman and fifteen DOS pages, keyed by Windows code page number, with the RTF/Word font charsets. craft-rtf, craft-dxf and craft-mime decode through it. +- [`craft-color-ui`](crates/color-ui/README.md): colour picker, wells, swatch tables, ramps and the hex + field; the Color Picker dialog, droppers, eyedropper, samplers, screen picker, Color and Swatches + panels (`ui` feature); swatch files, the display transform and harmonies. - [`craft-crw`](crates/crw/README.md): clean-room Canon CRW (CIFF) raw decoder, from LightCraft: the heap container, the entropy coding derived by black-box analysis (frozen code tables), sensor black and white levels and as-shot white balance. The complete derivation record (plan, sources @@ -108,6 +116,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-docpath`](crates/docpath/src/lib.rs): decides whether a path or `file:` URL stored in a document may be opened. Paths stored in documents are followed only when they are local or on the document's own network share; other network paths, device paths and non-file URLs are refused. + `links` keeps a document's linked files: their status, the identity check, folder remaps and + folder searches. - [`craft-dpx`](crates/dpx/src/lib.rs): DPX (SMPTE ST 268) and Kodak Cineon frames, from PhotoCraft, FilmCraft and EffectCraft: header fields and code values at 8, 10, 12 and 16 bits in both byte orders, filled and packed, RGB, RGBA, ABGR, luma and Y'CbCr descriptors, and a writer for both @@ -124,6 +134,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-docx`](crates/docx/README.md): DOCX (WordprocessingML) read and written on `craft-wordmodel`, with Word XML (Flat OPC) and Word 2003 XML, password-protected packages and Restrict Editing hashes. WordCraft's DOCX crate on `craft-opc`, `craft-xml` and `craft-offcrypto`. +- [`craft-draw`](crates/draw/README.md): vector and shape tools; the gradient editor and + on-canvas gradient overlay, the pen and path overlays, the crop frame and perspective crop, and the + free transform box and fields (`ui` feature). - [`craft-dxf`](crates/dxf/src/lib.rs): DXF tag reader and writer, from CADCraft: ASCII and binary DXF as (group code, value) tags, split into sections and entities, with pre-2007 code pages and version detection, and written back; and `model`, the drawing above the tags (header @@ -158,14 +171,20 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit decoding (scan lines, tiles, every compression of the `exr` crate) and writing. - [`craft-flags`](crates/flags/README.md): Feature flags shared by the Craft apps and the ArtCraft Launcher: one per-user `ArtCraft/flags.toml`, a `CRAFT_FLAGS` override, every flag off by default (`AI-MCP`, `AI-MODELS`). - [`craft-flow`](crates/flow/README.md): the flow model every text format maps to (paragraphs with a kind, lists and formatted spans; tables; pictures, fields, notes, equations), converted to and from a craft-wordmodel `Document`. +- [`craft-imaging`](crates/imaging/README.md): raster image editing; the scope counting (every + target) and, with the `ui` feature, the warp grid, the levels editor, the Channels panel and the + scope panel with its clipping overlay. - [`craft-font-catalog`](crates/font-catalog/README.md): the installed fonts on every platform (font folders, fontconfig and Flatpak host folders, CoreText, DirectWrite, the font store), lookup by family, style, localized, legacy, full and PostScript names, family loads shared between threads, and rescans when fonts are installed or removed. - [`craft-font-manager`](crates/font-manager/README.md): Craft Font Manager as a library: search and filters over the Google Fonts index, installed fonts by family, the font store interface, - and (`egui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab + and (`ui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab and the standalone app. +- [`craft-font-os-windows`](crates/font-os-windows/src/lib.rs): the Win32 calls `craft-font-store` + needs on Windows to make a font available to every app of the user (the per-user font + registry, `AddFontResourceW`, `WM_FONTCHANGE`), behind a safe API. - [`craft-font-store`](crates/font-store/README.md): the suite's font store: the pinned Google Fonts and Noto indexes plus indexes the user adds (never curated), exact lookup by family and style or PostScript name, and installs from each source's URLs (jsDelivr, then raw GitHub) @@ -224,13 +243,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit CCITT Group 3 and 4 decoding and Group 4 encoding, JBIG2 decoding and lossless encoding. Every decoder is bounded and returns its partial output on damage. From PdfCraft; a PDF filter chain is built on it in `craft-pdf`. -- [`craft-timeline`](crates/timeline/README.md): editorial timeline interchange: exact media time and SMPTE timecode, import/export reports, media path and `file://` URL handling, Avid Log Exchange (ALE) and CMX 3600 EDL documents, format detection. From FilmCraft. - [`craft-time`](crates/time/README.md): exact rational ticks and SMPTE time across media, with a `soundcraft` compatibility module retaining SoundCraft's sample-index timebase, tempo maps, grids and session serialization semantics. - [`craft-scraft-format`](crates/scraft-format/README.md): SoundCraft's typed `.scraft` session schema, versioned reader/writer, hostile-input validation, and `.scraftz` bundle reader/writer. Engine and UI mapping stays in SoundCraft. -- [`craft-metadata`](crates/metadata/README.md): photo metadata, from LightCraft: EXIF (read and write, - maker-note lens and focus point, every tag by name), IPTC-IIM, XMP packets (read, write, and a merge - that keeps what another program wrote), GPX track logs, and the blocks that carry them in JPEG, PNG, - WebP, TIFF-based, RAF and CR3 files. One `Metadata` model for all of them. Built on `craft-tiff`. - [`craft-tiff`](crates/tiff/README.md): TIFF and BigTIFF IFD reader and writer, from LightCraft: every field type, the IFD chain, SubIFDs and Exif/GPS/Interop pointer IFDs, maker-note IFDs (Canon, Nikon, Sony, Fujifilm, Olympus, Panasonic, Pentax), strip and tile layout. Bounded and @@ -266,6 +280,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit scopes, conflicts, user overrides stored through craft-settings and import of other applications' shortcut sets. Command catalogs, file readers and the shortcut editor UI stay in each app. +- [`craft-layers`](crates/layers/README.md): the Layers panel over the app's `LayerTree`: rows + with thumbnails and masks, blend, opacity, lock and fill rows, the filter bar, Layers Panel + Options, drag and drop, and events the app applies with its own commands and undo. UI-only. - [`craft-audio`](crates/audio/README.md): audio file I/O and codecs (WAV, AIFF, FLAC, AAC, Opus, AC-3/E-AC-3, MP1/MP2, MP3 encoding), streaming and seeking, and packet decoding for any demuxer. See its README for formats and features. @@ -310,6 +327,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-opc`](crates/opc/README.md): Open Packaging Conventions, the ZIP container of DOCX, XLSX and PPTX files: bounded readers (every part up front, or on demand), part names, relationships, content types and a deterministic package writer. What the parts hold stays with each format's crate. +- [`craft-pages`](crates/pages/README.md): pages for the document apps: page layout and fit modes, + paper sizes and page setup, page ranges and numbering; with `ui`, the page view, thumbnails, Page + Setup, margin handles, header and footer zones, text selection, reading view, page list and + document tables. The document, its layout and rendering stay in each app. - [`craft-pcraft-format`](crates/pcraft-format/README.md): the envelope of PhotoCraft's `.pcraft` bundle: `Manifest` with the document as a type parameter, `TileRef`, the entry paths, the manifest decode limits and the migration runner. The document model stays in PhotoCraft. @@ -339,7 +360,6 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit craft-i18n's `language-data/`, embedded at build time from `CRAFT_I18N_DIR`: English and the carry-over locales by default, the set `CRAFT_PROOF_EMBED` names otherwise (`en` for English only); other languages come from installed Language packs. - - [`craft-pst`](crates/pst/README.md): Outlook personal folders files (`.pst`, [MS-PST]) read over any `Read + Seek`, from MailCraft: the node database, property and table contexts, folders, messages, recipients, attachments, attached messages and named properties, ANSI and Unicode, encoded or not, @@ -348,11 +368,15 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`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-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). -- [`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. Policy in [docs/settings-storage.md](docs/settings-storage.md). + +- [`craft-review`](crates/review/README.md): review: the comments panel, comment pins, thread + popover and composer, Acrobat's annotation tool, the signature pad, version history and the + 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-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. @@ -370,6 +394,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency. - [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`, `color` and `write`; re-exports them for existing users. +- [`craft-table`](crates/table/README.md): spreadsheet widgets: the cell grid with Excel's + keys, outline bands, the PivotTable field list, the condition builder, chart painting, slicers, + reference picking, selection statistics, error tags and filter buttons (`ui` feature). - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test @@ -379,18 +406,22 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns - for 47 more languages (one cargo feature each). + for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and + Paragraph controls, text style panels and Check Spelling dialog, and the paged-text controls + (ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find` + (regex) are features. - [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are bounded by `Limits`. From MaterialCraft. -- [`craft-ui`](crates/ui/README.md): SVG catalogs, icon buttons, tabs, pane controls, transactional docking, print settings and theme helpers for egui frontends; -- [`craft-ai`](crates/ai/README.md) *(spec)*: AI provider abstraction — BYO API keys (OpenAI-compatible) and one-click curated local models with capability probing, resumable checksummed downloads, and document segmentation that protects markup while translating prose; - assets, themes, localization and command handling stay in each app. Requires Rust 1.95 or later. -- [`craft-vcard`](crates/vcard/README.md): vCard contacts, from MailCraft: vCard 2.1, 3.0 and 4.0 read - (legacy character sets, quoted-printable, labels and Apple label groups, `KEY` certificates and - OpenPGP public keys), vCard 3.0 written. Bounded and panic-free on hostile input. The mapping onto - an app's contact type stays in each app. - +- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates, + timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE, + CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel, + ruler, clips, keyframe lanes, graph editor, transport, timecode fields, preview, overview and + render queue (`ui` feature). +- [`craft-metadata`](crates/metadata/README.md): photo metadata, from LightCraft: EXIF (read and write, + maker-note lens and focus point, every tag by name), IPTC-IIM, XMP packets (read, write, and a merge + that keeps what another program wrote), GPX track logs, and the blocks that carry them in JPEG, PNG, + WebP, TIFF-based, RAF and CR3 files. One `Metadata` model for all of them. Built on `craft-tiff`. - [`craft-vectorcraft-format`](crates/vectorcraft-format/README.md): the envelope of VectorCraft's `.vectorcraft` file: its members, versions, embedded images and the data after the JSON, with the document as a type parameter. The document and its migrations stay in VectorCraft. @@ -421,12 +452,47 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-xcf`](crates/xcf/README.md): GIMP XCF images (`.xcf`, `.xcf.gz`), read: header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, under a caller's byte budget. From PhotoCraft. - [`craft-xml`](crates/xml/README.md): bounded XML for hostile input: an owned element tree with limits on size, depth, nodes and attributes, streaming of repeated elements, namespace handling (as written, by local name, or canonical prefixes by URI), escaping and a writer. No DTDs and no entity expansion. - [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. With the `lenient` feature, also a reader of the raw bytes without the `zip` crate, from Craft Anything, for inspectors that must describe damaged archives rather than refuse them: the central-directory listing with ZIP64, prepended-stub and multi-volume checks, CP437 and Info-ZIP Unicode Path names, and entry reads (stored, DEFLATE, and bzip2, LZMA, XZ and Zstandard behind `lenient-*` features) checked against the declared size and CRC-32. -- [Shared UI component audit](docs/ui-components-audit.md): source inventory, extraction priorities - and compatibility boundaries across the Craft suite. -- [Theme infrastructure](docs/theme-infrastructure.md): eight-app comparison and the small shared - widget-state styling boundary. -- [Panel docking](docs/ui-docking.md): validated panel moves, floating groups, workspace adapters - and an optional egui docking surface. + +## Craft framework + +The shared UI layer of the Craft apps: the design system, the UI library on egui, the host convention and the +feature families above. Assets, localization and commands stay in each app. Requires Rust 1.95 or later. Design and +architecture: [docs/craft-framework.md](docs/craft-framework.md). + +- [`craft`](crates/craft/README.md): the facade: one dependency, one pin and one import root for an app, with a + feature per crate. +- `craft-ui`: the UI library's facade, which re-exports its six crates under one root (`craft_ui::…`): + - `craft-ui-contract`: runtime, style, fonts, primitives, the component contract, layout and the test kit; + - `craft-ui-widgets`: the components (buttons, choices, fields, lists, menus, pickers, tabs, tables, bars); + - `craft-ui-panels`: sections, dialogs, docking and rails; + - `craft-ui-canvas`: the canvas, its tools and controls, and the full-window dialogs; + - `craft-ui-patterns`: ready-made dialogs, presets, preferences and dock areas; + - `craft-ui-shell`: the app shell, the title bar and the eframe entry point. +- [`craft-vcard`](crates/vcard/README.md): vCard contacts, from MailCraft: vCard 2.1, 3.0 and 4.0 read + (legacy character sets, quoted-printable, labels and Apple label groups, `KEY` certificates and + OpenPGP public keys), vCard 3.0 written. Bounded and panic-free on hostile input. The mapping onto + an app's contact type stays in each app. +- `craft-ui-macros`: the derives and macros of the library (`Component`, `Props`, `ComponentStyle`, `Pattern`, + `CommandSet`, words, stories and trials); use them through `craft-ui`. +- `craft-behavior`: the behaviour cores with no egui: press lifecycle, value drags, navigation, item layouts, edit + events and the dock model. +- [`craft-theme`](crates/theme/README.md) and [`craft-theme-store`](crates/theme-store/README.md): the token model, + the built-in themes and the suite's theme selection ([docs/suite-themes.md](docs/suite-themes.md)). +- [`craft-host`](crates/host/README.md): the services an app installs once and every feature reads. +- `craft-win32`: the window-procedure and window-handle Win32 calls that need `unsafe`, behind a safe API. +- Tools, not shipped in apps: `craft-ui-gallery` (the story viewer), `story-render` (one component's stories to + PNG files), [`craft-design-lint`](crates/design-lint/README.md), `craft-ui-bench`, `craft-ui-test-kit`. + +Framework docs: + +- [Craft framework](docs/craft-framework.md): the design, installation, architecture, design system, foundations, + components, accessibility, tests, and the migration and landing plan. +- [Development workflow](docs/development.md): the `cl` commands, the one fixed feature set, what not to run + locally, CI coverage, the profiles, the job pool and what a new worktree's first build costs. +- [Writing a component](docs/authoring.md), the [component index](docs/components-index.md), the + [contract API](docs/contract-api.md) and the [glossary](docs/glossary.md). +- [Docking](docs/ui-docking.md): the dock model, `DockArea`, `SplitArea` and `PaneArea`. +- [Dialogs](docs/ui-dialogs.md): `Dialog`, `DialogHost`, the dialog stack and the standard prompts. ## License and credits diff --git a/clippy.toml b/clippy.toml index 8f54197d87..d0b9b63ca0 100644 --- a/clippy.toml +++ b/clippy.toml @@ -4,5 +4,5 @@ allow-panic-in-tests = true allow-indexing-slicing-in-tests = true cognitive-complexity-threshold = 30 disallowed-types = [ - { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, + { path = "egui::ComboBox", reason = "use craft_ui::controls::Select: egui's combo box menu can't grow back while open (egui#5225)" }, ] diff --git a/crates/aaf/README.md b/crates/aaf/README.md index 7d3d447674..12f2839ba6 100644 --- a/crates/aaf/README.md +++ b/crates/aaf/README.md @@ -5,7 +5,7 @@ composition model. | Module | What | |---|---| -| `model` | `Document`: compositions (tracks of fillers, source clips and overlapping transitions; clip gain, constant or keyframed; markers; start timecode), nested compositions, and the media `Source`s they reference (file path or embedded PCM, picture size and rate, sound channels / rate / bits, start timecode, markers). Times are exact `craft_timeline::time::Tick`s. | +| `model` | `Document`: compositions (tracks of fillers, source clips and overlapping transitions; clip gain, constant or keyframed; markers; start timecode), nested compositions, and the media `Source`s they reference (file path or embedded PCM, picture size and rate, sound channels / rate / bits, start timecode, markers). Times are exact `craft_timeline::Tick`s. | | `aaf` | `read`, `write`, `sniff`: AAF Edit Protocol in structured storage (`craft-cfb`). | | `omf` | `read`, `write`, `sniff`: OMF Interchange 2.0 in a Bento container. Sound only. | diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index b9638fffbb..f7a061ccb3 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -1,7 +1,7 @@ //! AAF (Advanced Authoring Format) import and export, following the AAF Edit Protocol. //! //! Written from the public AMWA specifications: *AAF Object Specification v1.1*, *AAF Low-Level -//! Container Specification v1.0.1* (structured storage mapping, see [`store`]) and *AAF Edit +//! Container Specification v1.0.1* (structured storage mapping) and *AAF Edit //! Protocol v1.0*; the container is Microsoft's Compound File Binary format ([`craft_cfb`]). //! //! A written file holds one top-level **CompositionMob** (Edit Protocol usage code @@ -49,6 +49,7 @@ use crate::{Identity, Report, Result}; /// How to write an AAF file. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WriteOptions<'a> { + /// Who the file says made it. pub identity: Identity<'a>, /// Write 512-byte sectors (compound file version 3) instead of 4096-byte sectors. pub small_sectors: bool, diff --git a/crates/aaf/src/aaf/linked_audio.rs b/crates/aaf/src/aaf/linked_audio.rs index cf291d69dc..7fd48f9a7a 100644 --- a/crates/aaf/src/aaf/linked_audio.rs +++ b/crates/aaf/src/aaf/linked_audio.rs @@ -5,7 +5,9 @@ use super::ids::{cls, pid}; /// The two audio descriptor classes commonly attached to an external WAV source. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DescriptorKind { + /// A WAVEDescriptor (`.wav` with a RIFF header). Wave, + /// A PCMDescriptor (raw PCM samples). Pcm, } @@ -24,16 +26,22 @@ impl DescriptorKind { /// One property from an already framed and caller-validated object. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DescriptorProperty<'a> { + /// The object has no such property. Missing, + /// The property is stored in a form other than a plain data value. OtherForm, + /// The property's raw value bytes. Data(&'a [u8]), } /// Why a descriptor field is unavailable. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DescriptorFieldError { + /// The descriptor has no such property. Missing, + /// The property is stored in a form other than a plain data value. OtherForm, + /// The value is shorter than the field's type. Truncated, } diff --git a/crates/aaf/src/aaf/properties.rs b/crates/aaf/src/aaf/properties.rs index 5db9619aca..e9e6d45562 100644 --- a/crates/aaf/src/aaf/properties.rs +++ b/crates/aaf/src/aaf/properties.rs @@ -3,17 +3,24 @@ /// One indexed AAF property. The payload borrows the original stream. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Property<'a> { + /// The property ID (pid). pub id: u16, + /// The stored form of the value, as the index records it. pub form: u16, + /// The value's bytes. pub payload: &'a [u8], } /// Malformed property-stream framing. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PropertyError { + /// The stream ends before its 4-byte header. ShortHeader, + /// The header's byte-order mark is not little-endian (0x4c). UnsupportedByteOrder, + /// The stream ends inside the property index. TruncatedIndex, + /// A property's length runs past the end of the stream. TruncatedValue, } diff --git a/crates/aaf/src/aaf/read.rs b/crates/aaf/src/aaf/read.rs index 9739f87baa..fb5d44539c 100644 --- a/crates/aaf/src/aaf/read.rs +++ b/crates/aaf/src/aaf/read.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; -use craft_timeline::time::{FrameRate, Tick}; +use craft_timeline::{FrameRate, Tick}; use super::ids::{cls, ddef, def, pid}; use super::store::{self, Auid, Obj, Value, rational_of, utf16_of}; diff --git a/crates/aaf/src/aaf/tests.rs b/crates/aaf/src/aaf/tests.rs index 34eb2bbb35..a8b6bbc050 100644 --- a/crates/aaf/src/aaf/tests.rs +++ b/crates/aaf/src/aaf/tests.rs @@ -3,7 +3,7 @@ use std::collections::HashSet; -use craft_timeline::time::FrameRate; +use craft_timeline::FrameRate; use super::ids::{self, cls, ddef, def, path, pid}; use super::store::{self, Obj, Value}; @@ -517,7 +517,7 @@ fn sound_source_offsets_use_audio_sample_rate_on_disk() { _ => None, }) .unwrap(); - assert_eq!(clip.start, craft_timeline::time::FrameRate::FPS_25.tick_of(10)); + assert_eq!(clip.start, craft_timeline::FrameRate::FPS_25.tick_of(10)); } #[test] diff --git a/crates/aaf/src/aaf/write.rs b/crates/aaf/src/aaf/write.rs index 1fcc6a3320..d43d58a8ac 100644 --- a/crates/aaf/src/aaf/write.rs +++ b/crates/aaf/src/aaf/write.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; -use craft_timeline::time::{FrameRate, Tick}; +use craft_timeline::{FrameRate, Tick}; use super::ids::{META_DICTIONARY, ROOT, cls, ddef, def, path, pid}; use super::store::{self, Auid, Obj, Value, rational, utf16z}; diff --git a/crates/aaf/src/lib.rs b/crates/aaf/src/lib.rs index 4968c5b39b..77a6e190f4 100644 --- a/crates/aaf/src/lib.rs +++ b/crates/aaf/src/lib.rs @@ -4,7 +4,7 @@ //! //! - [`model`]: a [`model::Document`] of compositions (tracks of fillers, source clips and //! overlapping transitions, with clip gain and markers) and the media sources they reference, -//! with exact times ([`craft_timeline::time::Tick`]). +//! with exact times ([`craft_timeline::Tick`]). //! - [`aaf`]: Advanced Authoring Format, Edit Protocol, in structured storage (`craft-cfb`). //! - [`omf`]: OMF Interchange 2.0 in a Bento container; sound only. //! @@ -19,6 +19,7 @@ //! //! Input is untrusted: a damaged or crafted file gives an [`Error`] or a [`Report`] entry, never //! a panic, a hang or an allocation sized by a count in the file. +#![warn(missing_docs)] pub mod aaf; pub mod model; @@ -40,7 +41,12 @@ pub use craft_timeline::time; pub enum Error { /// The bytes are not a readable document of the format. #[error("{format} parse error: {message}")] - Parse { format: &'static str, message: String }, + Parse { + /// The format that failed to parse. + format: &'static str, + /// What was wrong. + message: String, + }, /// The document has no composition. #[error("the document contains no timeline")] Empty, @@ -49,15 +55,19 @@ pub enum Error { Other(String), } +/// `Result` with this crate's [`Error`]. pub type Result = std::result::Result; /// Who a written file says made it (the AAF `Identification` object, the OMF `IDNT` object). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Identity<'a> { + /// The company that made the product. pub company: &'a str, + /// The product name. pub product: &'a str, /// The product's version, as text. pub version: &'a str, + /// The platform the product ran on. pub platform: &'a str, /// AAF `ProductID`: an AUID naming the product. pub product_id: [u8; 16], diff --git a/crates/aaf/src/model.rs b/crates/aaf/src/model.rs index e6bc791402..e017840942 100644 --- a/crates/aaf/src/model.rs +++ b/crates/aaf/src/model.rs @@ -7,12 +7,14 @@ //! mobs and file source mobs: here, a [`Source`] per essence, grouped into one media item by its //! key. All times are ticks; the format serialisers convert to and from edit units. -use craft_timeline::time::{FrameRate, TICKS_PER_SECOND, Tick}; +use craft_timeline::{FrameRate, TICKS_PER_SECOND, Tick}; /// Picture or sound. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum CKind { + /// Moving or still images. Picture, + /// Audio. Sound, } @@ -21,46 +23,63 @@ pub enum CKind { pub struct Document { /// The top-level compositions. pub compositions: Vec, + /// The essences the compositions reference. pub sources: Vec, /// Compositions that are only used inside others (nested sequences); a [`Source`] refers to /// one by its index here. They may nest further. pub nested: Vec, } -/// How a nested sequence is written. Premiere Pro writes one as a composition of its own in AAF -/// (clips refer to it the way they refer to media) and renders its sound in OMF, which has no +/// One composition: its tracks, markers and timing. #[derive(Clone, Debug, PartialEq)] pub struct Composition { + /// The name. pub name: String, /// AAF CompositionMob identifier as 64 lowercase hexadecimal digits. OMF has no equivalent. /// It is a read identity for applications that let a user choose among compositions; writers /// generate fresh format identifiers and do not preserve it. pub aaf_mob_id: Option, + /// The edit rate. pub rate: FrameRate, + /// Sound: samples per second. pub sample_rate: u32, + /// Picture: width in pixels. pub width: u32, + /// Picture: height in pixels. pub height: u32, + /// Start timecode in frames at `rate`. pub start_tc: i64, + /// Whether the timecode is drop-frame. pub drop: bool, + /// The tracks, picture and sound. pub tracks: Vec, + /// The markers, at times in the composition. pub markers: Vec, } +/// One track of a composition. #[derive(Clone, Debug, PartialEq)] pub struct CTrack { + /// Whether the track carries picture or sound. pub kind: CKind, + /// The name. pub name: String, /// Physical track number (1-based, per kind). pub number: u32, /// Sound: channels of the track (1 mono, 2 stereo, 6 5.1). pub channels: u32, + /// The segments in order. pub items: Vec, } +/// One segment of a track. #[derive(Clone, Debug, PartialEq)] pub enum CItem { + /// Nothing for the given length. Filler(Tick), + /// A stretch of a source. Clip(CClip), + /// A transition overlapping its neighbours. Transition(CTransition), } @@ -75,30 +94,39 @@ impl CItem { } } +/// A clip: a stretch of one source on a track. #[derive(Clone, Debug, PartialEq)] pub struct CClip { + /// The length on the track. pub len: Tick, /// Index into [`Document::sources`]. pub source: usize, /// Source (file) time of the segment's first frame. pub start: Tick, + /// Sound: the clip gain, if any. pub gain: Option, + /// The name. pub name: String, } /// Clip gain (linear amplitude). #[derive(Clone, Debug, PartialEq)] pub enum Gain { + /// One gain for the whole segment. Constant(f64), /// Points at offsets from the segment start; `linear` false = hold (step) interpolation. Varying { + /// Whether the points join by straight lines rather than steps. linear: bool, + /// The gain at each offset. points: Vec<(Tick, f64)>, }, } +/// A transition between the segments before and after it. #[derive(Clone, Debug, PartialEq)] pub struct CTransition { + /// The length on the track. pub len: Tick, /// Where the cut lies, from the transition start. pub cut: Tick, @@ -109,12 +137,18 @@ pub struct CTransition { pub effect: String, } +/// A marker or note at a time in a composition or source. #[derive(Clone, Debug, PartialEq)] pub struct CMarker { + /// Where it starts. pub start: Tick, + /// How long it lasts; zero for a point. pub duration: Tick, + /// The name. pub name: String, + /// The free-text comment. pub comment: String, + /// The colour name the writing application gave it. pub color: Option, } @@ -124,8 +158,11 @@ pub struct CMarker { pub struct Source { /// Groups the sources of one media item (one master mob). pub key: String, + /// The name. pub name: String, + /// Whether the essence is picture or sound. pub kind: CKind, + /// The file the essence lives in; `None` for embedded data. pub path: Option, /// Sound: the (0-based) channel of the file this source exposes (broken out to mono), or /// `None` for all of them. @@ -134,19 +171,27 @@ pub struct Source { pub channels: u32, /// Sound: channels of the file / embedded data. pub file_channels: u32, + /// Picture: width in pixels. pub width: u32, + /// Picture: height in pixels. pub height: u32, /// Picture: the frame rate of the media. pub frame_rate: FrameRate, + /// Sound: samples per second. pub sample_rate: u32, + /// Sound: bits per sample. pub bits: u16, + /// The length of the essence. pub length: Tick, /// Media time of the essence's time 0 (trimmed / consolidated essence). pub offset: Tick, /// Start timecode in frames at `tc_rate`. pub start_tc: Option, + /// The rate `start_tc` counts in. pub tc_rate: FrameRate, + /// Essence data stored in the file itself. pub embedded: Option>, + /// Markers on the source, at times in the essence. pub markers: Vec, /// Not media but a nested composition: its index in [`Document::nested`]. `start` of a clip /// that uses it is a time in that composition. diff --git a/crates/aaf/src/omf.rs b/crates/aaf/src/omf.rs index bbd2e85713..5566be9d24 100644 --- a/crates/aaf/src/omf.rs +++ b/crates/aaf/src/omf.rs @@ -1,7 +1,7 @@ //! OMF Interchange 2.0 for audio post: written, and the same structures read. //! //! Written from the public *OMF Interchange Specification Version 2.0* (Avid Technology, 1995/97) -//! and Apple's *Bento Specification* revision 1.0d5 for the container ([`bento`]). +//! and Apple's *Bento Specification* revision 1.0d5 for the container. //! //! The file holds a composition mob (`CMOB`) with a timecode slot and one sound slot per audio //! track (one per channel when broken out to mono): sequences (`SEQU`) of fillers (`FILL`), source @@ -33,7 +33,7 @@ pub fn write(doc: &Document, identity: &Identity<'_>, report: &mut Report) -> Re write::write(doc, identity, report) } -/// Read an OMF 2.0 file (as written by [`write`] and by applications using the same structures). +/// Read an OMF 2.0 file (as written by [`fn@write`] and by applications using the same structures). pub fn read(bytes: &[u8], report: &mut Report) -> Result { read::read(bytes, report) } diff --git a/crates/aaf/src/omf/bento.rs b/crates/aaf/src/omf/bento.rs index 171196fe16..20069826f4 100644 --- a/crates/aaf/src/omf/bento.rs +++ b/crates/aaf/src/omf/bento.rs @@ -35,7 +35,9 @@ use std::collections::{BTreeMap, HashMap}; +/// The eight-byte magic number that opens a Bento container. pub const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7]; +/// The size in bytes of one label in the container table. pub const LABEL_SIZE: usize = 24; // standard object ids @@ -97,6 +99,7 @@ impl Default for Writer { } impl Writer { + /// An empty writer that assigns user object ids from the first free id. pub fn new() -> Writer { Writer { data: Vec::new(), names: HashMap::new(), next: MIN_USER_ID, entries: Vec::new() } } @@ -114,14 +117,17 @@ impl Writer { id } + /// The id of the global property named `name`, assigned on first use. pub fn property(&mut self, name: &str) -> u32 { self.named(GLOBAL_PROP_NAME, name) } + /// The id of the global type named `name`, assigned on first use. pub fn type_id(&mut self, name: &str) -> u32 { self.named(GLOBAL_TYPE_NAME, name) } + /// Allocates the next free user object id. pub fn new_object(&mut self) -> u32 { let id = self.next; self.next += 1; @@ -156,6 +162,7 @@ impl Writer { self.entries.push((obj, OBJ_REFERENCES, TYPE_7BIT_ASCII, vec![seg])); } + /// Finishes the container and returns its bytes. pub fn finish(mut self) -> Vec { let seed = self.next; self.entries.push((TOC_OBJECT, TOC_SEED, TOC_TYPE, vec![Seg::Imm(seed.to_be_bytes().to_vec())])); @@ -245,6 +252,7 @@ impl<'a> Container<'a> { self.objects.keys().copied() } + /// Opens `data` as a Bento container, or says why it is not one. pub fn open(data: &'a [u8]) -> Result, String> { if !sniff(data) { return Err("no Bento label at the end of the file".into()); @@ -362,11 +370,13 @@ impl<'a> Container<'a> { Ok(out) } + /// The id registered for `name`, if any. pub fn id_of(&self, name: &str) -> Option { self.by_name.get(name).copied() } #[allow(dead_code)] + /// The name registered for `id`, if any. pub fn name_of(&self, id: u32) -> Option<&str> { self.names.get(&id).map(String::as_str) } diff --git a/crates/aaf/src/omf/read.rs b/crates/aaf/src/omf/read.rs index 9e892a0ce8..f825e9e609 100644 --- a/crates/aaf/src/omf/read.rs +++ b/crates/aaf/src/omf/read.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; -use craft_timeline::time::{FrameRate, Tick}; +use craft_timeline::{FrameRate, Tick}; use super::bento::Container; use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks}; diff --git a/crates/aaf/src/omf/write.rs b/crates/aaf/src/omf/write.rs index 7559948046..e4b638f879 100644 --- a/crates/aaf/src/omf/write.rs +++ b/crates/aaf/src/omf/write.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; -use craft_timeline::time::Tick; +use craft_timeline::Tick; use super::bento; use crate::model::{CItem, CKind, Document, Gain, Source, ticks_to_units}; diff --git a/crates/aaf/src/roundtrip_tests.rs b/crates/aaf/src/roundtrip_tests.rs index 7ba6e993a6..a84a843198 100644 --- a/crates/aaf/src/roundtrip_tests.rs +++ b/crates/aaf/src/roundtrip_tests.rs @@ -1,6 +1,6 @@ //! Documents written and read back, in both formats; damaged files. -use craft_timeline::time::{FrameRate, Tick}; +use craft_timeline::{FrameRate, Tick}; use crate::model::{CItem, CKind, CMarker, Composition, Document, Gain}; use crate::testdoc::{IDENTITY, pcm_ramp, picture_and_sound, sound_only}; diff --git a/crates/aaf/src/testdoc.rs b/crates/aaf/src/testdoc.rs index c2740e1e7e..16c3209505 100644 --- a/crates/aaf/src/testdoc.rs +++ b/crates/aaf/src/testdoc.rs @@ -1,7 +1,7 @@ //! Documents the tests write: what an editor's two-clip sequence with a dissolve looks like in //! the model. -use craft_timeline::time::{FrameRate, Tick}; +use craft_timeline::{FrameRate, Tick}; use crate::Identity; use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source}; diff --git a/crates/aep/src/index.rs b/crates/aep/src/index.rs index 76d5430dac..6137d5c268 100644 --- a/crates/aep/src/index.rs +++ b/crates/aep/src/index.rs @@ -69,7 +69,7 @@ impl<'a> Entry<'a> { /// An entry of an index whose bytes are still being written (the `.aepx` reader decodes into a /// buffer that grows, so it keeps positions, not slices): the body is `start..start + len` of -/// that buffer. The fields are those of [`Entry`]; [`TreeIndex::from_drafts`] turns the list +/// that buffer. The fields are those of `Entry`; [`TreeIndex::from_drafts`] turns the list /// into an index once the buffer is final. #[derive(Debug, Clone, Copy)] pub struct Draft { @@ -140,7 +140,7 @@ impl<'a> TreeIndex<'a> { /// The index of the entries `drafts` (in depth-first order, see [`Draft`]) whose bodies and /// trailer are ranges of `buffer`. A range outside `buffer` reads as empty. The list is turned - /// into entries; a [`Draft`] and an [`Entry`] have the same size and alignment, so the standard + /// into entries; a [`Draft`] and an `Entry` have the same size and alignment, so the standard /// library reuses the list's allocation for them. pub fn from_drafts(buffer: &'a [u8], drafts: Vec, trailer: (usize, usize)) -> Self { let slice = |start: usize, len: usize| start.checked_add(len).and_then(|end| buffer.get(start..end)).unwrap_or(&[]); diff --git a/crates/aep/src/textdoc.rs b/crates/aep/src/textdoc.rs index 1e7569b677..fb0003edc4 100644 --- a/crates/aep/src/textdoc.rs +++ b/crates/aep/src/textdoc.rs @@ -549,7 +549,7 @@ pub struct TextDocument { /// run from the sampled defaults). pub incomplete_runs: usize, /// Style slots that are not decoded and differ from the sampled default (`"68"`, ...), each - /// once and at most [`MAX_UNDECODED_FIELDS`]; empty for every synthetic sample. + /// once and at most `MAX_UNDECODED_FIELDS`; empty for every synthetic sample. pub undecoded_style_fields: Vec, /// Paragraph slots that are not decoded and differ from the sampled default. pub undecoded_paragraph_fields: Vec, diff --git a/crates/aep/src/typed.rs b/crates/aep/src/typed.rs index 9334b45cc7..f6888f6bff 100644 --- a/crates/aep/src/typed.rs +++ b/crates/aep/src/typed.rs @@ -453,7 +453,7 @@ pub struct KeyList<'f> { } /// What the property header says about its keyframe records: how many value components each -/// record holds and which of the two record templates applies (see [`KeyframeKind`]). +/// record holds and which of the two record templates applies (see `KeyframeKind`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct KeyLayout { /// `tdb4` byte 3. diff --git a/crates/aep/src/write.rs b/crates/aep/src/write.rs index cadd84f0d0..f64ef68cdc 100644 --- a/crates/aep/src/write.rs +++ b/crates/aep/src/write.rs @@ -5,7 +5,7 @@ use std::io::Write; use crate::chunk::{AepFile, Body, Chunk}; use crate::error::AepError; -/// Deepest tree [`write`] accepts (a hand-built tree may be deeper than any parsed one). +/// Deepest tree [`fn@write`] accepts (a hand-built tree may be deeper than any parsed one). const MAX_WRITE_DEPTH: usize = 256; /// Serialises `file`: `RIFX`, the recomputed container size, `Egg!`, the chunks and the trailer. @@ -39,10 +39,10 @@ pub fn write(file: &AepFile<'_>) -> Result, AepError> { Ok(out) } -/// Like [`write`], into any writer. +/// Like [`fn@write`], into any writer. /// /// # Errors -/// A size or depth error of [`write`] becomes `ErrorKind::InvalidData`; otherwise I/O errors. +/// A size or depth error of [`fn@write`] becomes `ErrorKind::InvalidData`; otherwise I/O errors. pub fn write_to(file: &AepFile<'_>, w: &mut impl Write) -> std::io::Result<()> { let bytes = write(file).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; w.write_all(&bytes) diff --git a/crates/ai-core/Cargo.toml b/crates/ai-core/Cargo.toml index 780f9f0e96..20684f4afb 100644 --- a/crates/ai-core/Cargo.toml +++ b/crates/ai-core/Cargo.toml @@ -1,4 +1,5 @@ [package] +autotests = false name = "craft-ai-core" description = "Shared data model for AI connections, roles, requests and jobs across the Craft apps" version.workspace = true diff --git a/crates/ai-core/src/capability.rs b/crates/ai-core/src/capability.rs index 13f85c9344..11f1e8829d 100644 --- a/crates/ai-core/src/capability.rs +++ b/crates/ai-core/src/capability.rs @@ -36,11 +36,13 @@ impl CapabilityId { Ok(Self(s.to_owned())) } + /// Builds an id from a modality and a task token. Fails when `task` is not a valid token. pub fn new(modality: &Modality, task: &str) -> Result { validate_token(task)?; Ok(Self(format!("{}.{}", modality.as_str(), task))) } + /// The full `modality.task` text. pub fn as_str(&self) -> &str { &self.0 } @@ -51,6 +53,7 @@ impl CapabilityId { Modality::parse(head).unwrap_or_else(|_| Modality::Other(head.to_owned())) } + /// The task half, for example `inpaint` in `image.inpaint`. pub fn task(&self) -> &str { self.0.split_once('.').map_or("", |(_, t)| t) } @@ -117,50 +120,3 @@ pub const WELL_KNOWN: &[&str] = &[ pub fn well_known() -> Vec { WELL_KNOWN.iter().filter_map(|s| CapabilityId::parse(s).ok()).collect() } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn well_known_all_parse() { - assert_eq!(well_known().len(), WELL_KNOWN.len()); - } - - #[test] - fn splits_modality_and_task() { - let c = CapabilityId::parse("image.inpaint").unwrap(); - assert_eq!(c.modality(), Modality::Image); - assert_eq!(c.task(), "inpaint"); - } - - #[test] - fn open_set_accepts_new_modalities() { - let c = CapabilityId::parse("cad.explain").unwrap(); - assert_eq!(c.modality(), Modality::Other("cad".into())); - } - - #[test] - fn rejects_malformed() { - for bad in ["", "image", "image.", ".inpaint", "image.in.paint", "im age.x", "image.in/paint"] { - assert!(CapabilityId::parse(bad).is_err(), "{bad:?} should be rejected"); - } - } - - #[test] - fn modality_round_trips_known_and_unknown() { - for text in ["image", "audio", "hologram"] { - let m = Modality::parse(text).unwrap(); - assert_eq!(m.as_str(), text); - let back: Modality = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap(); - assert_eq!(m, back); - } - } - - #[test] - fn new_builds_from_parts() { - let c = CapabilityId::new(&Modality::Audio, "transcribe").unwrap(); - assert_eq!(c.as_str(), "audio.transcribe"); - assert!(CapabilityId::new(&Modality::Audio, "a.b").is_err()); - } -} diff --git a/crates/ai-core/src/conformance.rs b/crates/ai-core/src/conformance.rs index 40452f5bbf..9a792d9ad8 100644 --- a/crates/ai-core/src/conformance.rs +++ b/crates/ai-core/src/conformance.rs @@ -16,7 +16,9 @@ pub const MAX_POLLS: u32 = 1000; /// What a completed run produced. #[derive(Debug)] pub struct Completed { + /// The terminal state the job reached. pub state: JobState, + /// Every event the polls reported, in order. pub events: Vec, } diff --git a/crates/ai-core/src/connection.rs b/crates/ai-core/src/connection.rs index 2ae692d6ce..f8fb5e1c79 100644 --- a/crates/ai-core/src/connection.rs +++ b/crates/ai-core/src/connection.rs @@ -21,6 +21,7 @@ use crate::model::ModelInfo; pub enum Locality { /// Loopback server or in-process model: nothing leaves the machine. Local, + /// The model runs on another machine. Consent applies. Remote, } @@ -30,17 +31,22 @@ pub enum Locality { pub enum Auth { /// No credentials (a local model, an open local server). None, + /// Authenticates with a stored key, sent in a header (see `Connection::key_header`). ApiKey { + /// Locator of the key. secret: SecretRef, }, /// An official subscription route (for example the Codex app-server). `route` names it. Subscription { + /// Name of the subscription route. route: String, + /// Locator of the credential for the route. secret: SecretRef, }, } impl Auth { + /// The secret locator this authentication uses, or `None` when it needs no credentials. pub fn secret_ref(&self) -> Option<&SecretRef> { match self { Self::None => None, @@ -53,28 +59,38 @@ impl Auth { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Billing { + /// No charge. Free, /// Pay per use, billed separately. Metered, /// Covered by an existing subscription's allowance. SubscriptionAllowance, + /// The cost is not known. Unknown, } /// A saved connection. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Connection { + #[allow(missing_docs)] pub id: ConnectionId, + /// Name shown to the user. pub label: String, /// Which adapter talks to it, such as `http`, `openai`, `fal`, `comfyui`, `onnx`. pub provider: String, + /// Server address, such as `https://host:port`. `None` for an in-process or route-only connection. #[serde(default, skip_serializing_if = "Option::is_none")] pub endpoint: Option, + /// Whether data stays on this machine. `validate` checks it against `endpoint`. pub locality: Locality, + /// How the connection authenticates. pub auth: Auth, + /// Who pays for use. pub billing: Billing, + /// Models this connection offers. Ids must be unique. #[serde(default)] pub models: Vec, + /// When false, the connection is kept but not offered for use. Defaults to true. #[serde(default = "yes")] pub enabled: bool, /// Header that carries the key, for a server that does not use `Authorization: Bearer`. @@ -138,7 +154,9 @@ pub fn check_key_header(name: &str) -> Result<(), &'static str> { /// Why a connection was refused. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ConnectionError { + /// The provider name is not a valid id. Provider(IdError), + /// The endpoint cannot be parsed. Endpoint(IdError), /// Labelled `Local` but the endpoint is not loopback. LocalButNotLoopback, @@ -146,7 +164,9 @@ pub enum ConnectionError { RemoteButLoopback, /// No endpoint, labelled `Local`, yet it uses credentials. Such a route sends data away. LocalWithoutEndpointNeedsNoAuth, + /// The label is empty or only whitespace. EmptyLabel, + /// Two models share this id. DuplicateModel(String), /// A key header name that is not allowed, or a header named for a connection with no key. KeyHeader(&'static str), @@ -211,6 +231,7 @@ impl Connection { Ok(()) } + /// The model with this id, if the connection lists it. pub fn model(&self, id: &crate::ids::ModelId) -> Option<&ModelInfo> { self.models.iter().find(|m| &m.id == id) } @@ -234,89 +255,4 @@ pub(crate) mod fixtures { key_header: None, } } - - pub fn local(id: &str) -> Connection { - Connection { - endpoint: Some("http://127.0.0.1:8188".into()), - locality: Locality::Local, - auth: Auth::None, - billing: Billing::Free, - ..remote(id) - } - } -} - -#[cfg(test)] -mod tests { - use super::fixtures::{local, remote}; - use super::*; - - #[test] - fn good_connections_validate() { - assert!(remote("a").validate().is_ok()); - assert!(local("b").validate().is_ok()); - } - - #[test] - fn a_remote_host_cannot_be_labelled_local() { - let mut c = remote("a"); - c.locality = Locality::Local; - assert_eq!(c.validate(), Err(ConnectionError::LocalButNotLoopback)); - } - - #[test] - fn the_userinfo_trick_cannot_make_a_remote_host_local() { - let mut c = local("a"); - c.endpoint = Some("http://127.0.0.1@evil.example/".into()); - assert!(matches!(c.validate(), Err(ConnectionError::Endpoint(_)))); - } - - #[test] - fn loopback_labelled_remote_is_flagged() { - let mut c = local("a"); - c.locality = Locality::Remote; - assert_eq!(c.validate(), Err(ConnectionError::RemoteButLoopback)); - } - - #[test] - fn subscription_route_without_endpoint_cannot_be_local() { - let mut c = remote("codex"); - c.endpoint = None; - c.auth = Auth::Subscription { route: "codex-app-server".into(), secret: SecretRef::new("s").unwrap() }; - c.locality = Locality::Local; - assert_eq!(c.validate(), Err(ConnectionError::LocalWithoutEndpointNeedsNoAuth)); - c.locality = Locality::Remote; - assert!(c.validate().is_ok()); - } - - #[test] - fn in_process_model_can_be_local_without_endpoint() { - let mut c = local("onnx"); - c.endpoint = None; - assert!(c.validate().is_ok()); - } - - #[test] - fn duplicate_models_and_empty_labels_are_refused() { - let mut c = remote("a"); - let m = ModelInfo::new(crate::ids::ModelId::new("m").unwrap(), "M"); - c.models = vec![m.clone(), m]; - assert!(matches!(c.validate(), Err(ConnectionError::DuplicateModel(_)))); - let mut c = remote("b"); - c.label = " ".into(); - assert_eq!(c.validate(), Err(ConnectionError::EmptyLabel)); - } - - #[test] - fn serialized_form_holds_a_reference_not_a_secret() { - let json = serde_json::to_string(&remote("a")).unwrap(); - assert!(json.contains("\"secret\":\"secret-a\"")); - assert!(!json.to_lowercase().contains("sk-")); - } - - #[test] - fn json_round_trip() { - let c = remote("a"); - assert_eq!(serde_json::from_str::(&serde_json::to_string(&c).unwrap()).unwrap(), c); - } } diff --git a/crates/ai-core/src/consent.rs b/crates/ai-core/src/consent.rs index 2b6a860dee..99044c1520 100644 --- a/crates/ai-core/src/consent.rs +++ b/crates/ai-core/src/consent.rs @@ -24,27 +24,35 @@ use crate::request::Request; /// One thing a request sends. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct DisclosureItem { + /// The role the input plays in the request. pub role: InputRole, + /// The kind of data sent. pub kind: PayloadKind, + /// Size in bytes when known. pub bytes: Option, } /// What a request will send to a connection. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Disclosure { + /// The app that sends the request. pub app: AppId, + /// The connection the request goes to. pub connection: ConnectionId, /// What the request asks the connection to do. Consent is given per capability. pub capability: CapabilityId, + /// Whether the connection is local or remote. pub locality: Locality, /// `scheme://host[:port]`, or the route name when there is no endpoint. pub destination: String, + /// The inputs the request sends. pub items: Vec, /// Parameter names only, never values. pub param_names: Vec, } impl Disclosure { + /// Builds the disclosure for sending `request` from `app` through `connection`. pub fn for_request(app: &AppId, connection: &Connection, request: &Request) -> Self { let destination = connection .endpoint @@ -85,7 +93,9 @@ impl Disclosure { /// another's. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ConsentRecord { + /// The app that agreed. pub app: AppId, + /// The connection agreed to. pub connection: ConnectionId, /// The destination agreed to. A different destination needs fresh consent. pub destination: String, @@ -93,6 +103,7 @@ pub struct ConsentRecord { /// none and covers nothing, so the person is asked once more. #[serde(default)] pub capability: Option, + /// The kinds of data the agreement covers. pub kinds: Vec, /// Unix seconds. The agreement holds while the clock is before this; `None` holds until /// revoked. @@ -111,6 +122,7 @@ impl ConsentRecord { /// An app's saved agreements. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ConsentLedger { + /// The saved agreements. #[serde(default)] pub records: Vec, } @@ -165,6 +177,7 @@ impl ConsentLedger { } } + /// Removes every agreement the app has for the connection, whatever the destination or capability. pub fn revoke(&mut self, app: &AppId, connection: &ConnectionId) { self.records.retain(|r| !(&r.app == app && &r.connection == connection)); } @@ -174,7 +187,7 @@ impl ConsentLedger { mod tests { use super::*; use crate::capability::CapabilityId; - use crate::connection::fixtures::{local, remote}; + use crate::connection::fixtures::remote; use crate::payload::Payload; fn app() -> AppId { @@ -188,32 +201,6 @@ mod tests { .with_param("seed", 7.into()) } - #[test] - fn disclosure_lists_kinds_sizes_and_param_names_not_contents() { - let d = Disclosure::for_request(&app(), &remote("a"), &req()); - assert_eq!(d.destination, "https://api.example.com"); - assert_eq!(d.kinds(), vec![PayloadKind::Text, PayloadKind::Image]); - assert_eq!(d.items.first().and_then(|i| i.bytes), Some(10)); - assert_eq!(d.param_names, vec!["seed".to_string()]); - let json = serde_json::to_string(&d).unwrap(); - assert!(!json.contains("a cat")); - } - - #[test] - fn local_connections_never_ask() { - let d = Disclosure::for_request(&app(), &local("a"), &req()); - assert!(!ConsentLedger::default().needs_consent(&d, 0)); - } - - #[test] - fn remote_asks_until_granted_then_stops() { - let d = Disclosure::for_request(&app(), &remote("a"), &req()); - let mut ledger = ConsentLedger::default(); - assert!(ledger.needs_consent(&d, 0)); - ledger.grant(&d); - assert!(!ledger.needs_consent(&d, 0)); - } - #[test] fn a_new_kind_of_data_asks_again() { let mut ledger = ConsentLedger::default(); @@ -226,113 +213,10 @@ mod tests { assert_eq!(ledger.records.len(), 1); } - #[test] - fn changing_the_host_invalidates_consent() { - let mut ledger = ConsentLedger::default(); - ledger.grant(&Disclosure::for_request(&app(), &remote("a"), &req())); - let mut moved = remote("a"); - moved.endpoint = Some("https://other.example.org".into()); - assert!(ledger.needs_consent(&Disclosure::for_request(&app(), &moved, &req()), 0)); - } - - #[test] - fn consent_is_per_app_and_revocable() { - let mut ledger = ConsentLedger::default(); - let d = Disclosure::for_request(&app(), &remote("a"), &req()); - ledger.grant(&d); - let other = Disclosure::for_request(&AppId::new("wordcraft").unwrap(), &remote("a"), &req()); - assert!(ledger.needs_consent(&other, 0)); - ledger.revoke(&app(), &remote("a").id); - assert!(ledger.needs_consent(&d, 0)); - } - - #[test] - fn parameters_alone_still_need_consent() { - let only_params = Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_param("negative", "a private note".into()); - let d = disclosure_for(&only_params); - assert_eq!(d.kinds(), vec![PayloadKind::Text]); - let mut ledger = ConsentLedger::default(); - assert!(ledger.needs_consent(&d, 0)); - ledger.grant(&d); - assert!(!ledger.needs_consent(&d, 0)); - } - - fn upscale_req() -> Request { - Request::new(CapabilityId::parse("image.upscale").unwrap()).with_input(InputRole::Source, Payload::inline("image/png", vec![0; 10]).unwrap()) - } - fn disclosure_for(r: &Request) -> Disclosure { Disclosure::for_request(&app(), &remote("a"), r) } - #[test] - fn disclosure_names_the_capability() { - assert_eq!(disclosure_for(&req()).capability, CapabilityId::parse("image.inpaint").unwrap()); - } - - #[test] - fn consent_for_one_capability_does_not_cover_another() { - let mut ledger = ConsentLedger::default(); - ledger.grant(&disclosure_for(&req())); - let other = disclosure_for(&upscale_req()); - assert!(ledger.needs_consent(&other, 0)); - ledger.grant(&other); - assert!(!ledger.needs_consent(&other, 0)); - assert!(!ledger.needs_consent(&disclosure_for(&req()), 0)); - assert_eq!(ledger.records.len(), 2); - } - - #[test] - fn a_timed_agreement_lapses_at_its_expiry() { - let d = disclosure_for(&req()); - let mut ledger = ConsentLedger::default(); - ledger.grant_until(&d, 1_000); - assert!(!ledger.needs_consent(&d, 0)); - assert!(!ledger.needs_consent(&d, 999)); - assert!(ledger.needs_consent(&d, 1_000)); - assert!(ledger.needs_consent(&d, 5_000)); - } - - #[test] - fn an_open_agreement_never_lapses() { - let d = disclosure_for(&req()); - let mut ledger = ConsentLedger::default(); - ledger.grant(&d); - assert!(!ledger.needs_consent(&d, u64::MAX)); - } - - #[test] - fn agreeing_again_after_it_lapsed_renews_it() { - let d = disclosure_for(&req()); - let mut ledger = ConsentLedger::default(); - ledger.grant_until(&d, 1_000); - assert!(ledger.needs_consent(&d, 2_000)); - ledger.grant_until(&d, 3_000); - assert!(!ledger.needs_consent(&d, 2_000)); - assert!(ledger.needs_consent(&d, 3_000)); - assert_eq!(ledger.records.len(), 1); - } - - #[test] - fn the_latest_agreement_sets_the_expiry_for_that_capability() { - let d = disclosure_for(&req()); - let mut ledger = ConsentLedger::default(); - ledger.grant(&d); - ledger.grant_until(&d, 1_000); - assert!(ledger.needs_consent(&d, 1_000)); - ledger.grant(&d); - assert!(!ledger.needs_consent(&d, u64::MAX)); - } - - #[test] - fn a_timed_agreement_for_one_capability_leaves_another_open() { - let mut ledger = ConsentLedger::default(); - ledger.grant(&disclosure_for(&req())); - ledger.grant_until(&disclosure_for(&upscale_req()), 1_000); - assert!(!ledger.needs_consent(&disclosure_for(&req()), 5_000)); - assert!(ledger.needs_consent(&disclosure_for(&upscale_req()), 5_000)); - } - fn text_only_req() -> Request { Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_input(InputRole::Prompt, Payload::text("a cat")) } @@ -347,34 +231,4 @@ mod tests { assert!(!ledger.needs_consent(&text, 2_000)); assert!(ledger.needs_consent(&disclosure_for(&req()), 2_000), "image consent lapsed at 1000 and was not renewed"); } - - #[test] - fn renewing_one_kind_leaves_the_others_on_their_own_expiry() { - let mut ledger = ConsentLedger::default(); - ledger.grant_until(&disclosure_for(&req()), 1_000); - ledger.grant(&disclosure_for(&text_only_req())); - let both = disclosure_for(&req()); - assert!(!ledger.needs_consent(&both, 999)); - assert!(ledger.needs_consent(&both, 1_000)); - assert!(!ledger.needs_consent(&disclosure_for(&text_only_req()), u64::MAX)); - } - - #[test] - fn a_record_from_before_scoping_loads_but_covers_nothing() { - let old = r#"{"records":[{"app":"photocraft","connection":"a","destination":"https://api.example.com","kinds":["text","image"]}]}"#; - let ledger: ConsentLedger = serde_json::from_str(old).unwrap(); - assert_eq!(ledger.records.len(), 1); - assert_eq!(ledger.records[0].capability, None); - assert_eq!(ledger.records[0].expires_at, None); - assert!(ledger.needs_consent(&disclosure_for(&req()), 0)); - } - - #[test] - fn the_capability_and_expiry_survive_a_save() { - let mut ledger = ConsentLedger::default(); - ledger.grant_until(&disclosure_for(&req()), 1_000); - let back: ConsentLedger = serde_json::from_str(&serde_json::to_string(&ledger).unwrap()).unwrap(); - assert_eq!(back, ledger); - assert_eq!(back.records[0].expires_at, Some(1_000)); - } } diff --git a/crates/ai-core/src/draft.rs b/crates/ai-core/src/draft.rs index 32f82dd9af..4cc2d3c87b 100644 --- a/crates/ai-core/src/draft.rs +++ b/crates/ai-core/src/draft.rs @@ -40,10 +40,13 @@ pub struct Preset { pub key: &'static str, /// What the button says. pub name: &'static str, + /// Adapter name the preset selects. pub provider: &'static str, /// Empty for "type your own". pub endpoint: &'static str, + /// Billing the preset assumes. pub billing: Billing, + /// Whether the form asks for a key. pub needs_key: bool, /// One line about it, shown under the name. pub note: &'static str, @@ -182,9 +185,13 @@ fn preset_models(preset: &Preset) -> Vec { /// Which box a problem belongs to, so a form can mark it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Field { + #[allow(missing_docs)] Label, + #[allow(missing_docs)] Provider, + #[allow(missing_docs)] Address, + #[allow(missing_docs)] Key, /// The name of the header that carries the key. KeyHeader, @@ -193,7 +200,9 @@ pub enum Field { /// Why a draft was refused. The message is safe to show. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DraftError { + /// The box the problem belongs to. pub field: Field, + /// What to tell the user. pub message: String, } @@ -216,6 +225,7 @@ impl std::error::Error for DraftError {} pub enum KeyChange { /// Leave whatever is saved. Keep, + /// Save this key, replacing any saved one. Set(SecretString), /// The connection no longer uses a key; remove the saved one. Clear, @@ -224,7 +234,9 @@ pub enum KeyChange { /// A checked connection and what to do with its key. #[derive(Clone, Debug)] pub struct Prepared { + /// The validated connection to save. pub connection: Connection, + /// What to do with the stored key. pub key: KeyChange, } @@ -233,17 +245,23 @@ pub struct Prepared { pub struct ConnectionDraft { /// `Some` when editing an existing connection. pub editing: Option, + #[allow(missing_docs)] pub label: String, + #[allow(missing_docs)] pub provider: String, + #[allow(missing_docs)] pub endpoint: String, + #[allow(missing_docs)] pub billing: Billing, + /// Whether the connection authenticates with a key. pub uses_key: bool, /// Text typed into the key box. Empty while editing means "keep the saved key". It is a plain - /// string only because a text box needs one; [`Debug`] never prints it and [`prepare`] + /// string only because a text box needs one; [`Debug`] never prints it and [`Self::prepare`] /// (Self::prepare) turns it into a [`SecretString`]. pub key: String, /// Header that carries the key; empty sends it as `Authorization: Bearer`. pub key_header: String, + /// Whether the connection is offered for use. pub enabled: bool, /// Models carried onto the saved connection. Assigning here declares them by hand and records /// no address, so they survive any address change; models a test found go through @@ -329,7 +347,7 @@ impl ConnectionDraft { /// A test is not instant and the address stays editable while it runs, so its answer can /// arrive after the address has changed, or after a later test at the new address has already /// answered. Recording it then would file one endpoint's models under another, which is what - /// [`models_fit`](Self::models_fit) exists to prevent. An answer is therefore taken only while + /// `models_fit` exists to prevent. An answer is therefore taken only while /// the field still holds the address it was asked of, and a late one is dropped. Returns /// whether the models were taken, so a caller can say "this result is out of date". /// diff --git a/crates/ai-core/src/draft/tests.rs b/crates/ai-core/src/draft/tests.rs index cfd9f81d68..f7ca898e32 100644 --- a/crates/ai-core/src/draft/tests.rs +++ b/crates/ai-core/src/draft/tests.rs @@ -10,120 +10,6 @@ fn with_key(mut d: ConnectionDraft, key: &str) -> ConnectionDraft { d } -#[test] -fn every_preset_with_an_address_makes_a_valid_connection() { - for p in PRESETS.iter().filter(|p| !p.endpoint.is_empty()) { - let d = with_key(ConnectionDraft::from_preset(p), "sk-test-123"); - let prepared = d.prepare(&[]).unwrap_or_else(|e| panic!("{}: {e}", p.key)); - assert!(prepared.connection.validate().is_ok()); - assert_eq!(prepared.connection.auth.secret_ref().is_some(), p.needs_key, "{}", p.key); - } - // The custom preset needs an address typed in. - let custom = with_key(draft("custom"), "k"); - assert_eq!(custom.prepare(&[]).unwrap_err().field, Field::Address); -} - -#[test] -fn artcraft_api_key_preset_is_distinct_from_unverified_account_access() { - let p = PRESETS.iter().find(|p| p.key == "artcraft-omni").unwrap(); - assert_eq!(p.provider, "artcraft-omni"); - assert!(p.needs_key); - assert_eq!(p.endpoint, "https://api.storyteller.ai"); - assert!(!PRESETS.iter().any(|p| p.key == "artcraft-account")); - let prepared = with_key(ConnectionDraft::from_preset(p), "test-key").prepare(&[]).unwrap(); - assert_eq!(prepared.connection.models.len(), 2); - assert!(prepared.connection.models.iter().any(|m| m.id.as_str() == "nano_banana")); - assert!(prepared.connection.models.iter().any(|m| m.id.as_str() == "seedance_2p0")); -} - -#[test] -fn where_it_goes_decides_local_or_remote() { - assert_eq!(draft("ollama").locality(), Some(Locality::Local)); - assert_eq!(draft("openai").locality(), Some(Locality::Remote)); - let mut d = draft("custom"); - assert_eq!(d.locality(), None, "no address yet"); - d.endpoint = "https://localhost.evil.example".into(); - assert_eq!(d.locality(), Some(Locality::Remote), "a lookalike host is remote"); - d.endpoint = "not a url".into(); - assert_eq!(d.locality(), None); - // The connection carries what the address says, whatever the preset hoped. - let mut o = with_key(draft("ollama"), ""); - o.endpoint = "https://api.example.com/v1".into(); - let c = o.prepare(&[]).unwrap().connection; - assert_eq!(c.locality, Locality::Remote); -} - -#[test] -fn plain_http_is_refused_unless_it_is_this_computer() { - let mut d = with_key(draft("custom"), "k"); - d.endpoint = "http://192.168.1.20:8000/v1".into(); - let e = d.prepare(&[]).unwrap_err(); - assert_eq!(e.field, Field::Address); - assert!(e.message.contains("https://"), "{e}"); - d.endpoint = "http://user:pw@127.0.0.1/v1".into(); - assert!(d.prepare(&[]).is_err()); -} - -#[test] -fn keys_must_be_one_clean_line() { - for bad in ["sk-abc\ndef", "sk abc", "sk-\u{e9}", "sk-abc\u{0}", &"x".repeat(MAX_KEY_BYTES + 1)] { - let d = with_key(draft("openai"), bad); - let e = d.prepare(&[]).unwrap_err(); - assert_eq!(e.field, Field::Key, "{bad:?}"); - assert!(!e.message.contains("abc"), "the message must not echo the key"); - } - // Surrounding whitespace from a paste is trimmed, not refused. - let d = with_key(draft("openai"), " sk-good-key\r\n"); - match d.prepare(&[]).unwrap().key { - KeyChange::Set(k) => assert_eq!(k.expose(), "sk-good-key"), - other => panic!("{other:?}"), - } -} - -#[test] -fn a_new_connection_that_needs_a_key_must_have_one() { - let e = draft("openai").prepare(&[]).unwrap_err(); - assert_eq!(e.field, Field::Key); - // Turning the key off makes it a no-key connection. - let mut d = draft("openai"); - d.uses_key = false; - let p = d.prepare(&[]).unwrap(); - assert_eq!(p.connection.auth, Auth::None); - assert!(matches!(p.key, KeyChange::Keep), "nothing saved, nothing to clear"); -} - -#[test] -fn names_are_checked() { - let mut d = with_key(draft("openai"), "k"); - d.label = " ".into(); - assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label); - d.label = "two\nlines".into(); - assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label); - d.label = "x".repeat(MAX_LABEL_CHARS + 1); - assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label); - d.label = "OpenAI".into(); - d.provider = "bad provider!".into(); - assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Provider); -} - -#[test] -fn ids_come_from_the_name_and_stay_unique() { - let first = with_key(draft("openai"), "k").prepare(&[]).unwrap(); - assert_eq!(first.connection.id.as_str(), "openai"); - assert_eq!(first.connection.auth.secret_ref().unwrap().as_str(), "openai.key"); - let second = with_key(draft("openai"), "k2").prepare(std::slice::from_ref(&first.connection)).unwrap(); - assert_eq!(second.connection.id.as_str(), "openai-2"); - // Two connections never share a key, even with the same name. - assert_eq!(second.connection.auth.secret_ref().unwrap().as_str(), "openai-2.key"); - let mut odd = with_key(draft("openai"), "k"); - odd.label = "!!! Café Ünïcode ???".into(); - let c = odd.prepare(&[]).unwrap().connection; - assert_eq!(c.id.as_str(), "caf-n-code"); - odd.label = "???".into(); - assert_eq!(odd.prepare(&[]).unwrap().connection.id.as_str(), "connection"); - assert_eq!(c.label, "!!! Café Ünïcode ???", "the label itself is kept as typed"); -} - #[test] fn a_taken_key_locator_is_never_reused() { let mut other = with_key(draft("openai"), "k").prepare(&[]).unwrap().connection; @@ -133,117 +19,3 @@ fn a_taken_key_locator_is_never_reused() { let p = with_key(draft("openai"), "k2").prepare(&[other]).unwrap(); assert_eq!(p.connection.auth.secret_ref().unwrap().as_str(), "openai.key2"); } - -fn saved_openai() -> Connection { - let mut c = with_key(draft("openai"), "sk-x").prepare(&[]).unwrap().connection; - c.models = vec![ModelInfo::new(crate::ids::ModelId::new("gpt-x").unwrap(), "GPT X")]; - c -} - -#[test] -fn editing_keeps_the_saved_key_unless_a_new_one_is_typed() { - let saved = saved_openai(); - let mut d = ConnectionDraft::from_connection(&saved); - assert!(d.key.is_empty()); - d.label = "Work OpenAI".into(); - let p = d.prepare(std::slice::from_ref(&saved)).unwrap(); - assert!(matches!(p.key, KeyChange::Keep)); - assert_eq!(p.connection.id, saved.id, "the id never changes on rename"); - assert_eq!(p.connection.auth, saved.auth, "same secret locator"); - d.key = "sk-new".into(); - assert!(matches!(d.prepare(std::slice::from_ref(&saved)).unwrap().key, KeyChange::Set(_))); -} - -#[test] -fn turning_the_key_off_clears_the_saved_one() { - let saved = saved_openai(); - let mut d = ConnectionDraft::from_connection(&saved); - d.uses_key = false; - let p = d.prepare(std::slice::from_ref(&saved)).unwrap(); - assert!(matches!(p.key, KeyChange::Clear)); - assert_eq!(p.connection.auth, Auth::None); -} - -#[test] -fn models_follow_the_address() { - let saved = saved_openai(); - let same = ConnectionDraft::from_connection(&saved); - assert_eq!(same.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.len(), 1); - let mut moved = ConnectionDraft::from_connection(&saved); - moved.endpoint = "https://other.example.com/v1".into(); - assert!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty()); -} - -#[test] -fn models_found_at_the_new_address_are_kept() { - let saved = saved_openai(); - let found = vec![ModelInfo::new(crate::ids::ModelId::new("llama-x").unwrap(), "Llama X")]; - let mut moved = ConnectionDraft::from_connection(&saved); - moved.endpoint = "https://other.example.com/v1".into(); - assert!(moved.set_models("https://other.example.com/v1", found.clone())); - assert_eq!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, found); -} - -#[test] -fn a_retest_that_finds_the_same_models_keeps_them() { - let saved = saved_openai(); - let mut moved = ConnectionDraft::from_connection(&saved); - moved.endpoint = "https://other.example.com/v1".into(); - assert!(moved.set_models("https://other.example.com/v1", saved.models.clone())); - assert_eq!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, saved.models); -} - -#[test] -fn models_found_before_the_address_changed_are_dropped() { - let saved = saved_openai(); - let found = vec![ModelInfo::new(crate::ids::ModelId::new("llama-x").unwrap(), "Llama X")]; - let mut d = ConnectionDraft::from_connection(&saved); - let at = d.endpoint.clone(); - assert!(d.set_models(&at, found)); - d.endpoint = "https://other.example.com/v1".into(); - assert!(d.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty()); -} - -#[test] -fn editing_something_removed_elsewhere_is_an_error() { - let saved = saved_openai(); - let d = ConnectionDraft::from_connection(&saved); - assert!(d.prepare(&[]).is_err()); -} - -#[test] -fn nothing_secret_shows_in_debug_or_errors() { - let d = with_key(draft("openai"), "sk-very-secret-value"); - assert!(!format!("{d:?}").contains("secret-value")); - let mut bad = d.clone(); - bad.endpoint = "nope".into(); - let e = bad.prepare(&[]).unwrap_err(); - assert!(!format!("{e} {e:?}").contains("secret-value")); - let p = d.prepare(&[]).unwrap(); - assert!(!format!("{p:?}").contains("secret-value")); -} - -#[test] -fn hostile_text_never_panics() { - let nasty = ["", "\0", "\u{202e}rtl", "💥💥💥", &"a".repeat(100_000), "http://[::1", "https://", "%00%00", "' OR 1=1 --"]; - for a in nasty { - for b in nasty { - let mut d = draft("custom"); - d.label = a.to_owned(); - d.endpoint = b.to_owned(); - d.provider = a.to_owned(); - d.key = b.to_owned(); - let _ = d.prepare(&[]); - let _ = d.locality(); - } - } -} - -#[test] -fn seedance_connects_through_byteplus_modelark_with_an_api_key() { - let p = PRESETS.iter().find(|p| p.key == "seedance").unwrap(); - assert_eq!(p.endpoint, "https://ark.ap-southeast.bytepluses.com/api/v3"); - assert!(p.name.contains("BytePlus"), "{}", p.name); - assert!(!p.name.contains("Volcengine"), "{}", p.name); - assert!(p.needs_key); -} diff --git a/crates/ai-core/src/endpoint.rs b/crates/ai-core/src/endpoint.rs index 6f2765293e..569f101da5 100644 --- a/crates/ai-core/src/endpoint.rs +++ b/crates/ai-core/src/endpoint.rs @@ -15,8 +15,11 @@ const MAX_ENDPOINT_LEN: usize = 2048; /// A parsed endpoint. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Endpoint { + /// True for `https`, false for `http`. pub https: bool, + /// Host name or address, without port. pub host: String, + /// Explicit port, or `None` for the scheme default. pub port: Option, } @@ -100,26 +103,6 @@ fn parse_port(p: &str) -> Result { mod tests { use super::*; - #[test] - fn loopback_forms() { - for ok in ["http://localhost:8188", "http://127.0.0.1:11434/v1", "http://127.9.9.9", "http://[::1]:8080/x"] { - assert!(Endpoint::parse(ok).unwrap().is_loopback(), "{ok}"); - } - } - - #[test] - fn remote_https() { - let e = Endpoint::parse("https://api.example.com/v1").unwrap(); - assert!(!e.is_loopback()); - assert_eq!(e.fingerprint(), "https://api.example.com"); - } - - #[test] - fn plain_http_to_a_remote_host_is_refused() { - assert!(Endpoint::parse("http://api.example.com").is_err()); - assert!(Endpoint::parse("http://192.168.1.20:8188").is_err()); - } - #[test] fn userinfo_trick_is_refused() { assert!(Endpoint::parse("http://127.0.0.1@evil.example/").is_err()); @@ -135,32 +118,4 @@ mod tests { assert!(!Endpoint::parse(host).unwrap().is_loopback(), "{host}"); } } - - #[test] - fn rejects_garbage_without_panicking() { - for bad in [ - "", - "ftp://x", - "https://", - "https://:80", - "http://[::1", - "http://[::1]x", - "https://a b", - "https://a:99999", - "https://a\\b", - "localhost:8080", - ] { - assert!(Endpoint::parse(bad).is_err(), "{bad:?}"); - } - assert!(Endpoint::parse(&format!("https://{}", "a".repeat(5000))).is_err()); - } - - #[test] - fn fingerprint_changes_with_host_and_port() { - let a = Endpoint::parse("https://a.example:8443/x").unwrap().fingerprint(); - let b = Endpoint::parse("https://b.example:8443/x").unwrap().fingerprint(); - assert_eq!(a, "https://a.example:8443"); - assert_ne!(a, b); - assert_eq!(Endpoint::parse("http://[::1]:80").unwrap().fingerprint(), "http://[::1]:80"); - } } diff --git a/crates/ai-core/src/error.rs b/crates/ai-core/src/error.rs index 5bcfca4137..5c1c54dec8 100644 --- a/crates/ai-core/src/error.rs +++ b/crates/ai-core/src/error.rs @@ -38,6 +38,7 @@ pub enum ErrorKind { } impl ErrorKind { + /// A short lowercase name for messages and logs. pub fn as_str(self) -> &'static str { match self { Self::Unsupported => "unsupported", @@ -57,25 +58,32 @@ impl ErrorKind { /// The error type of the whole crate. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct AiError { + /// What went wrong, for the app to act on. pub kind: ErrorKind, + /// Human-readable detail. Secrets are scrubbed when built with [`AiError::redacted`]. pub message: String, + /// How long to wait before retrying, when the provider said so. #[serde(default, skip_serializing_if = "Option::is_none")] pub retry_after_secs: Option, } impl AiError { + /// Builds an error of the given kind. pub fn new(kind: ErrorKind, message: impl Into) -> Self { Self { kind, message: message.into(), retry_after_secs: None } } + /// Builds an [`ErrorKind::Unsupported`] error. pub fn unsupported(message: impl Into) -> Self { Self::new(ErrorKind::Unsupported, message) } + /// Builds an [`ErrorKind::InvalidRequest`] error. pub fn invalid(message: impl Into) -> Self { Self::new(ErrorKind::InvalidRequest, message) } + /// Builds an [`ErrorKind::Cancelled`] error. pub fn cancelled() -> Self { Self::new(ErrorKind::Cancelled, "cancelled") } @@ -85,6 +93,7 @@ impl AiError { Self::new(kind, redact(message, secrets)) } + /// Sets the wait, in seconds, before a retry. pub fn with_retry_after(mut self, secs: u64) -> Self { self.retry_after_secs = Some(secs); self @@ -103,38 +112,3 @@ impl fmt::Display for AiError { } impl std::error::Error for AiError {} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn redacted_removes_the_key() { - let key = SecretString::new("sk-test-999"); - let e = AiError::redacted(ErrorKind::Auth, "invalid key sk-test-999", &[&key]); - assert!(!e.message.contains("999")); - assert!(!format!("{e}").contains("999")); - } - - #[test] - fn consent_required_is_not_retryable_and_round_trips() { - let e = AiError::new(ErrorKind::ConsentRequired, "ask first"); - assert!(!e.is_retryable()); - let back: AiError = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); - assert_eq!(back.kind, ErrorKind::ConsentRequired); - assert!(format!("{e}").starts_with("consent required")); - } - - #[test] - fn retryable_kinds() { - assert!(AiError::new(ErrorKind::RateLimited, "x").is_retryable()); - assert!(!AiError::unsupported("x").is_retryable()); - } - - #[test] - fn round_trips_through_json() { - let e = AiError::new(ErrorKind::RateLimited, "slow down").with_retry_after(30); - let back: AiError = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); - assert_eq!(e, back); - } -} diff --git a/crates/ai-core/src/history.rs b/crates/ai-core/src/history.rs index 9922c50984..f2f1db1c01 100644 --- a/crates/ai-core/src/history.rs +++ b/crates/ai-core/src/history.rs @@ -28,27 +28,41 @@ pub const MAX_PROMPT_CHARS: usize = 2000; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "status", rename_all = "snake_case")] pub enum Outcome { + /// The job finished and produced a result. Done, - Failed { kind: ErrorKind }, + /// The job failed. Only the error kind is kept, never the message. + Failed { + /// What kind of failure it was. + kind: ErrorKind, + }, + /// The user or app cancelled the job. Cancelled, } /// Written when a job is submitted (or refused by the provider). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct StartRecord { + /// Schema version, [`HISTORY_SCHEMA`]. pub v: u32, /// Joins this line to its [`EndRecord`]. Unique across apps and runs. pub run: String, /// Unix milliseconds. pub at_ms: u64, + /// Id of the app that submitted the job. pub app: String, + /// Id of the role the job ran for. pub role_id: String, /// The feature as the user knows it, such as "Generative Fill". pub role_label: String, + /// The capability requested, as `.`. pub capability: String, + /// Id of the connection used. pub connection: String, + /// The connection's label when the job ran, kept in case the connection is later renamed or removed. pub connection_label: String, + /// Id of the model used. pub model: String, + /// Whether the connection was local or remote. pub locality: Locality, /// `scheme://host[:port]`, or the route name when there is no endpoint. pub destination: String, @@ -73,9 +87,13 @@ pub struct StartRecord { /// Written when a job reaches a final state. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct EndRecord { + /// Schema version, [`HISTORY_SCHEMA`]. pub v: u32, + /// The run id shared with the [`StartRecord`]. pub run: String, + /// Unix milliseconds when the job ended. pub at_ms: u64, + /// How the job ended. pub outcome: Outcome, /// What the provider reported, or `None`. Never an estimate of ours. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -88,14 +106,18 @@ pub struct EndRecord { #[serde(tag = "phase", rename_all = "snake_case")] #[allow(clippy::large_enum_variant)] pub enum HistoryRecord { + /// The line written at submission. Start(StartRecord), + /// The line written at the final state. End(EndRecord), } /// A job as the history list shows it: the start line and, if seen, the end line. #[derive(Clone, Debug, PartialEq, Eq)] pub struct HistoryEntry { + /// The submission line. pub start: StartRecord, + /// The final line, or `None` while unfinished. pub end: Option, } @@ -106,6 +128,7 @@ impl HistoryEntry { end.at_ms.checked_sub(self.start.at_ms) } + /// How the job ended, or `None` while unfinished. pub fn outcome(&self) -> Option<&Outcome> { self.end.as_ref().map(|e| &e.outcome) } @@ -120,7 +143,9 @@ impl HistoryEntry { /// Entries newest first, plus how many lines could not be read. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct HistoryLog { + /// Jobs, newest first. pub entries: Vec, + /// Lines that could not be read and were left out. pub skipped: usize, } @@ -161,6 +186,3 @@ pub fn clip_prompt(text: &str) -> String { } pub mod report; - -#[cfg(test)] -mod tests; diff --git a/crates/ai-core/src/history/report.rs b/crates/ai-core/src/history/report.rs index 28c69317c6..b3d2ce79ff 100644 --- a/crates/ai-core/src/history/report.rs +++ b/crates/ai-core/src/history/report.rs @@ -16,8 +16,11 @@ const DAY_MS: i64 = 86_400_000; /// A calendar day. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Day { + #[allow(missing_docs)] pub year: i32, + /// Month number, 1 to 12. pub month: u8, + /// Day of the month, starting at 1. pub day: u8, } @@ -38,6 +41,7 @@ impl Day { civil_from_days(days) } + /// The month this day falls in. pub fn month(self) -> Month { Month { year: self.year, month: self.month } } @@ -52,7 +56,9 @@ impl fmt::Display for Day { /// A calendar month. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Month { + #[allow(missing_docs)] pub year: i32, + /// Month number, 1 to 12. pub month: u8, } @@ -128,19 +134,23 @@ fn exact_amount(micros: u64) -> String { /// Which entries to show. An empty filter shows everything. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct HistoryFilter { + /// Only jobs from this app id. pub app: Option, + /// Only jobs that used this model id. pub model: Option, /// Only jobs that started at or after this Unix-millisecond time. pub since_ms: Option, } impl HistoryFilter { + /// Whether `entry` passes every filter that is set. pub fn matches(&self, entry: &HistoryEntry) -> bool { self.app.as_ref().is_none_or(|a| *a == entry.start.app) && self.model.as_ref().is_none_or(|m| *m == entry.start.model) && self.since_ms.is_none_or(|t| entry.start.at_ms >= t) } + /// The entries that pass, in their original order. pub fn apply<'a>(&self, entries: &'a [HistoryEntry]) -> Vec<&'a HistoryEntry> { entries.iter().filter(|e| self.matches(e)).collect() } @@ -164,9 +174,13 @@ fn distinct<'a>(items: impl Iterator) -> Vec { /// A count of jobs and the money the providers reported for them. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Totals { + /// Every job counted, finished or not. pub jobs: usize, + /// Jobs that finished successfully. pub done: usize, + /// Jobs that failed. pub failed: usize, + /// Jobs that were cancelled. pub cancelled: usize, /// Started, but the app closed before the end was seen. pub unfinished: usize, @@ -181,6 +195,7 @@ pub struct Totals { } impl Totals { + /// Counts one entry into the totals. pub fn add(&mut self, entry: &HistoryEntry) { self.jobs += 1; if matches!(entry.outcome(), Some(Outcome::Done)) @@ -213,6 +228,7 @@ impl Totals { } } +/// Sums `entries` into one [`Totals`]. pub fn totals<'a>(entries: impl IntoIterator) -> Totals { let mut t = Totals::default(); for e in entries { diff --git a/crates/ai-core/src/history/report/tests.rs b/crates/ai-core/src/history/report/tests.rs index 4265237618..501e8686fc 100644 --- a/crates/ai-core/src/history/report/tests.rs +++ b/crates/ai-core/src/history/report/tests.rs @@ -1,10 +1,8 @@ use super::*; use crate::connection::Locality; -use crate::error::ErrorKind; use crate::history::{EndRecord, HISTORY_SCHEMA, HistoryRecord, StartRecord, merge}; -use crate::job::{CostEstimate, Usage}; +use crate::job::Usage; -const HOUR: u64 = 3_600_000; const T0: u64 = 1_760_000_000_000; // 2025-10-09T08:53:20Z fn start(run: &str, at_ms: u64, app: &str, model: &str) -> StartRecord { @@ -63,112 +61,6 @@ fn days_are_right_across_leap_days_epoch_and_year_ends() { assert_eq!(day_of(T0, 0).to_string(), "2025-10-09"); } -#[test] -fn the_offset_moves_the_day_boundary_both_ways() { - let late = 1_767_225_599_000; // 2025-12-31T23:59:59Z - assert_eq!(day_of(late, 60).to_string(), "2026-01-01"); - assert_eq!(day_of(late, -300).to_string(), "2025-12-31"); - let early = 1_767_225_600_000; // 2026-01-01T00:00:00Z - assert_eq!(day_of(early, -1).to_string(), "2025-12-31"); - assert_eq!(day_of(0, -60).to_string(), "1969-12-31"); -} - -#[test] -fn iso_time_is_utc_and_padded() { - assert_eq!(iso_utc(T0), "2025-10-09T08:53:20Z"); - assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z"); -} - -#[test] -fn amounts_are_exact_and_small_costs_are_not_zero() { - assert_eq!(amount_text(31_000), "0.03"); - assert_eq!(amount_text(1_234_567), "1.23"); - assert_eq!(amount_text(1_500), "0.0015"); - assert_eq!(amount_text(0), "0.0000"); - assert_eq!(exact_amount(31_000), "0.031000"); - assert_eq!(exact_amount(2_000_001), "2.000001"); -} - -#[test] -fn the_filter_narrows_by_app_model_and_time_and_empty_shows_all() { - let e = entries(&[ - ("a", T0, "photocraft", "m1", Some(Outcome::Done), Some(1)), - ("b", T0 + HOUR, "wordcraft", "m1", Some(Outcome::Done), None), - ("c", T0 + 2 * HOUR, "photocraft", "m2", None, None), - ]); - assert_eq!(HistoryFilter::default().apply(&e).len(), 3); - let photo = HistoryFilter { app: Some("photocraft".into()), ..HistoryFilter::default() }; - assert_eq!(photo.apply(&e).len(), 2); - let both = HistoryFilter { model: Some("m2".into()), ..photo.clone() }; - assert_eq!(both.apply(&e).len(), 1); - let recent = HistoryFilter { since_ms: Some(T0 + HOUR), ..HistoryFilter::default() }; - let runs: Vec<_> = recent.apply(&e).iter().map(|x| x.start.run.clone()).collect(); - assert_eq!(runs, ["c", "b"], "inclusive of the boundary, newest first"); - assert_eq!(apps(&e), ["photocraft", "wordcraft"]); - assert_eq!(models(&e), ["m1", "m2"]); -} - -#[test] -fn totals_count_outcomes_and_sum_cost_per_currency() { - let e = entries(&[ - ("a", T0, "p", "m", Some(Outcome::Done), Some(40_000)), - ("b", T0 + 1, "p", "m", Some(Outcome::Done), Some(25_000)), - ("c", T0 + 2, "p", "m", Some(Outcome::Done), None), - ("d", T0 + 3, "p", "m", Some(Outcome::Failed { kind: ErrorKind::Quota }), None), - ("e", T0 + 4, "p", "m", Some(Outcome::Cancelled), None), - ("f", T0 + 5, "p", "m", None, None), - ]); - let t = totals(&e); - assert_eq!(t.jobs, 6); - assert_eq!((t.done, t.failed, t.cancelled, t.unfinished), (3, 1, 1, 1)); - assert_eq!(t.cost_micros.get("USD"), Some(&65_000)); - assert_eq!(t.without_cost, 1, "only a finished success counts as unpriced"); -} - -#[test] -fn a_huge_cost_saturates_instead_of_wrapping() { - let e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), Some(u64::MAX)), ("b", T0 + 1, "p", "m", Some(Outcome::Done), Some(10))]); - assert_eq!(totals(&e).cost_micros.get("USD"), Some(&u64::MAX)); -} - -#[test] -fn days_and_months_group_newest_first() { - let day = 24 * HOUR; - let e = entries(&[ - ("a", T0, "p", "m", Some(Outcome::Done), Some(10_000)), - ("b", T0 + HOUR, "p", "m", Some(Outcome::Done), Some(20_000)), - ("c", T0 + day, "p", "m", Some(Outcome::Done), Some(5_000)), - ("d", T0 + 30 * day, "p", "m", Some(Outcome::Done), Some(1_000)), - ]); - let refs: Vec<&HistoryEntry> = e.iter().collect(); - let days = by_day(&refs, 0); - let labels: Vec<_> = days.iter().map(|(d, t)| (d.to_string(), t.jobs)).collect(); - assert_eq!(labels, [("2025-11-08".to_owned(), 1), ("2025-10-10".to_owned(), 1), ("2025-10-09".to_owned(), 2)]); - let months = by_month(&refs, 0); - let labels: Vec<_> = months.iter().map(|(m, t)| (m.to_string(), t.jobs, t.cost_micros.get("USD").copied())).collect(); - assert_eq!(labels, [("2025-11".to_owned(), 1, Some(1_000)), ("2025-10".to_owned(), 3, Some(35_000))]); -} - -#[test] -fn csv_has_a_header_one_row_per_entry_and_matching_column_counts() { - let mut e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), Some(31_000)), ("b", T0 + 5, "p", "m", None, None)]); - e[0].start.estimate = Some(CostEstimate { micros: 30_000, currency: "USD".into(), billing: crate::Billing::Metered }); - let refs: Vec<&HistoryEntry> = e.iter().collect(); - let csv = to_csv(&refs); - let lines: Vec<&str> = csv.split("\r\n").collect(); - assert_eq!(lines.len(), 4, "header, two rows, trailing empty"); - assert!(lines[0].starts_with("started_utc,app,feature")); - assert_eq!(lines[0].split(',').count(), CSV_HEADER.len()); - // Newest first: the unfinished job (b) is the first row. - assert!(lines[1].contains(",unfinished,"), "{}", lines[1]); - assert!(lines[1].contains("0.030000,USD"), "estimate: {}", lines[1]); - assert!(lines[2].contains("0.031000,USD"), "{}", lines[2]); - assert!(lines[2].contains(",done,"), "{}", lines[2]); - assert!(lines[2].contains(",2.000,"), "two seconds: {}", lines[2]); - assert_eq!(lines[1].split(',').count(), CSV_HEADER.len()); - assert_eq!(lines[2].split(',').count(), CSV_HEADER.len()); -} - #[test] fn csv_quotes_awkward_text_and_defuses_formulas() { let mut e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), None)]); @@ -183,27 +75,6 @@ fn csv_quotes_awkward_text_and_defuses_formulas() { assert!(!csv.contains(",=HYPERLINK"), "{csv}"); } -#[test] -fn a_failed_job_exports_its_error_kind() { - let e = entries(&[("a", T0, "p", "m", Some(Outcome::Failed { kind: ErrorKind::RateLimited }), None)]); - let refs: Vec<&HistoryEntry> = e.iter().collect(); - assert!(to_csv(&refs).contains(",failed,rate_limited,")); -} - -#[test] -fn list_times_and_day_starts_follow_the_offset() { - assert_eq!(time_text(T0, 0), "2025-10-09 08:53"); - assert_eq!(time_text(T0, 120), "2025-10-09 10:53"); - assert_eq!(time_text(T0, -540), "2025-10-08 23:53"); - // 2025-10-09T08:53:20Z; the UTC day began at 00:00Z. - assert_eq!(start_of_day_ms(T0, 0), 1_759_968_000_000); - // At UTC+2 the local day began at 22:00Z the evening before. - assert_eq!(start_of_day_ms(T0, 120), 1_759_968_000_000 - 2 * HOUR); - // At UTC-9 the local day (Oct 8) began at 09:00Z on Oct 8. - assert_eq!(start_of_day_ms(T0, -540), 1_759_968_000_000 - 24 * HOUR + 9 * HOUR); - assert_eq!(start_of_day_ms(0, 0), 0); -} - #[test] fn days_convert_to_and_from_the_epoch_count_both_ways() { for ms in [0, 951_782_400_000, 1_709_164_800_000, 1_767_225_599_000, T0] { @@ -232,41 +103,3 @@ fn days_convert_to_and_from_the_epoch_count_both_ways() { } const DAY_MS_FOR_TESTS: u64 = 86_400_000; - -#[test] -fn the_daily_series_fills_empty_days_and_keeps_the_most_recent() { - let day = DAY_MS_FOR_TESTS; - let e = entries(&[ - ("a", T0, "p", "m", Some(Outcome::Done), Some(10_000)), - ("b", T0 + 3 * day, "p", "m", Some(Outcome::Done), Some(5_000)), - ("c", T0 + 3 * day + 1, "p", "m", None, None), - ]); - let refs: Vec<&HistoryEntry> = e.iter().collect(); - let all = daily(&refs, 0, 31); - let shape: Vec<(String, usize)> = all.iter().map(|(d, t)| (d.to_string(), t.jobs)).collect(); - assert_eq!(shape, [("2025-10-09".to_owned(), 1), ("2025-10-10".to_owned(), 0), ("2025-10-11".to_owned(), 0), ("2025-10-12".to_owned(), 2)]); - let recent = daily(&refs, 0, 2); - let shape: Vec = recent.iter().map(|(d, _)| d.to_string()).collect(); - assert_eq!(shape, ["2025-10-11", "2025-10-12"]); - assert!(daily(&[], 0, 31).is_empty()); -} - -#[test] -fn models_and_apps_group_busiest_first_and_average_only_successful_timed_jobs() { - let e = entries(&[ - ("a", T0, "photocraft", "flux", Some(Outcome::Done), Some(50_000)), - ("b", T0 + 10, "photocraft", "flux", Some(Outcome::Done), Some(50_000)), - ("c", T0 + 20, "wordcraft", "gpt", Some(Outcome::Done), Some(1_000)), - ("d", T0 + 30, "wordcraft", "gpt", Some(Outcome::Failed { kind: ErrorKind::Network }), None), - ("e", T0 + 40, "wordcraft", "gpt", None, None), - ]); - let refs: Vec<&HistoryEntry> = e.iter().collect(); - let models = by_model(&refs); - assert_eq!(models.iter().map(|(k, t)| (k.as_str(), t.jobs)).collect::>(), [("gpt", 3), ("flux", 2)]); - let apps = by_app(&refs); - assert_eq!(apps[0].0, "wordcraft"); - // Each finished job took two seconds in the fixture; the failed and unfinished ones do not count. - assert_eq!(models[0].1.average_ms(), Some(2_000)); - assert_eq!(models[0].1.timed, 1); - assert_eq!(Totals::default().average_ms(), None); -} diff --git a/crates/ai-core/src/history/tests.rs b/crates/ai-core/src/history/tests.rs deleted file mode 100644 index e70fa5dc45..0000000000 --- a/crates/ai-core/src/history/tests.rs +++ /dev/null @@ -1,114 +0,0 @@ -use super::*; - -fn start(run: &str, at_ms: u64) -> StartRecord { - StartRecord { - v: HISTORY_SCHEMA, - run: run.into(), - at_ms, - app: "photocraft".into(), - role_id: "fill".into(), - role_label: "Generative Fill".into(), - capability: "image.inpaint".into(), - connection: "conn1".into(), - connection_label: "Hosted".into(), - model: "m1".into(), - locality: Locality::Remote, - destination: "https://api.example.com".into(), - sent: Vec::new(), - params: vec!["seed".into()], - provider_job: Some("gen-9".into()), - estimate: None, - prompt: None, - } -} - -fn end(run: &str, at_ms: u64, outcome: Outcome) -> EndRecord { - EndRecord { v: HISTORY_SCHEMA, run: run.into(), at_ms, outcome, usage: None } -} - -fn s(r: StartRecord) -> HistoryRecord { - HistoryRecord::Start(r) -} - -fn e(r: EndRecord) -> HistoryRecord { - HistoryRecord::End(r) -} - -#[test] -fn a_line_round_trips_and_leaves_out_what_is_absent() { - let line = serde_json::to_string(&s(start("a", 5))).unwrap(); - assert!(!line.contains('\n')); - assert!(!line.contains("prompt"), "{line}"); - assert!(!line.contains("estimate"), "{line}"); - assert_eq!(serde_json::from_str::(&line).unwrap(), s(start("a", 5))); - let failed = e(end("a", 9, Outcome::Failed { kind: ErrorKind::Quota })); - let line = serde_json::to_string(&failed).unwrap(); - assert!(line.contains("\"phase\":\"end\""), "{line}"); - assert_eq!(serde_json::from_str::(&line).unwrap(), failed); -} - -#[test] -fn an_unknown_phase_does_not_parse_so_readers_can_skip_it() { - assert!(serde_json::from_str::(r#"{"phase":"pause","run":"a"}"#).is_err()); -} - -#[test] -fn start_and_end_join_by_run_and_the_list_is_newest_first() { - let log = merge(vec![s(start("old", 10)), s(start("new", 30)), e(end("new", 45, Outcome::Done)), e(end("old", 12, Outcome::Cancelled))], 0); - let runs: Vec<_> = log.entries.iter().map(|x| x.start.run.as_str()).collect(); - assert_eq!(runs, ["new", "old"]); - assert_eq!(log.entries[0].duration_ms(), Some(15)); - assert_eq!(log.entries[1].outcome(), Some(&Outcome::Cancelled)); -} - -#[test] -fn a_start_with_no_end_stays_unfinished() { - let log = merge(vec![s(start("a", 10))], 0); - assert_eq!(log.entries.len(), 1); - assert_eq!(log.entries[0].outcome(), None); - assert_eq!(log.entries[0].duration_ms(), None); -} - -#[test] -fn an_end_whose_start_was_rotated_away_is_dropped() { - let log = merge(vec![e(end("gone", 5, Outcome::Done))], 2); - assert!(log.entries.is_empty()); - assert_eq!(log.skipped, 2); -} - -#[test] -fn the_first_end_wins_and_a_repeated_start_is_ignored() { - let log = merge(vec![s(start("a", 10)), s(start("a", 99)), e(end("a", 20, Outcome::Done)), e(end("a", 30, Outcome::Cancelled))], 0); - assert_eq!(log.entries.len(), 1); - assert_eq!(log.entries[0].start.at_ms, 10); - assert_eq!(log.entries[0].outcome(), Some(&Outcome::Done)); -} - -#[test] -fn a_clock_that_went_backwards_gives_no_duration() { - let log = merge(vec![s(start("a", 50)), e(end("a", 40, Outcome::Done))], 0); - assert_eq!(log.entries[0].duration_ms(), None); -} - -#[test] -fn cost_is_only_what_the_provider_reported() { - let mut finished = end("a", 20, Outcome::Done); - let mut log = merge(vec![s(start("a", 10)), e(finished.clone())], 0); - assert_eq!(log.entries[0].reported_cost(), None); - - finished.usage = Some(Usage { cost_micros: Some(40_000), currency: None, ..Usage::default() }); - log = merge(vec![s(start("a", 10)), e(finished.clone())], 0); - assert_eq!(log.entries[0].reported_cost(), None, "no currency, no cost"); - - finished.usage = Some(Usage { cost_micros: Some(40_000), currency: Some("USD".into()), ..Usage::default() }); - log = merge(vec![s(start("a", 10)), e(finished)], 0); - assert_eq!(log.entries[0].reported_cost(), Some((40_000, "USD"))); -} - -#[test] -fn prompts_are_clipped_on_a_character_boundary() { - let long = "é".repeat(MAX_PROMPT_CHARS + 50); - let clipped = clip_prompt(&long); - assert_eq!(clipped.chars().count(), MAX_PROMPT_CHARS); - assert_eq!(clip_prompt("short"), "short"); -} diff --git a/crates/ai-core/src/ids.rs b/crates/ai-core/src/ids.rs index 484b9e47dc..e09ef6ccad 100644 --- a/crates/ai-core/src/ids.rs +++ b/crates/ai-core/src/ids.rs @@ -13,9 +13,18 @@ pub const MAX_ID_LEN: usize = 128; /// Why a string was refused as an identifier. #[derive(Clone, Debug, PartialEq, Eq)] pub enum IdError { + /// The value is empty. Empty, - TooLong { len: usize, max: usize }, + /// The value is longer than the limit. + TooLong { + /// Length of the value in bytes. + len: usize, + /// Longest allowed length in bytes. + max: usize, + }, + /// The value contains a character outside the allowed set. BadChar(char), + /// The value is the wrong shape. The text says how. Malformed(&'static str), } @@ -71,6 +80,7 @@ macro_rules! validated_string { Ok(Self(value)) } + /// The wrapped string. pub fn as_str(&self) -> &str { &self.0 } @@ -118,12 +128,16 @@ macro_rules! open_enum { $(#[$m])* #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum $name { - $($var,)+ + $( + #[allow(missing_docs)] + $var, + )+ /// A well-formed value this library does not know by name. Other(String), } impl $name { + /// The well-known name, or the text of `Other`. pub fn as_str(&self) -> &str { match self { $(Self::$var => $text,)+ @@ -197,42 +211,3 @@ validated_string!( SecretRef, validate_id ); - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ids_accept_normal_values() { - assert!(ModelId::new("black-forest-labs/flux-1.1-pro").is_ok()); - assert!(ConnectionId::new("conn_01hx").is_ok()); - } - - #[test] - fn ids_reject_bad_values_without_panicking() { - assert_eq!(ModelId::new(""), Err(IdError::Empty)); - assert_eq!(ModelId::new("a b"), Err(IdError::BadChar(' '))); - assert_eq!(ModelId::new("a\0b"), Err(IdError::BadChar('\0'))); - assert!(matches!(ModelId::new("x".repeat(MAX_ID_LEN + 1)), Err(IdError::TooLong { .. }))); - assert!(ModelId::new("\u{202e}rtl").is_err()); - } - - #[test] - fn tokens_reject_dots() { - assert!(validate_token("image").is_ok()); - assert_eq!(validate_token("a.b"), Err(IdError::BadChar('.'))); - } - - #[test] - fn deserialize_validates() { - let ok: Result = serde_json::from_str("\"gpt-image-1\""); - assert!(ok.is_ok()); - let bad: Result = serde_json::from_str("\"has space\""); - assert!(bad.is_err()); - } - - #[test] - fn debug_shows_type_and_value() { - assert_eq!(format!("{:?}", AppId::new("photocraft").unwrap()), "AppId(\"photocraft\")"); - } -} diff --git a/crates/ai-core/src/job.rs b/crates/ai-core/src/job.rs index 4a3b654768..139717701b 100644 --- a/crates/ai-core/src/job.rs +++ b/crates/ai-core/src/job.rs @@ -15,19 +15,26 @@ use crate::payload::Payload; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "state", rename_all = "snake_case")] pub enum JobState { + /// Accepted by the provider but not started. Queued, /// `percent` is 0 to 100 when the provider reports it. Running { + /// Progress from 0 to 100, when the provider reports it. percent: Option, }, + /// Finished with outputs. Final. Succeeded, + /// Ended with an error. Final. Failed { + /// Why the job failed. error: AiError, }, + /// Stopped on request. Final. Cancelled, } impl JobState { + /// True for succeeded, failed and cancelled, the states that never change. pub fn is_terminal(&self) -> bool { matches!(self, Self::Succeeded | Self::Failed { .. } | Self::Cancelled) } @@ -53,6 +60,7 @@ impl JobState { /// A finished result. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Output { + /// The result data. pub payload: Payload, /// Optional note such as "variation 2". Structured output arrives as an `application/json` /// inline payload. @@ -64,41 +72,66 @@ pub struct Output { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Event { - TextDelta { text: String }, - ToolCall { name: String, arguments: String }, + /// A piece of generated text, to append to what came before. + TextDelta { + /// The new text. + text: String, + }, + /// The model asked to call a tool. + ToolCall { + /// Name of the tool. + name: String, + /// The arguments, as a JSON string. + arguments: String, + }, + /// A finished output. Output(Output), - Notice { message: String }, + /// A message from the provider for the user, not part of the result. + Notice { + /// The message text. + message: String, + }, } /// What a provider charged or counted. All fields optional: many providers report none. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Usage { + /// Input the provider counted, in its own units (for example tokens). pub input_units: Option, + /// Output the provider counted, in its own units. pub output_units: Option, /// Millionths of `currency`, so no floating point money. pub cost_micros: Option, + /// Currency code for `cost_micros`, such as `USD`. pub currency: Option, } /// A price estimate shown before a job runs. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CostEstimate { + /// Estimated price in millionths of `currency`. pub micros: u64, + /// Currency code, such as `USD`. pub currency: String, + /// How the job will be billed. pub billing: Billing, } /// One poll's answer. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct JobSnapshot { + /// Where the job is now. pub state: JobState, + /// Events since the previous poll, oldest first. #[serde(default)] pub events: Vec, + /// What the provider reported charging, when it did. #[serde(default, skip_serializing_if = "Option::is_none")] pub usage: Option, } impl JobSnapshot { + /// A snapshot with the given state and no events or usage. pub fn new(state: JobState) -> Self { Self { state, events: Vec::new(), usage: None } } @@ -111,59 +144,3 @@ impl JobSnapshot { }) } } - -#[cfg(test)] -mod tests { - use super::*; - use JobState::{Cancelled, Failed, Queued, Running, Succeeded}; - - fn failed() -> JobState { - Failed { error: AiError::new(crate::error::ErrorKind::Provider, "boom") } - } - - #[test] - fn forward_moves_are_legal() { - assert!(Queued.can_become(&Running { percent: None })); - assert!(Running { percent: Some(10) }.can_become(&Running { percent: Some(10) })); - assert!(Running { percent: Some(10) }.can_become(&Running { percent: Some(80) })); - assert!(Running { percent: Some(80) }.can_become(&Succeeded)); - assert!(Running { percent: None }.can_become(&failed())); - assert!(Queued.can_become(&Succeeded)); - } - - #[test] - fn progress_cannot_go_backwards() { - assert!(!Running { percent: Some(50) }.can_become(&Running { percent: Some(40) })); - assert!(!Running { percent: Some(50) }.can_become(&Running { percent: None })); - assert!(!Running { percent: Some(5) }.can_become(&Queued)); - } - - #[test] - fn terminal_states_are_final() { - for t in [Succeeded, Cancelled, failed()] { - assert!(t.is_terminal()); - assert!(t.can_become(&t.clone())); - assert!(!t.can_become(&Running { percent: None })); - assert!(!t.can_become(&Queued)); - } - assert!(!Succeeded.can_become(&Cancelled)); - assert!(!Cancelled.can_become(&Succeeded)); - } - - #[test] - fn snapshot_collects_outputs_only() { - let mut s = JobSnapshot::new(Succeeded); - s.events.push(Event::TextDelta { text: "hi".into() }); - s.events.push(Event::Output(Output { payload: Payload::text("done"), label: None })); - assert_eq!(s.outputs().count(), 1); - } - - #[test] - fn snapshot_json_round_trip() { - let mut s = JobSnapshot::new(Running { percent: Some(40) }); - s.events.push(Event::ToolCall { name: "lookup".into(), arguments: "{}".into() }); - s.usage = Some(Usage { cost_micros: Some(1200), currency: Some("USD".into()), ..Usage::default() }); - let json = serde_json::to_string(&s).unwrap(); - assert_eq!(serde_json::from_str::(&json).unwrap(), s); - } -} diff --git a/crates/ai-core/src/lib.rs b/crates/ai-core/src/lib.rs index c9959e68e3..5f381d3ce8 100644 --- a/crates/ai-core/src/lib.rs +++ b/crates/ai-core/src/lib.rs @@ -28,7 +28,7 @@ //! | [`spec`] | a provider described as data: types, checker and substitutions (task u2) | //! | [`provider`] | the [`Provider`] trait | //! | [`mock`], [`conformance`] | scripted provider and reusable behaviour checks | - +#![warn(missing_docs)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod capability; @@ -68,3 +68,10 @@ pub use request::Request; pub use role::{Binding, Role}; pub use secret::SecretString; pub use store::StoreFile; + +#[cfg(test)] +extern crate self as craft_ai_core; + +#[cfg(test)] +#[path = "../tests/main.rs"] +mod integration; diff --git a/crates/ai-core/src/mock.rs b/crates/ai-core/src/mock.rs index 8dee5c4157..16886611ae 100644 --- a/crates/ai-core/src/mock.rs +++ b/crates/ai-core/src/mock.rs @@ -18,7 +18,9 @@ use crate::request::Request; /// How a mock job ends. #[derive(Clone, Debug)] pub enum Outcome { + /// Finish successfully with these outputs. Succeed(Vec), + /// Finish in the `Failed` state with this error. Fail(AiError), } @@ -29,6 +31,7 @@ pub struct Script { pub running_polls: u32, /// One text delta is emitted per poll until these run out. pub text_chunks: Vec, + /// How the job ends once the running polls and text chunks are done. pub outcome: Outcome, } @@ -61,6 +64,7 @@ pub struct MockProvider { } impl MockProvider { + /// Builds a provider that offers `models` and runs every job by `script`. pub fn new(models: Vec, script: Script) -> Self { Self { models, script, limits: Limits::default(), state: Mutex::new(State::default()) } } diff --git a/crates/ai-core/src/model.rs b/crates/ai-core/src/model.rs index 99bc719f8e..265d28fbee 100644 --- a/crates/ai-core/src/model.rs +++ b/crates/ai-core/src/model.rs @@ -27,10 +27,13 @@ open_enum!( /// Optional abilities beyond the basic request and result. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Features { + /// The model can stream text deltas as it generates. #[serde(default)] pub streaming: bool, + /// The model can call tools. #[serde(default)] pub tools: bool, + /// The model can return JSON that follows a schema. #[serde(default)] pub structured_output: bool, } @@ -38,6 +41,7 @@ pub struct Features { /// What one model can do for one capability. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CapabilitySpec { + /// The capability this spec describes. pub capability: CapabilityId, /// Inputs the model accepts, with the most of each. An input role not listed is unsupported. pub accepts: BTreeMap, @@ -47,6 +51,7 @@ pub struct CapabilitySpec { /// Most outputs one request can return (variations count here). #[serde(default = "one")] pub max_outputs: u32, + /// Optional abilities the model has for this capability. #[serde(default)] pub features: Features, } @@ -56,16 +61,19 @@ fn one() -> u32 { } impl CapabilitySpec { - /// A spec that accepts the given inputs (one of each) and requires none. + /// A spec for `capability` that accepts no inputs, requires none and returns one output; add + /// inputs with [`accepting`](Self::accepting). pub fn new(capability: CapabilityId) -> Self { Self { capability, accepts: BTreeMap::new(), requires: Vec::new(), max_outputs: 1, features: Features::default() } } + /// Accepts up to `max` inputs of `role`. pub fn accepting(mut self, role: InputRole, max: u32) -> Self { self.accepts.insert(role, max); self } + /// Requires an input of `role`. Adding the same role twice has no effect. pub fn requiring(mut self, role: InputRole) -> Self { if !self.requires.contains(&role) { self.requires.push(role); @@ -73,11 +81,13 @@ impl CapabilitySpec { self } + /// Sets the most outputs one request can return. pub fn max_outputs(mut self, n: u32) -> Self { self.max_outputs = n; self } + /// Sets the optional abilities. pub fn with_features(mut self, features: Features) -> Self { self.features = features; self @@ -102,8 +112,11 @@ pub struct Pricing { /// One model as offered by one connection. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ModelInfo { + #[allow(missing_docs)] pub id: ModelId, + /// Name shown to the user. pub label: String, + /// What the model can do, one spec per capability. #[serde(default)] pub capabilities: Vec, /// Reported by the provider where it can be (OpenRouter does). Absent in stores written before @@ -123,80 +136,19 @@ pub struct ModelInfo { } impl ModelInfo { + /// Builds a model with no capabilities. Add them with [`ModelInfo::with`]. pub fn new(id: ModelId, label: impl Into) -> Self { Self { id, label: label.into(), capabilities: Vec::new(), pricing: None, released: None, tags: Vec::new(), local_file: None } } + /// Adds a capability spec. pub fn with(mut self, spec: CapabilitySpec) -> Self { self.capabilities.push(spec); self } + /// The spec for `capability`, if the model supports it. pub fn spec_for(&self, capability: &CapabilityId) -> Option<&CapabilitySpec> { self.capabilities.iter().find(|s| &s.capability == capability) } } - -#[cfg(test)] -mod tests { - use super::*; - - fn cap(s: &str) -> CapabilityId { - CapabilityId::parse(s).unwrap() - } - - #[test] - fn a_store_written_before_pricing_existed_still_loads_and_leaves_it_out_when_absent() { - let old = r#"{"id":"gpt-4o","label":"gpt-4o","capabilities":[]}"#; - let info: ModelInfo = serde_json::from_str(old).unwrap(); - assert_eq!((info.pricing.clone(), info.released, info.tags.clone()), (None, None, Vec::new())); - let again = serde_json::to_string(&info).unwrap(); - assert!(!again.contains("pricing") && !again.contains("released") && !again.contains("tags"), "{again}"); - let priced = ModelInfo { - pricing: Some(Pricing { per_image_micros: Some(40_000), ..Pricing::default() }), - released: Some(1_760_000_000), - tags: vec!["recommended".into()], - ..info - }; - let back: ModelInfo = serde_json::from_str(&serde_json::to_string(&priced).unwrap()).unwrap(); - assert_eq!(back, priced); - } - - #[test] - fn input_roles_round_trip_including_custom() { - for text in ["mask", "reference", "depth-map"] { - let r = InputRole::parse(text).unwrap(); - assert_eq!(r.as_str(), text); - assert_eq!(serde_json::from_str::(&serde_json::to_string(&r).unwrap()).unwrap(), r); - } - assert!(InputRole::parse("bad role").is_err()); - } - - #[test] - fn spec_round_trips_with_map_keys() { - let spec = CapabilitySpec::new(cap("image.inpaint")) - .accepting(InputRole::Source, 1) - .accepting(InputRole::Mask, 1) - .accepting(InputRole::Reference, 3) - .requiring(InputRole::Source) - .max_outputs(4); - let json = serde_json::to_string(&spec).unwrap(); - assert!(json.contains("\"reference\":3")); - assert_eq!(serde_json::from_str::(&json).unwrap(), spec); - } - - #[test] - fn missing_fields_take_defaults() { - let spec: CapabilitySpec = serde_json::from_str(r#"{"capability":"text.complete","accepts":{"prompt":1}}"#).unwrap(); - assert_eq!(spec.max_outputs, 1); - assert!(!spec.features.streaming); - assert!(spec.requires.is_empty()); - } - - #[test] - fn model_finds_its_spec() { - let m = ModelInfo::new(ModelId::new("m1").unwrap(), "M1").with(CapabilitySpec::new(cap("image.generate"))); - assert!(m.spec_for(&cap("image.generate")).is_some()); - assert!(m.spec_for(&cap("image.inpaint")).is_none()); - } -} diff --git a/crates/ai-core/src/payload.rs b/crates/ai-core/src/payload.rs index 54a2fd152c..8193120658 100644 --- a/crates/ai-core/src/payload.rs +++ b/crates/ai-core/src/payload.rs @@ -18,7 +18,9 @@ const MAX_URI_LEN: usize = 4096; /// Size limits applied to payloads in a request. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Limits { + /// Largest inline binary payload, in bytes. pub max_inline_bytes: u64, + /// Largest text payload, in bytes. pub max_text_bytes: usize, } @@ -52,6 +54,7 @@ validated_string!( ); impl MediaType { + /// The coarse kind for this media type. Unknown types are `Other`; `application/json` counts as text. pub fn kind(&self) -> PayloadKind { let s = self.as_str(); if s.starts_with("image/") { @@ -75,19 +78,28 @@ impl MediaType { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PayloadKind { + #[allow(missing_docs)] Text, + #[allow(missing_docs)] Image, + #[allow(missing_docs)] Video, + #[allow(missing_docs)] Audio, + /// A document such as a PDF. Document, + /// Any other media type. Other, } /// A reference to data that stays where it is until a provider adapter streams it. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct PayloadHandle { + /// Where the data lives, such as a file path or URL. Never empty and has no control characters. pub uri: String, + /// What the data is. pub media_type: MediaType, + /// Size in bytes, when known. #[serde(default, skip_serializing_if = "Option::is_none")] pub size_bytes: Option, } @@ -96,27 +108,36 @@ pub struct PayloadHandle { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Payload { + /// Plain text. Text { + /// The text. text: String, }, + /// Binary data carried in the payload, serialized as base64. Inline { + /// What the data is. media_type: MediaType, + /// The raw bytes. #[serde(with = "base64_bytes")] data: Vec, }, + /// Data kept where it is, referenced by a handle. Handle(PayloadHandle), } impl Payload { + /// A text payload. pub fn text(text: impl Into) -> Self { Self::Text { text: text.into() } } + /// An inline payload. Fails when `media_type` is not a valid media type. pub fn inline(media_type: &str, data: Vec) -> Result { let media_type = MediaType::new(media_type).map_err(|e| AiError::invalid(format!("media type: {e}")))?; Ok(Self::Inline { media_type, data }) } + /// A handle payload. Fails on an empty, over-long (4096 bytes) or control-character URI, or an invalid media type. pub fn handle(uri: &str, media_type: &str, size_bytes: Option) -> Result { if uri.is_empty() || uri.len() > MAX_URI_LEN || uri.chars().any(char::is_control) { return Err(AiError::invalid("payload uri is empty, too long, or has control characters")); @@ -125,6 +146,7 @@ impl Payload { Ok(Self::Handle(PayloadHandle { uri: uri.to_owned(), media_type, size_bytes })) } + /// The coarse kind: text for `Text`, otherwise from the media type. pub fn kind(&self) -> PayloadKind { match self { Self::Text { .. } => PayloadKind::Text, @@ -224,79 +246,3 @@ mod base64_bytes { super::base64_decode(&text).ok_or_else(|| serde::de::Error::custom("invalid base64")) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn base64_matches_known_vectors() { - for (raw, enc) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("foobar", "Zm9vYmFy")] { - assert_eq!(base64_encode(raw.as_bytes()), enc); - assert_eq!(base64_decode(enc).unwrap(), raw.as_bytes()); - } - } - - #[test] - fn base64_round_trips_all_byte_values() { - let data: Vec = (0..=255u8).collect(); - assert_eq!(base64_decode(&base64_encode(&data)).unwrap(), data); - } - - #[test] - fn base64_rejects_malformed() { - for bad in ["Zg=", "Z", "Zm9v!", "=Zm9", "Zg==Zg==", "Zm=v", "Z===", "Zm9v\n"] { - assert!(base64_decode(bad).is_none(), "{bad:?}"); - } - } - - #[test] - fn media_type_validation() { - assert!(MediaType::new("image/png").is_ok()); - assert!(MediaType::new("application/vnd.api+json").is_ok()); - for bad in ["", "png", "image/", "/png", "Image/PNG", "image/png/x", "image/p ng"] { - assert!(MediaType::new(bad).is_err(), "{bad:?}"); - } - } - - #[test] - fn kinds_follow_media_type() { - assert_eq!(Payload::inline("image/png", vec![1]).unwrap().kind(), PayloadKind::Image); - assert_eq!(Payload::inline("application/pdf", vec![1]).unwrap().kind(), PayloadKind::Document); - assert_eq!(Payload::text("hi").kind(), PayloadKind::Text); - } - - #[test] - fn inline_over_limit_is_refused_with_a_hint() { - let limits = Limits { max_inline_bytes: 4, max_text_bytes: 4 }; - let err = Payload::inline("image/png", vec![0; 5]).unwrap().check(&limits).unwrap_err(); - assert!(err.message.contains("handle")); - assert!(Payload::text("12345").check(&limits).is_err()); - assert!(Payload::text("1234").check(&limits).is_ok()); - } - - #[test] - fn handles_skip_the_inline_limit() { - let limits = Limits { max_inline_bytes: 4, max_text_bytes: 4 }; - let h = Payload::handle("file:///big.mov", "video/quicktime", Some(10_000_000_000)).unwrap(); - assert!(h.check(&limits).is_ok()); - assert_eq!(h.size_hint(), Some(10_000_000_000)); - } - - #[test] - fn handle_rejects_bad_uris() { - assert!(Payload::handle("", "video/mp4", None).is_err()); - assert!(Payload::handle("file:///a\nb", "video/mp4", None).is_err()); - assert!(Payload::handle(&"x".repeat(MAX_URI_LEN + 1), "video/mp4", None).is_err()); - } - - #[test] - fn json_round_trip() { - let p = Payload::inline("image/png", vec![0, 1, 2, 250, 255]).unwrap(); - let json = serde_json::to_string(&p).unwrap(); - assert!(json.contains("\"type\":\"inline\"")); - assert_eq!(serde_json::from_str::(&json).unwrap(), p); - let bad = r#"{"type":"inline","media_type":"image/png","data":"!!"}"#; - assert!(serde_json::from_str::(bad).is_err()); - } -} diff --git a/crates/ai-core/src/picks.rs b/crates/ai-core/src/picks.rs index a6404277dd..4fda7a900a 100644 --- a/crates/ai-core/src/picks.rs +++ b/crates/ai-core/src/picks.rs @@ -27,10 +27,15 @@ pub const MAX_CATALOG_BYTES: usize = 256 * 1024; pub enum Pick { /// The one we would choose: a balance of quality, speed and price. Recommended, + /// The model with the best output quality, as judged by whoever keeps the catalog. BestResult, + /// The model with the lowest reported price. LowestCost, + /// The model judged fastest, as kept in the catalog. Fastest, + /// The most recently released model. Newest, + /// The model judged most used, as kept in the catalog. MostPopular, } @@ -43,6 +48,7 @@ impl Pick { !matches!(self, Pick::LowestCost | Pick::Newest) } + /// The stable text form, used in the catalog file. pub fn key(self) -> &'static str { match self { Pick::Recommended => "recommended", @@ -58,19 +64,23 @@ impl Pick { /// One curated pick: for this job, on this kind of connection, this model earns this tag. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CatalogEntry { + /// The capability the pick is for, as `.`. pub capability: String, /// The tag it earns, as [`Pick::key`]. pub pick: String, /// The connection's provider key, such as `openrouter`. pub provider: String, + /// The model id. pub model: String, } /// The curated picks. Earlier entries for the same job and tag win. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Catalog { + /// Catalog version. [`Catalog::over`] keeps the higher of the two. #[serde(default)] pub version: u32, + /// The picks. Earlier entries win over later ones for the same job and tag. #[serde(default)] pub entries: Vec, } @@ -78,7 +88,9 @@ pub struct Catalog { /// Why a catalog could not be used. #[derive(Clone, Debug, PartialEq, Eq)] pub enum CatalogError { + /// The text is longer than [`MAX_CATALOG_BYTES`]. TooLarge, + /// The text is not valid catalog JSON. The string says why. Syntax(String), } @@ -100,6 +112,7 @@ impl Catalog { Self::from_json(include_str!("catalog.json")).unwrap_or_default() } + /// Parses a catalog file. Fails when it is over [`MAX_CATALOG_BYTES`] or not valid JSON. pub fn from_json(text: &str) -> Result { if text.len() > MAX_CATALOG_BYTES { return Err(CatalogError::TooLarge); @@ -129,6 +142,7 @@ impl Catalog { pub struct Candidate<'a> { /// The connection's provider key. pub provider: &'a str, + /// The model itself. pub model: &'a ModelInfo, /// Running it costs nothing (a local model, a free connection). pub free: bool, @@ -150,8 +164,11 @@ pub enum PickedBy { /// A pick that was earned, and by which candidate (an index into the candidates given). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Picked { + /// The tag earned. pub pick: Pick, + /// Index of the winning candidate in the slice that was ranked. pub candidate: usize, + /// What earned it. pub by: PickedBy, } @@ -211,6 +228,3 @@ fn newest(candidates: &[Candidate<'_>]) -> Option<(usize, PickedBy)> { }) .map(|(i, at)| (i, PickedBy::Released(at))) } - -#[cfg(test)] -mod tests; diff --git a/crates/ai-core/src/picks/tests.rs b/crates/ai-core/src/picks/tests.rs deleted file mode 100644 index a5e1cd7cf9..0000000000 --- a/crates/ai-core/src/picks/tests.rs +++ /dev/null @@ -1,166 +0,0 @@ -use super::*; -use crate::ids::ModelId; - -fn cap(s: &str) -> CapabilityId { - CapabilityId::parse(s).unwrap() -} - -fn model(id: &str, price: Option, released: Option) -> ModelInfo { - let mut m = ModelInfo::new(ModelId::new(id).unwrap(), id); - m.pricing = price.map(|p| Pricing { per_image_micros: Some(p), ..Pricing::default() }); - m.released = released; - m -} - -fn cands<'a>(models: &'a [(&'a str, ModelInfo, bool)]) -> Vec> { - models.iter().map(|(provider, model, free)| Candidate { provider, model, free: *free }).collect() -} - -fn catalog(entries: &[(&str, &str, &str, &str)]) -> Catalog { - Catalog { - version: 1, - entries: entries - .iter() - .map(|(capability, pick, provider, model)| CatalogEntry { - capability: (*capability).into(), - pick: (*pick).into(), - provider: (*provider).into(), - model: (*model).into(), - }) - .collect(), - } -} - -fn find(picks: &[Picked], pick: Pick) -> Option<&Picked> { - picks.iter().find(|p| p.pick == pick) -} - -#[test] -fn the_built_in_catalog_loads_and_starts_empty() { - let c = Catalog::builtin(); - assert_eq!(c.version, 1); - assert!(c.entries.is_empty(), "no curated pick is claimed until it is checked"); -} - -#[test] -fn lowest_cost_and_newest_are_worked_out_from_what_is_reported() { - let models = [ - ("or", model("a-pricey", Some(80_000), Some(300)), false), - ("or", model("b-cheap", Some(20_000), Some(100)), false), - ("or", model("c-new", Some(50_000), Some(900)), false), - ("or", model("d-unpriced", None, None), false), - ]; - let picks = choose(&cap("image.inpaint"), &cands(&models), &Catalog::default()); - let cheapest = find(&picks, Pick::LowestCost).unwrap(); - assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Price(20_000))); - let newest = find(&picks, Pick::Newest).unwrap(); - assert_eq!((newest.candidate, &newest.by), (2, &PickedBy::Released(900))); - assert!(find(&picks, Pick::Recommended).is_none(), "curated picks need the catalog"); -} - -#[test] -fn a_free_model_is_the_lowest_cost_and_unpriced_hosted_models_are_not_guessed_at() { - let models = [ - ("or", model("hosted", Some(1), None), false), - ("comfyui", model("local-sdxl", None, None), true), - ("or", model("unpriced", None, None), false), - ]; - let picks = choose(&cap("image.generate"), &cands(&models), &Catalog::default()); - let cheapest = find(&picks, Pick::LowestCost).unwrap(); - assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Free)); - - let only_unpriced = [("or", model("x", None, None), false)]; - let picks = choose(&cap("image.generate"), &cands(&only_unpriced), &Catalog::default()); - assert!(picks.is_empty(), "no data, no pick: {picks:?}"); -} - -#[test] -fn text_models_compare_input_plus_output_per_million_tokens() { - let text = |id: &str, i: u64, o: u64| { - let mut m = ModelInfo::new(ModelId::new(id).unwrap(), id); - m.pricing = Some(Pricing { input_micros_per_mtok: Some(i), output_micros_per_mtok: Some(o), per_image_micros: None }); - m - }; - let models = [("or", text("big", 3_000_000, 15_000_000), false), ("or", text("small", 150_000, 600_000), false)]; - let picks = choose(&cap("text.complete"), &cands(&models), &Catalog::default()); - let cheapest = find(&picks, Pick::LowestCost).unwrap(); - assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Price(750_000))); -} - -#[test] -fn curated_picks_come_from_the_catalog_and_only_when_the_connection_offers_the_model() { - let models = [("or", model("flux-fill", None, None), false), ("bfl", model("flux-pro", None, None), false)]; - let c = catalog(&[ - // The first entry is for a model nobody offers, so it is skipped for the next. - ("image.inpaint", "recommended", "or", "not-offered"), - ("image.inpaint", "recommended", "bfl", "flux-pro"), - ("image.inpaint", "best_result", "or", "flux-fill"), - // A model on the wrong provider does not match. - ("image.inpaint", "fastest", "bfl", "flux-fill"), - // Another job's entry never leaks across. - ("text.complete", "most_popular", "or", "flux-fill"), - ]); - let picks = choose(&cap("image.inpaint"), &cands(&models), &c); - assert_eq!(find(&picks, Pick::Recommended).map(|p| p.candidate), Some(1)); - assert_eq!(find(&picks, Pick::BestResult).map(|p| p.candidate), Some(0)); - assert_eq!(find(&picks, Pick::Recommended).unwrap().by, PickedBy::Catalog); - assert!(find(&picks, Pick::Fastest).is_none()); - assert!(find(&picks, Pick::MostPopular).is_none()); -} - -#[test] -fn a_model_that_disappears_stops_earning_its_pick() { - let c = catalog(&[("image.inpaint", "recommended", "or", "flux-fill")]); - let with = [("or", model("flux-fill", None, None), false)]; - assert!(find(&choose(&cap("image.inpaint"), &cands(&with), &c), Pick::Recommended).is_some()); - let without = [("or", model("something-else", None, None), false)]; - assert!(choose(&cap("image.inpaint"), &cands(&without), &c).is_empty()); - assert!(choose(&cap("image.inpaint"), &[], &c).is_empty()); -} - -#[test] -fn ties_go_to_the_id_that_sorts_first_so_the_answer_is_stable() { - let models = [("or", model("zeta", Some(10_000), Some(500)), false), ("or", model("alpha", Some(10_000), Some(500)), false)]; - let picks = choose(&cap("image.generate"), &cands(&models), &Catalog::default()); - assert_eq!(find(&picks, Pick::LowestCost).unwrap().candidate, 1); - assert_eq!(find(&picks, Pick::Newest).unwrap().candidate, 1); -} - -#[test] -fn a_catalog_file_loads_and_a_bad_or_oversize_one_is_refused() { - let ok = r#"{"version":2,"entries":[{"capability":"image.inpaint","pick":"recommended","provider":"or","model":"m"}, - {"capability":"image.inpaint","pick":"a_pick_from_the_future","provider":"or","model":"m"}]}"#; - let c = Catalog::from_json(ok).unwrap(); - assert_eq!((c.version, c.entries.len()), (2, 2)); - // The unknown tag is carried but can never match a known pick. - let models = [("or", model("m", None, None), false)]; - let picks = choose(&cap("image.inpaint"), &cands(&models), &c); - assert_eq!(picks.len(), 1); - assert!(matches!(Catalog::from_json("not json"), Err(CatalogError::Syntax(_)))); - assert_eq!(Catalog::from_json(&" ".repeat(MAX_CATALOG_BYTES + 1)), Err(CatalogError::TooLarge)); -} - -#[test] -fn which_picks_are_judgements_and_which_are_computed() { - let curated: Vec<_> = Pick::ALL.into_iter().filter(|p| p.is_curated()).collect(); - assert_eq!(curated, [Pick::Recommended, Pick::BestResult, Pick::Fastest, Pick::MostPopular]); - let keys: std::collections::HashSet<_> = Pick::ALL.into_iter().map(Pick::key).collect(); - assert_eq!(keys.len(), 6); -} - -#[test] -fn a_newer_catalog_wins_over_the_built_in_one_and_the_rest_still_applies() { - let newer = catalog(&[("text.complete", "recommended", "openrouter", "model-new")]); - let built_in = - catalog(&[("text.complete", "recommended", "openrouter", "model-old"), ("text.complete", "best_result", "openrouter", "model-best")]); - let merged = newer.over(built_in); - let models = [ - ("openrouter", model("model-old", None, None), false), - ("openrouter", model("model-new", None, None), false), - ("openrouter", model("model-best", None, None), false), - ]; - let picks = choose(&cap("text.complete"), &cands(&models), &merged); - let by = |p: Pick| picks.iter().find(|x| x.pick == p).map(|x| x.candidate); - assert_eq!(by(Pick::Recommended), Some(1), "the newer entry wins"); - assert_eq!(by(Pick::BestResult), Some(2), "an entry only the old one had still counts"); -} diff --git a/crates/ai-core/src/request.rs b/crates/ai-core/src/request.rs index 27d667860c..917d32238e 100644 --- a/crates/ai-core/src/request.rs +++ b/crates/ai-core/src/request.rs @@ -21,14 +21,18 @@ pub const MAX_PARAMS_BYTES: usize = 64 * 1024; /// One typed input. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Input { + /// What the input is for. pub role: InputRole, + /// The data. pub payload: Payload, } /// A unit of work for a model. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Request { + /// What the model is asked to do. pub capability: CapabilityId, + /// The typed inputs, in the order given. #[serde(default)] pub inputs: Vec, /// Provider-neutral options such as `seed` or `size`. Capped by [`MAX_PARAMS_BYTES`]. @@ -47,25 +51,30 @@ fn one() -> u32 { } impl Request { + /// A request for `capability` with no inputs or params, one output, and no streaming. pub fn new(capability: CapabilityId) -> Self { Self { capability, inputs: Vec::new(), params: Map::new(), outputs: 1, stream: false } } + /// Adds an input. pub fn with_input(mut self, role: InputRole, payload: Payload) -> Self { self.inputs.push(Input { role, payload }); self } + /// Sets a param, replacing any earlier value under `key`. pub fn with_param(mut self, key: &str, value: Value) -> Self { self.params.insert(key.to_owned(), value); self } + /// Sets how many results to return. pub fn with_outputs(mut self, n: u32) -> Self { self.outputs = n; self } + /// Asks for incremental results. pub fn streaming(mut self) -> Self { self.stream = true; self @@ -114,107 +123,3 @@ impl Request { Ok(()) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::error::ErrorKind; - use crate::model::Features; - - fn cap(s: &str) -> CapabilityId { - CapabilityId::parse(s).unwrap() - } - - fn png() -> Payload { - Payload::inline("image/png", vec![1, 2, 3]).unwrap() - } - - fn inpaint_spec() -> CapabilitySpec { - CapabilitySpec::new(cap("image.inpaint")) - .accepting(InputRole::Prompt, 1) - .accepting(InputRole::Source, 1) - .accepting(InputRole::Mask, 1) - .accepting(InputRole::Reference, 1) - .requiring(InputRole::Source) - .requiring(InputRole::Mask) - .max_outputs(3) - } - - fn good() -> Request { - Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()).with_input(InputRole::Mask, png()) - } - - #[test] - fn a_well_formed_request_passes() { - assert!(good().with_input(InputRole::Prompt, Payload::text("a cat")).validate(&inpaint_spec(), &Limits::default()).is_ok()); - } - - #[test] - fn unsupported_input_is_a_clear_error() { - let spec = CapabilitySpec::new(cap("image.generate")).accepting(InputRole::Prompt, 1); - let req = Request::new(cap("image.generate")).with_input(InputRole::Mask, png()); - let err = req.validate(&spec, &Limits::default()).unwrap_err(); - assert_eq!(err.kind, ErrorKind::Unsupported); - assert!(err.message.contains("mask")); - } - - #[test] - fn too_many_references_are_counted_separately_from_masks() { - let req = good().with_input(InputRole::Reference, png()).with_input(InputRole::Reference, png()); - let err = req.validate(&inpaint_spec(), &Limits::default()).unwrap_err(); - assert_eq!(err.kind, ErrorKind::Unsupported); - assert!(err.message.contains("reference")); - } - - #[test] - fn missing_required_input_is_invalid() { - let req = Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()); - let err = req.validate(&inpaint_spec(), &Limits::default()).unwrap_err(); - assert_eq!(err.kind, ErrorKind::InvalidRequest); - assert!(err.message.contains("mask")); - } - - #[test] - fn output_count_is_bounded() { - assert!(good().with_outputs(3).validate(&inpaint_spec(), &Limits::default()).is_ok()); - assert!(good().with_outputs(4).validate(&inpaint_spec(), &Limits::default()).is_err()); - assert!(good().with_outputs(0).validate(&inpaint_spec(), &Limits::default()).is_err()); - } - - #[test] - fn streaming_needs_the_feature() { - let spec = CapabilitySpec::new(cap("text.complete")).accepting(InputRole::Prompt, 1); - let req = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("hi")).streaming(); - assert_eq!(req.validate(&spec, &Limits::default()).unwrap_err().kind, ErrorKind::Unsupported); - let spec = spec.with_features(Features { streaming: true, ..Features::default() }); - assert!(req.validate(&spec, &Limits::default()).is_ok()); - } - - #[test] - fn capability_mismatch_is_invalid() { - let req = Request::new(cap("image.generate")); - assert_eq!(req.validate(&inpaint_spec(), &Limits::default()).unwrap_err().kind, ErrorKind::InvalidRequest); - } - - #[test] - fn oversized_inline_input_is_refused() { - let limits = Limits { max_inline_bytes: 2, max_text_bytes: 10 }; - assert!(good().validate(&inpaint_spec(), &limits).is_err()); - } - - #[test] - fn oversized_params_are_refused() { - let big = Value::String("x".repeat(MAX_PARAMS_BYTES + 1)); - assert!(good().with_param("blob", big).validate(&inpaint_spec(), &Limits::default()).is_err()); - } - - #[test] - fn request_round_trips_and_defaults_apply() { - let req = good().with_param("seed", Value::from(7)).with_outputs(2); - let back: Request = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap(); - assert_eq!(req, back); - let minimal: Request = serde_json::from_str(r#"{"capability":"image.generate"}"#).unwrap(); - assert_eq!(minimal.outputs, 1); - assert!(!minimal.stream); - } -} diff --git a/crates/ai-core/src/role.rs b/crates/ai-core/src/role.rs index 4a70cef70d..2fa1312484 100644 --- a/crates/ai-core/src/role.rs +++ b/crates/ai-core/src/role.rs @@ -19,8 +19,11 @@ use crate::model::{CapabilitySpec, InputRole, ModelInfo}; /// A feature an app offers that needs a model. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Role { + #[allow(missing_docs)] pub id: RoleId, + /// Name shown to the user, such as "Generative Fill". pub label: String, + /// The capability a model must offer to fill the role. pub capability: CapabilityId, /// Inputs this feature will send. A model must accept them and require no others. #[serde(default)] @@ -30,29 +33,63 @@ pub struct Role { /// The user's choice for one role. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Binding { + /// The role being bound. pub role: RoleId, + /// The chosen connection. pub connection: ConnectionId, + /// The chosen model, offered by that connection. pub model: ModelId, } /// A fully checked choice. #[derive(Clone, Copy, Debug)] pub struct Resolved<'a> { + /// The connection to send the job to. pub connection: &'a Connection, + /// The model to run. pub model: &'a ModelInfo, + /// The model's spec for the role's capability. pub spec: &'a CapabilitySpec, } /// Why a role could not be resolved. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ResolveError { + /// No layer has a binding for the role. Unbound(RoleId), + /// The bound connection is not in the list. ConnectionMissing(ConnectionId), + /// The bound connection is switched off. ConnectionDisabled(ConnectionId), - ModelMissing { connection: ConnectionId, model: ModelId }, - CapabilityMismatch { model: ModelId, capability: CapabilityId }, - InputUnsupported { model: ModelId, input: InputRole }, - InputRequired { model: ModelId, input: InputRole }, + /// The bound connection does not offer the bound model. + ModelMissing { + /// The bound connection. + connection: ConnectionId, + /// The bound model. + model: ModelId, + }, + /// The model has no spec for the role's capability. + CapabilityMismatch { + /// The bound model. + model: ModelId, + /// The capability the role needs. + capability: CapabilityId, + }, + /// The role sends an input the model does not accept. + InputUnsupported { + /// The bound model. + model: ModelId, + /// The input the model rejects. + input: InputRole, + }, + /// The model requires an input the role does not send. + InputRequired { + /// The bound model. + model: ModelId, + /// The input the role is missing. + input: InputRole, + }, + /// A tool role differs from the shared definition saved for its id. ToolMismatch(RoleId), } @@ -157,21 +194,6 @@ mod tests { Binding { role: RoleId::new("generative-fill").unwrap(), connection: ConnectionId::new(conn).unwrap(), model: ModelId::new("m").unwrap() } } - #[test] - fn resolves_a_good_binding() { - let conns = [conn("a", true)]; - let defaults = [bind("a")]; - assert!(resolve(&role(), &[&[], &defaults], &conns).is_ok()); - } - - #[test] - fn app_override_beats_default() { - let conns = [conn("a", true), conn("b", true)]; - let (over, def) = ([bind("b")], [bind("a")]); - let r = resolve(&role(), &[&over, &def], &conns).unwrap(); - assert_eq!(r.connection.id.as_str(), "b"); - } - #[test] fn a_broken_override_is_an_error_and_never_falls_through() { let conns = [conn("a", true)]; @@ -179,56 +201,4 @@ mod tests { let err = resolve(&role(), &[&over, &def], &conns).unwrap_err(); assert!(matches!(err, ResolveError::ConnectionMissing(_))); } - - #[test] - fn unbound_and_disabled() { - let mut conns = [conn("a", true)]; - assert!(matches!(resolve(&role(), &[&[]], &conns), Err(ResolveError::Unbound(_)))); - conns[0].enabled = false; - assert!(matches!(resolve(&role(), &[&[bind("a")]], &conns), Err(ResolveError::ConnectionDisabled(_)))); - } - - #[test] - fn a_model_that_cannot_take_a_mask_does_not_resolve() { - let conns = [conn("a", false)]; - let err = resolve(&role(), &[&[bind("a")]], &conns).unwrap_err(); - assert!(matches!(err, ResolveError::InputUnsupported { input: InputRole::Mask, .. })); - } - - #[test] - fn a_required_input_the_role_cannot_supply_has_a_specific_error() { - let mut conns = [conn("a", true)]; - conns[0].models[0].capabilities[0].requires = vec![InputRole::Mask]; - let mut r = role(); - r.inputs = vec![InputRole::Source]; - let err = resolve(&r, &[&[bind("a")]], &conns).unwrap_err(); - assert!(matches!(err, ResolveError::InputRequired { input: InputRole::Mask, .. })); - assert_eq!(err.to_string(), "model m requires a 'mask' input that this tool does not provide"); - } - - #[test] - fn wrong_capability_and_missing_model() { - let mut conns = [conn("a", true)]; - let mut r = role(); - r.capability = cap("image.generate"); - assert!(matches!(resolve(&r, &[&[bind("a")]], &conns), Err(ResolveError::CapabilityMismatch { .. }))); - conns[0].models.clear(); - assert!(matches!(resolve(&role(), &[&[bind("a")]], &conns), Err(ResolveError::ModelMissing { .. }))); - } - - #[test] - fn eligible_filters_by_capability_inputs_and_enabled() { - let mut off = conn("c", true); - off.enabled = false; - let conns = [conn("a", true), conn("b", false), off]; - let list = eligible(&role(), &conns); - assert_eq!(list.len(), 1); - assert_eq!(list[0].connection.id.as_str(), "a"); - } - - #[test] - fn error_messages_read_well() { - let msg = ResolveError::Unbound(RoleId::new("x").unwrap()).to_string(); - assert!(msg.contains("no model is chosen")); - } } diff --git a/crates/ai-core/src/secret.rs b/crates/ai-core/src/secret.rs index 0a40b834db..afef41ade4 100644 --- a/crates/ai-core/src/secret.rs +++ b/crates/ai-core/src/secret.rs @@ -13,6 +13,7 @@ use std::fmt; pub struct SecretString(String); impl SecretString { + /// Wraps a secret value. pub fn new(value: impl Into) -> Self { Self(value.into()) } @@ -22,6 +23,7 @@ impl SecretString { &self.0 } + /// True when the secret has no characters. pub fn is_empty(&self) -> bool { self.0.is_empty() } @@ -73,21 +75,6 @@ pub fn redact(text: &str, secrets: &[&SecretString]) -> String { mod tests { use super::*; - #[test] - fn debug_and_display_never_show_the_value() { - let s = SecretString::new("sk-live-abc123"); - assert!(!format!("{s:?}").contains("abc123")); - assert!(!format!("{s}").contains("abc123")); - assert!(!format!("{:?}", Some(&s)).contains("abc123")); - } - - #[test] - fn redact_scrubs_every_occurrence() { - let s = SecretString::new("sk-live-abc123"); - let out = redact("bad key sk-live-abc123 (sk-live-abc123)", &[&s]); - assert_eq!(out, "bad key [redacted] ([redacted])"); - } - #[test] fn redact_never_searches_its_own_markers() { // Each secret matches the marker the one before it wrote; replacing in turn doubled the @@ -105,10 +92,4 @@ mod tests { assert_eq!(redact("xabcdx", &[&a, &b]), "x[redacted]x"); assert_eq!(redact("abcabc", &[&a]), "[redacted][redacted]"); } - - #[test] - fn redact_ignores_empty_secret() { - let s = SecretString::new(""); - assert_eq!(redact("hello", &[&s]), "hello"); - } } diff --git a/crates/ai-core/src/spec.rs b/crates/ai-core/src/spec.rs index 0712e26699..3957b82ffb 100644 --- a/crates/ai-core/src/spec.rs +++ b/crates/ai-core/src/spec.rs @@ -56,16 +56,23 @@ pub enum SpecAuth { /// `Authorization: Bearer `. Bearer, /// The key is the whole value of this header. - Header { name: String }, + Header { + /// The header name. It must pass the same checks as a connection's key header. + name: String, + }, /// No key. None, } +/// HTTP methods a call may use. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum Method { + #[allow(missing_docs)] Get, + #[allow(missing_docs)] Post, + #[allow(missing_docs)] Delete, } @@ -73,10 +80,14 @@ pub enum Method { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Call { + /// HTTP method. pub method: Method, + /// Path joined to the spec's `base`. Starts with `/` and cannot name another host. pub path: String, + /// Query parameters. Values may use the substitutions allowed for the call. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub query: BTreeMap, + /// JSON body template. Substitutions apply inside its string values only. #[serde(default, skip_serializing_if = "Option::is_none")] pub body: Option, } @@ -93,13 +104,16 @@ pub enum ExtractAs { Text, } +/// Where in a reply to find a result, and what kind of data it is. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Extract { /// A JSON pointer (RFC 6901) into the reply. pub at: String, + /// How to read the value at `at`. Written `as` in the spec file. #[serde(rename = "as")] pub kind: ExtractAs, + /// Media type of the result, such as `image/png`. Required for `base64` and `url`. #[serde(default, skip_serializing_if = "Option::is_none")] pub media_type: Option, } @@ -108,40 +122,60 @@ pub struct Extract { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StateWord { + /// The provider has accepted the job but not started it. Queued, + /// The job is in progress. Running, + /// The job finished and the result is ready. Succeeded, + /// The job failed. Failed, } +/// The call that starts a queued job. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Submit { + /// The call to make. pub call: Call, /// Pointer to the job id in the reply. pub job_id_at: String, } +/// The repeated call that checks a queued job and reads its result. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Poll { + /// The call to make. It may use `{job_id}`. pub call: Call, + /// JSON pointer to the status word in the reply. pub status_at: String, + /// Maps each status word the provider uses to one of the four states. A word not listed is an error. pub states: BTreeMap, + /// Where to read the result once the job has succeeded. pub result: Extract, } // A spec is loaded once and read many times; boxing the queue variant would only add noise. +/// How a request becomes a result: one call, or a submit and poll queue. #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum Flow { /// One call whose reply holds the result. - RequestResponse { call: Call, result: Extract }, + RequestResponse { + /// The one call to make. + call: Call, + /// Where the result is in the reply. + result: Extract, + }, /// Submit, then ask for the result until it is ready. Queue { + /// The call that starts the job. submit: Submit, + /// The call that checks it. poll: Poll, + /// Optional call that cancels the job. #[serde(default, skip_serializing_if = "Option::is_none")] cancel: Option, }, @@ -151,13 +185,18 @@ pub enum Flow { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SpecModel { + /// Model id, as the provider names it. Must be a valid [`ModelId`]. pub id: String, + /// Name shown to the user. pub label: String, + /// The capability the model offers, as `.`. pub capability: String, /// Input role to the most of it the model takes. pub accepts: BTreeMap, + /// Input roles that must be sent. Every model must require `prompt`. #[serde(default)] pub requires: Vec, + /// Most outputs one request can return. Defaults to 1. #[serde(default = "one")] pub max_outputs: u32, } @@ -196,18 +235,25 @@ impl Default for SpecLimits { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Spec { + /// Must equal [`SPEC_VERSION`]. pub spec_version: u32, + /// Id for the connection this spec makes. Must be a valid [`ConnectionId`](crate::ids::ConnectionId). pub id: String, + /// Name shown to the user, 1 to 120 plain characters. pub label: String, /// `https://host[/prefix]`, or `http://` for a loopback host. pub base: String, + /// How the key is sent. Defaults to a bearer token. #[serde(default = "bearer")] pub auth: SpecAuth, /// A free, read-only request for the Test button. #[serde(default, skip_serializing_if = "Option::is_none")] pub probe: Option, + /// The models the spec offers, at most [`MAX_MODELS`]. pub models: Vec, + /// How a request becomes a result. pub flow: Flow, + /// Bounds on one job. #[serde(default)] pub limits: SpecLimits, } diff --git a/crates/ai-core/src/spec/check.rs b/crates/ai-core/src/spec/check.rs index 20ef5f4fdc..b3fa0a8371 100644 --- a/crates/ai-core/src/spec/check.rs +++ b/crates/ai-core/src/spec/check.rs @@ -21,6 +21,7 @@ use crate::payload::validate_media_type; pub struct SpecError { /// Where in the spec, such as `flow.submit.call.path`. pub at: String, + /// What is wrong and what to do about it, in plain words. pub why: String, } diff --git a/crates/ai-core/src/spec/template.rs b/crates/ai-core/src/spec/template.rs index bc1d79b4c9..8d32603a5e 100644 --- a/crates/ai-core/src/spec/template.rs +++ b/crates/ai-core/src/spec/template.rs @@ -9,8 +9,11 @@ use serde_json::Value; /// A value a template may name. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Slot { + /// The user's prompt text. Prompt, + /// The model id. Model, + /// The job id a submit call returned. Only calls after the submit may use it. JobId, } @@ -28,8 +31,11 @@ impl Slot { /// The values for one call. A slot left `None` cannot be used by that call. #[derive(Clone, Copy, Debug, Default)] pub struct Values<'a> { + /// Text for `{prompt}`. pub prompt: Option<&'a str>, + /// Text for `{model}`. pub model: Option<&'a str>, + /// Text for `{job_id}`. pub job_id: Option<&'a str>, } diff --git a/crates/ai-core/src/store.rs b/crates/ai-core/src/store.rs index 78966f1c69..55ce27ffd2 100644 --- a/crates/ai-core/src/store.rs +++ b/crates/ai-core/src/store.rs @@ -35,12 +35,15 @@ pub struct AppSettings { /// The whole store. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct StoreFile { + /// Version of the file format, checked before anything else. [`SCHEMA_VERSION`] is the one this build writes. pub schema_version: u32, + /// The saved connections. Ids must be unique. #[serde(default)] pub connections: Vec, /// Default bindings, set in the launcher, used by every app unless it overrides. #[serde(default)] pub defaults: Vec, + /// Per-app settings, keyed by app id. #[serde(default)] pub apps: BTreeMap, /// User-declared tool contracts, shared across the suite. A declaration does not install an adapter. @@ -51,23 +54,37 @@ pub struct StoreFile { /// Why a store file was refused. #[derive(Clone, Debug, PartialEq, Eq)] pub enum StoreError { + /// The file is over [`MAX_STORE_BYTES`]. TooLarge { + /// Size of the file in bytes. len: usize, + /// The limit in bytes. max: usize, }, + /// The file is not valid JSON for this schema. The string says why. Syntax(String), /// Written by a newer version. Do not write to it. TooNew { + /// The file's schema version. found: u32, + /// The newest schema version this build reads. supported: u32, }, + /// The schema version is 0. BadVersion(u32), + /// Two connections share this id. DuplicateConnection(ConnectionId), + /// Two custom tools share this id. DuplicateTool(RoleId), + /// More than 64 custom tools. The number is the count found. TooManyTools(usize), + /// A custom tool has an empty or over-long label, or no inputs, more than 8, or a repeated one. InvalidTool(RoleId), + /// A connection failed its own validation. Invalid { + /// The connection that failed. connection: ConnectionId, + /// The rule it broke. why: ConnectionError, }, } @@ -152,6 +169,7 @@ impl StoreFile { Ok(()) } + /// Serializes the store as pretty-printed JSON. Does not validate; call [`StoreFile::validate`] first. pub fn to_json(&self) -> Result { serde_json::to_string_pretty(self).map_err(|e| StoreError::Syntax(e.to_string())) } @@ -204,95 +222,6 @@ mod tests { StoreFile { connections: vec![c], defaults: vec![binding], ..StoreFile::default() } } - fn role() -> Role { - Role { id: RoleId::new("rewrite").unwrap(), label: "Rewrite".into(), capability: cap(), inputs: vec![InputRole::Prompt] } - } - - #[test] - fn round_trips() { - let s = store(); - assert_eq!(StoreFile::parse(&s.to_json().unwrap()).unwrap(), s); - } - - #[test] - fn unknown_fields_are_ignored() { - let mut v: serde_json::Value = serde_json::from_str(&store().to_json().unwrap()).unwrap(); - v["added_in_a_later_release"] = serde_json::json!({"x": 1}); - v["connections"][0]["new_flag"] = serde_json::json!(true); - assert!(StoreFile::parse(&v.to_string()).is_ok()); - } - - #[test] - fn a_newer_schema_is_refused_even_if_its_shape_changed() { - let text = r#"{"schema_version": 2, "connections": "now a different shape"}"#; - assert_eq!(StoreFile::parse(text), Err(StoreError::TooNew { found: 2, supported: SCHEMA_VERSION })); - } - - #[test] - fn bad_input_is_an_error_not_a_panic() { - for text in - ["", "not json", "[]", "{}", r#"{"schema_version": 0}"#, r#"{"schema_version": -1}"#, r#"{"schema_version": 1, "connections": [1]}"#] - { - assert!(StoreFile::parse(text).is_err(), "{text:?}"); - } - let big = format!("{{\"schema_version\":1,\"pad\":\"{}\"}}", "x".repeat(MAX_STORE_BYTES)); - assert!(matches!(StoreFile::parse(&big), Err(StoreError::TooLarge { .. }))); - } - - #[test] - fn a_mislabelled_connection_is_refused_at_load() { - let mut s = store(); - s.connections[0].locality = crate::connection::Locality::Local; - let err = StoreFile::parse(&s.to_json().unwrap()).unwrap_err(); - assert!(matches!(err, StoreError::Invalid { .. })); - } - - #[test] - fn duplicate_connections_are_refused() { - let mut s = store(); - s.connections.push(s.connections[0].clone()); - assert!(matches!(s.validate(), Err(StoreError::DuplicateConnection(_)))); - } - - #[test] - fn resolve_uses_default_then_app_override() { - let mut s = store(); - let app = AppId::new("wordcraft").unwrap(); - assert_eq!(s.resolve(&app, &role()).unwrap().connection.id.as_str(), "a"); - let mut other = remote("b"); - other.models = s.connections[0].models.clone(); - s.connections.push(other); - let over = Binding { role: RoleId::new("rewrite").unwrap(), connection: ConnectionId::new("b").unwrap(), model: ModelId::new("m").unwrap() }; - s.apps.insert(app.clone(), AppSettings { overrides: vec![over] }); - assert_eq!(s.resolve(&app, &role()).unwrap().connection.id.as_str(), "b"); - assert_eq!(s.resolve(&AppId::new("photocraft").unwrap(), &role()).unwrap().connection.id.as_str(), "a"); - } - - #[test] - fn dangling_bindings_are_reported() { - let mut s = store(); - s.connections.clear(); - assert_eq!(s.dangling_bindings().len(), 1); - } - - #[test] - fn truncated_and_mutated_files_never_panic() { - let text = store().to_json().unwrap(); - for end in 0..=text.len() { - if text.is_char_boundary(end) { - let _ = StoreFile::parse(&text[..end]); - } - } - let bytes = text.as_bytes(); - for i in (0..bytes.len()).step_by(7) { - let mut copy = bytes.to_vec(); - copy[i] = copy[i].wrapping_add(1); - if let Ok(s) = String::from_utf8(copy) { - let _ = StoreFile::parse(&s); - } - } - } - #[test] fn serialized_store_contains_no_secret_values() { let json = store().to_json().unwrap(); diff --git a/crates/ai-core/tests/contract_regressions.rs b/crates/ai-core/tests/contract_regressions.rs index 86ef0f3967..6c1ed44a44 100644 --- a/crates/ai-core/tests/contract_regressions.rs +++ b/crates/ai-core/tests/contract_regressions.rs @@ -1,4 +1,5 @@ -use craft_ai_core::role::{eligible, fits, resolve}; +//! Integration tests of craft-ai-core: contract regressions. + use craft_ai_core::*; fn draft(endpoint: &str) -> ConnectionDraft { @@ -13,154 +14,6 @@ fn models(id: &str) -> Vec { vec![ModelInfo::new(ModelId::new(id).unwrap(), id)] } -#[test] -fn new_draft_discards_models_when_address_changes_after_probe() { - let mut draft = draft("https://a.example/v1"); - assert!(draft.set_models("https://a.example/v1", models("a-only"))); - draft.endpoint = "https://b.example/v1".into(); - assert!(draft.prepare(&[]).unwrap().connection.models.is_empty()); -} - -#[test] -fn returning_to_original_address_does_not_keep_another_addresses_models() { - let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection; - let mut draft = ConnectionDraft::from_connection(&saved); - draft.endpoint = "https://b.example/v1".into(); - assert!(draft.set_models("https://b.example/v1", models("b-only"))); - draft.endpoint = "https://a.example/v1".into(); - assert!(draft.prepare(&[saved]).unwrap().connection.models.is_empty()); -} - -#[test] -fn changing_model_contents_does_not_establish_address_provenance() { - let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection; - let mut draft = ConnectionDraft::from_connection(&saved); - draft.models = models("refreshed-at-a"); - draft.endpoint = "https://b.example/v1".into(); - assert!(draft.prepare(&[saved]).unwrap().connection.models.is_empty()); -} - -#[test] -fn preset_models_belong_to_the_preset_address() { - let preset = PRESETS.iter().find(|preset| preset.key == "vertex-express").unwrap(); - let mut draft = ConnectionDraft::from_preset(preset); - draft.key = "test-key".into(); - assert!(!draft.prepare(&[]).unwrap().connection.models.is_empty()); - draft.endpoint = "https://other.example/v1".into(); - assert!(draft.prepare(&[]).unwrap().connection.models.is_empty()); -} - -#[test] -fn a_fresh_test_at_each_address_keeps_its_models() { - let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection; - let mut draft = ConnectionDraft::from_connection(&saved); - for address in ["https://b.example/v1", "https://a.example/v1", "https://c.example/v1"] { - draft.endpoint = format!(" {address} "); - assert!(draft.set_models(address, models("same-model"))); - assert_eq!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, models("same-model")); - } -} - -#[test] -fn editing_and_returning_without_a_probe_preserves_original_models() { - let mut saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection; - saved.models = models("a-only"); - let mut draft = ConnectionDraft::from_connection(&saved); - draft.endpoint = "https://b.example/v1".into(); - assert!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty()); - draft.endpoint = "https://a.example/v1".into(); - assert_eq!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, saved.models); -} - -#[test] -fn custom_manual_models_still_work_for_a_new_connection_and_unchanged_address() { - let mut draft = ConnectionDraft::custom(); - draft.endpoint = "https://custom.example/v1".into(); - draft.uses_key = false; - draft.models = models("manual-model"); - let saved = draft.prepare(&[]).unwrap().connection; - assert_eq!(saved.models, models("manual-model")); - let mut edited = ConnectionDraft::from_connection(&saved); - edited.models = models("other-manual-model"); - assert_eq!(edited.prepare(&[saved]).unwrap().connection.models, models("other-manual-model")); -} - -fn role_and_connection() -> (Role, Connection, Binding) { - let capability = CapabilityId::parse("image.inpaint").unwrap(); - let role = Role { - id: RoleId::new("source-only").unwrap(), - label: "Source only".into(), - capability: capability.clone(), - inputs: vec![InputRole::Source], - }; - let mut connection = draft("https://a.example/v1").prepare(&[]).unwrap().connection; - connection.models = vec![ - ModelInfo::new(ModelId::new("needs-mask").unwrap(), "Needs mask").with( - CapabilitySpec::new(capability) - .accepting(InputRole::Source, 1) - .accepting(InputRole::Mask, 1) - .requiring(InputRole::Source) - .requiring(InputRole::Mask), - ), - ]; - let binding = Binding { role: role.id.clone(), connection: connection.id.clone(), model: connection.models[0].id.clone() }; - (role, connection, binding) -} - -#[test] -fn model_picker_excludes_inputs_the_tool_cannot_supply() { - let (role, connection, _) = role_and_connection(); - let request = Request::new(role.capability.clone()).with_input(InputRole::Source, Payload::inline("image/png", vec![1]).unwrap()); - assert!(request.validate(&connection.models[0].capabilities[0], &Limits::default()).is_err()); - assert!(fits(&role, &connection.models[0]).is_none()); - assert!(eligible(&role, &[connection]).is_empty()); -} - -#[test] -fn binding_resolution_rejects_inputs_the_tool_cannot_supply() { - let (role, connection, binding) = role_and_connection(); - assert!(resolve(&role, &[&[binding]], &[connection]).is_err()); -} - -#[test] -fn required_inputs_resolve_when_supplied_and_optional_inputs_need_not_be_sent() { - let (mut role, mut connection, binding) = role_and_connection(); - role.inputs.push(InputRole::Mask); - assert!(fits(&role, &connection.models[0]).is_some()); - assert!(resolve(&role, &[std::slice::from_ref(&binding)], std::slice::from_ref(&connection)).is_ok()); - role.inputs = vec![InputRole::Source]; - connection.models[0].capabilities[0].requires = vec![InputRole::Source]; - assert!(fits(&role, &connection.models[0]).is_some()); - assert!(resolve(&role, &[&[binding]], &[connection]).is_ok()); -} - -#[test] -fn a_test_that_answers_after_the_address_moved_on_is_dropped() { - let mut draft = draft("https://a.example/v1"); - // The test is started against a.example; the address is edited while it runs. - draft.endpoint = "https://b.example/v1".into(); - assert!(!draft.set_models("https://a.example/v1", models("a-only")), "a late answer is not taken"); - assert!(draft.models.is_empty(), "and it leaves the form's models alone"); - assert!(draft.prepare(&[]).unwrap().connection.models.is_empty()); -} - -#[test] -fn a_test_that_answers_while_its_address_still_stands_is_taken() { - let mut draft = draft("https://a.example/v1"); - assert!(draft.set_models(" https://a.example/v1 ", models("a-only")), "whitespace is not a different address"); - assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("a-only")); -} - -#[test] -fn a_late_answer_does_not_overwrite_the_newer_address_own_models() { - let mut draft = draft("https://a.example/v1"); - draft.endpoint = "https://b.example/v1".into(); - // The test at b.example answers first; the older one at a.example arrives afterwards. - assert!(draft.set_models("https://b.example/v1", models("b-only"))); - assert!(!draft.set_models("https://a.example/v1", models("a-only"))); - assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("b-only"), "the newer answer stands"); -} - #[test] fn an_answer_is_judged_by_its_address_not_by_how_long_it_waited() { // Identity here is the address, not the test. After a.example → b.example → a.example, an @@ -175,24 +28,3 @@ fn an_answer_is_judged_by_its_address_not_by_how_long_it_waited() { assert!(draft.set_models("https://a.example/v1", models("a-only")), "an answer for the address on the form is taken"); assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("a-only")); } - -#[test] -fn a_refused_answer_leaves_models_already_on_the_form_untouched() { - let mut draft = draft("https://a.example/v1"); - assert!(draft.set_models("https://a.example/v1", models("a-only"))); - draft.endpoint = "https://b.example/v1".into(); - assert!(!draft.set_models("https://a.example/v1", models("a-stale"))); - assert_eq!(draft.models, models("a-only"), "the refused set is not written over the form"); -} - -#[test] -fn an_address_differing_only_in_case_or_a_trailing_slash_is_a_different_address() { - // The comparison is on the field's text, not a parsed URL: Endpoint drops the path, so - // /v1 and /v2 would look equal through it. Differing the other way is safe — the answer is - // refused and the person tests again — so this pins which way it fails. - for other in ["https://A.Example/v1", "https://a.example/v1/", "https://a.example/v2"] { - let mut draft = draft("https://a.example/v1"); - assert!(!draft.set_models(other, models("x")), "{other} is not the field's address"); - assert!(draft.models.is_empty()); - } -} diff --git a/crates/ai-core/tests/custom_connection.rs b/crates/ai-core/tests/custom_connection.rs index f209dbe463..340ab45ab7 100644 --- a/crates/ai-core/tests/custom_connection.rs +++ b/crates/ai-core/tests/custom_connection.rs @@ -1,8 +1,7 @@ //! u1: the rules for a custom (unlisted, OpenAI-shaped) connection: a named key header, and what //! a stored file may carry. The form is `ConnectionDraft`; these tests go through its public API. -use craft_ai_core::connection::ConnectionError; -use craft_ai_core::{Billing, Connection, ConnectionDraft, Field, KeyChange, Locality}; +use craft_ai_core::{ConnectionDraft, Field}; fn custom(endpoint: &str, header: &str) -> ConnectionDraft { let mut d = ConnectionDraft::custom(); @@ -13,42 +12,6 @@ fn custom(endpoint: &str, header: &str) -> ConnectionDraft { d } -#[test] -fn the_custom_form_starts_from_the_other_preset_with_billing_unknown() { - let d = ConnectionDraft::custom(); - assert!(d.is_custom()); - assert_eq!(d.provider, "openai-compatible"); - assert_eq!(d.billing, Billing::Unknown); - assert!(d.uses_key); - assert!(d.key_header.is_empty()); - assert!(d.models.is_empty()); -} - -#[test] -fn without_a_header_name_the_key_goes_as_a_bearer_token() { - let p = custom("https://gw.example.com/ai/v7", "").prepare(&[]).unwrap(); - assert_eq!(p.connection.key_header, None); - let json = serde_json::to_string(&p.connection).unwrap(); - assert!(!json.contains("key_header"), "{json}"); -} - -#[test] -fn a_named_header_is_kept_saved_and_edited_back() { - let p = custom("https://gw.example.com/ai/v7", " X-Api-Key ").prepare(&[]).unwrap(); - assert_eq!(p.connection.key_header.as_deref(), Some("X-Api-Key")); - assert_eq!(p.connection.endpoint.as_deref(), Some("https://gw.example.com/ai/v7")); - assert_eq!(p.connection.locality, Locality::Remote); - assert!(matches!(p.key, KeyChange::Set(_))); - - let again: Connection = serde_json::from_str(&serde_json::to_string(&p.connection).unwrap()).unwrap(); - assert_eq!(again, p.connection); - let edit = ConnectionDraft::from_connection(&again); - assert_eq!(edit.key_header, "X-Api-Key"); - let kept = edit.prepare(std::slice::from_ref(&again)).unwrap(); - assert_eq!(kept.connection.key_header.as_deref(), Some("X-Api-Key")); - assert!(matches!(kept.key, KeyChange::Keep)); -} - #[test] fn header_names_that_could_break_the_request_are_refused() { let long = "a".repeat(65); @@ -74,35 +37,3 @@ fn header_names_that_could_break_the_request_are_refused() { assert!(!e.message.contains("k-123"), "{bad:?}"); } } - -#[test] -fn ordinary_key_header_names_are_accepted() { - for ok in ["x-api-key", "api-key", "X-Goog-Api-Key", "apikey", "x_token"] { - custom("https://gw.example.com/v1", ok).prepare(&[]).unwrap_or_else(|e| panic!("{ok}: {e}")); - } -} - -#[test] -fn a_header_name_without_a_key_is_refused() { - let mut d = custom("http://127.0.0.1:9000/v1", "x-api-key"); - d.uses_key = false; - d.key.clear(); - assert_eq!(d.prepare(&[]).unwrap_err().field, Field::KeyHeader); -} - -#[test] -fn a_stored_file_with_a_bad_header_name_is_refused_on_validate() { - let mut c = custom("https://gw.example.com/v1", "x-api-key").prepare(&[]).unwrap().connection; - assert!(c.validate().is_ok()); - c.key_header = Some("host".to_owned()); - assert!(matches!(c.validate(), Err(ConnectionError::KeyHeader(_)))); - c.key_header = Some("x-api-key".to_owned()); - c.auth = craft_ai_core::Auth::None; - assert!(matches!(c.validate(), Err(ConnectionError::KeyHeader(_)))); -} - -#[test] -fn plain_http_to_a_remote_host_is_still_refused_for_a_custom_address() { - let e = custom("http://gw.example.com/v1", "x-api-key").prepare(&[]).unwrap_err(); - assert_eq!(e.field, Field::Address); -} diff --git a/crates/ai-core/tests/custom_tools.rs b/crates/ai-core/tests/custom_tools.rs deleted file mode 100644 index 674272793a..0000000000 --- a/crates/ai-core/tests/custom_tools.rs +++ /dev/null @@ -1,69 +0,0 @@ -use craft_ai_core::{CapabilityId, InputRole, Role, RoleId, StoreFile}; - -fn tool(id: &str) -> Role { - Role { - id: RoleId::new(id).unwrap(), - label: "Describe photograph".into(), - capability: CapabilityId::parse("image.describe").unwrap(), - inputs: vec![InputRole::Source], - } -} - -#[test] -fn duplicate_user_tool_ids_are_refused_before_the_store_is_written() { - let store = StoreFile { custom_tools: vec![tool("describe-photo"), tool("describe-photo")], ..StoreFile::default() }; - assert!(store.validate().is_err()); -} - -#[test] -fn old_store_loads_and_user_tool_round_trips() { - let old = r#"{"schema_version":1,"connections":[],"defaults":[],"apps":{}}"#; - let mut store = StoreFile::parse(old).unwrap(); - assert!(store.custom_tools.is_empty()); - store.custom_tools.push(tool("describe-photo")); - let again = StoreFile::parse(&store.to_json().unwrap()).unwrap(); - assert_eq!(again.custom_tools, store.custom_tools); - assert_eq!(again.custom_tools[0].capability.as_str(), "image.describe"); -} - -#[test] -fn hostile_tool_declarations_are_refused_on_load() { - let mut s = StoreFile { custom_tools: vec![tool("describe-photo"); 65], ..StoreFile::default() }; - assert!(s.validate().is_err()); - s.custom_tools.truncate(1); - s.custom_tools[0].inputs.push(InputRole::Source); - assert!(StoreFile::parse(&s.to_json().unwrap()).is_err()); - s.custom_tools[0].inputs = vec![InputRole::Source]; - s.custom_tools[0].label = " \t ".into(); - assert!(StoreFile::parse(&s.to_json().unwrap()).is_err()); - s.custom_tools[0].label = "x".repeat(121); - assert!(StoreFile::parse(&s.to_json().unwrap()).is_err()); - s.custom_tools[0].label = "Describe photograph".into(); - s.custom_tools[0].inputs.clear(); - assert!(StoreFile::parse(&s.to_json().unwrap()).is_err()); -} - -#[test] -fn an_app_cannot_reinterpret_the_inputs_of_a_shared_custom_tool() { - use craft_ai_core::role::ResolveError; - use craft_ai_core::{AppId, Binding, CapabilitySpec, Connection, ConnectionId, ModelId, ModelInfo}; - let shared = tool("describe-photo"); - let model = ModelInfo::new(ModelId::new("m").unwrap(), "M").with(CapabilitySpec::new(shared.capability.clone()).accepting(InputRole::Source, 1)); - let connection: Connection = serde_json::from_value(serde_json::json!({ - "id":"service", "label":"Service", "provider":"test", - "endpoint":"http://127.0.0.1:9", "locality":"local", "auth":{"kind":"none"}, - "billing":"free", "models":[model] - })) - .unwrap(); - let store = StoreFile { - connections: vec![connection], - defaults: vec![Binding { role: shared.id.clone(), connection: ConnectionId::new("service").unwrap(), model: ModelId::new("m").unwrap() }], - custom_tools: vec![shared.clone()], - ..StoreFile::default() - }; - let app = AppId::new("photocraft").unwrap(); - assert!(store.resolve(&app, &shared).is_ok()); - let mut redefined = shared; - redefined.inputs.clear(); - assert!(matches!(store.resolve(&app, &redefined), Err(ResolveError::ToolMismatch(_)))); -} diff --git a/crates/ai-core/tests/main.rs b/crates/ai-core/tests/main.rs new file mode 100644 index 0000000000..393ae7e4e6 --- /dev/null +++ b/crates/ai-core/tests/main.rs @@ -0,0 +1,8 @@ +//! Integration tests, built into the library's own test executable. + +mod contract_regressions; +mod custom_connection; +mod mock_conformance; +mod spec_rules; +mod spec_support; +mod spec_template; diff --git a/crates/ai-core/tests/mock_conformance.rs b/crates/ai-core/tests/mock_conformance.rs index 26fe5ed28a..41c67cf7b0 100644 --- a/crates/ai-core/tests/mock_conformance.rs +++ b/crates/ai-core/tests/mock_conformance.rs @@ -1,12 +1,8 @@ -//! Drives the mock provider through the shared conformance checks, and shows the model working -//! end to end the way an app would use it: declare roles, resolve through the store, check -//! consent, submit, poll, cancel. Also proves one library serves different modalities. +//! Drives the mock provider through the shared conformance checks. -use craft_ai_core::conformance::{run_cancel, run_lifecycle, run_rejects, run_unknown_job}; -use craft_ai_core::consent::Disclosure; +use craft_ai_core::conformance::run_lifecycle; use craft_ai_core::job::{Event, JobState, Output}; use craft_ai_core::mock::{MockProvider, Outcome, Script}; -use craft_ai_core::role::{Binding, Role}; use craft_ai_core::*; fn cap(s: &str) -> CapabilityId { @@ -33,16 +29,6 @@ fn image_model() -> ModelInfo { ) } -fn text_model() -> ModelInfo { - ModelInfo::new(model_id("txt"), "Text model").with( - CapabilitySpec::new(cap("text.complete")).accepting(InputRole::Prompt, 1).accepting(InputRole::System, 1).with_features(Features { - streaming: true, - tools: true, - structured_output: true, - }), - ) -} - fn inpaint_request() -> Request { Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()).with_input(InputRole::Mask, png()).with_outputs(2) } @@ -58,104 +44,3 @@ fn image_job_passes_the_lifecycle_and_returns_variations() { assert_eq!(done.state, JobState::Succeeded); assert_eq!(done.events.iter().filter(|e| matches!(e, Event::Output(_))).count(), 2); } - -#[test] -fn text_job_streams_deltas_in_order() { - let script = Script { text_chunks: vec!["Hel".into(), "lo ".into(), "world".into()], ..Script::default() }; - let p = MockProvider::new(vec![text_model()], script); - let req = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("say hello")).streaming(); - let done = run_lifecycle(&p, &model_id("txt"), &req).unwrap(); - let text: String = done.events.iter().filter_map(|e| if let Event::TextDelta { text } = e { Some(text.as_str()) } else { None }).collect(); - assert_eq!(text, "Hello world"); -} - -#[test] -fn failure_is_reported_with_its_kind() { - let err = AiError::new(ErrorKind::Quota, "out of credits"); - let p = MockProvider::new(vec![image_model()], Script { outcome: Outcome::Fail(err.clone()), ..Script::default() }); - let done = run_lifecycle(&p, &model_id("img"), &inpaint_request()).unwrap(); - assert_eq!(done.state, JobState::Failed { error: err }); -} - -#[test] -fn cancel_mid_job_ends_cancelled() { - let p = MockProvider::new(vec![image_model()], Script { running_polls: 50, ..Script::default() }); - run_cancel(&p, &model_id("img"), &inpaint_request()).unwrap(); -} - -#[test] -fn unsupported_requests_are_refused_before_sending() { - let p = MockProvider::new(vec![image_model(), text_model()], Script::default()); - let with_reference = inpaint_request().with_input(InputRole::Reference, png()); - run_rejects(&p, &model_id("img"), &with_reference, ErrorKind::Unsupported).unwrap(); - let too_many = inpaint_request().with_outputs(9); - run_rejects(&p, &model_id("img"), &too_many, ErrorKind::Unsupported).unwrap(); - let missing_mask = Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()); - run_rejects(&p, &model_id("img"), &missing_mask, ErrorKind::InvalidRequest).unwrap(); - let wrong_model = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("x")); - run_rejects(&p, &model_id("img"), &wrong_model, ErrorKind::Unsupported).unwrap(); -} - -#[test] -fn unknown_jobs_are_errors() { - run_unknown_job(&MockProvider::new(vec![image_model()], Script::default())).unwrap(); -} - -#[test] -fn an_app_flow_from_store_to_finished_job() { - // The launcher's store: one remote connection offering both models, defaults for two apps' roles. - let conn = Connection { - id: ConnectionId::new("conn1").unwrap(), - label: "My provider".into(), - provider: "http".into(), - endpoint: Some("https://api.example.com".into()), - locality: Locality::Remote, - auth: Auth::ApiKey { secret: SecretRef::new("secret-conn1").unwrap() }, - billing: Billing::Metered, - models: vec![image_model(), text_model()], - enabled: true, - key_header: None, - }; - let fill = Role { - id: RoleId::new("generative-fill").unwrap(), - label: "Generative Fill".into(), - capability: cap("image.inpaint"), - inputs: vec![InputRole::Source, InputRole::Mask], - }; - let rewrite = - Role { id: RoleId::new("rewrite").unwrap(), label: "Rewrite".into(), capability: cap("text.complete"), inputs: vec![InputRole::Prompt] }; - let bind = |role: &Role, model: &str| Binding { role: role.id.clone(), connection: conn.id.clone(), model: model_id(model) }; - let store = StoreFile { connections: vec![conn.clone()], defaults: vec![bind(&fill, "img"), bind(&rewrite, "txt")], ..StoreFile::default() }; - let store = StoreFile::parse(&store.to_json().unwrap()).unwrap(); - - // Two different apps resolve their own roles from the same store. - let photocraft = AppId::new("photocraft").unwrap(); - let wordcraft = AppId::new("wordcraft").unwrap(); - let resolved = store.resolve(&photocraft, &fill).unwrap(); - assert_eq!(resolved.model.id.as_str(), "img"); - assert_eq!(store.resolve(&wordcraft, &rewrite).unwrap().model.id.as_str(), "txt"); - - // Consent is required for a remote connection, shows kinds and sizes, and is remembered. - let request = inpaint_request().with_input(InputRole::Prompt, Payload::text("remove the lamp")); - let disclosure = Disclosure::for_request(&photocraft, resolved.connection, &request); - let mut ledger = ConsentLedger::default(); - assert!(ledger.needs_consent(&disclosure, 0)); - ledger.grant(&disclosure); - assert!(!ledger.needs_consent(&disclosure, 0)); - - // Run it through a provider built from the same model list. - let provider = MockProvider::new(resolved.connection.models.clone(), Script { outcome: Outcome::Succeed(two_outputs()), ..Script::default() }); - resolved.spec.validate_request(&request).unwrap(); - let done = run_lifecycle(&provider, &resolved.model.id, &request).unwrap(); - assert_eq!(done.state, JobState::Succeeded); -} - -trait ValidateRequest { - fn validate_request(&self, r: &Request) -> Result<(), AiError>; -} - -impl ValidateRequest for CapabilitySpec { - fn validate_request(&self, r: &Request) -> Result<(), AiError> { - r.validate(self, &Limits::default()) - } -} diff --git a/crates/ai-core/tests/spec_calls.rs b/crates/ai-core/tests/spec_calls.rs deleted file mode 100644 index 77ef22a096..0000000000 --- a/crates/ai-core/tests/spec_calls.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! How calls may use substitutions and what a flow must send (task u2). Each case feeds an input -//! that only the named rule refuses. - -mod spec_support; - -use serde_json::{Value, json}; -use spec_support::{direct, parse, queue, refused, set}; - -#[test] -fn only_job_id_may_appear_in_a_path_and_only_where_a_job_exists() { - refused(set(queue(), "/flow/submit/call/path", json!("/images/{prompt}")), "flow.submit.call.path", "only {job_id} may be used in a path"); - refused(set(queue(), "/flow/submit/call/path", json!("/images/{model}")), "flow.submit.call.path", "only {job_id} may be used in a path"); - refused(set(queue(), "/flow/submit/call/path", json!("/images/{job_id}")), "flow.submit.call", "{job_id} is not available"); - refused(set(direct(), "/flow/call/path", json!("/images/{job_id}")), "flow.call", "{job_id} is not available"); -} - -#[test] -fn a_placeholder_this_version_lacks_is_refused_by_name() { - refused( - set(queue(), "/flow/submit/call/body", json!({"seed": "{seed}", "p": "{prompt}"})), - "flow.submit.call.body", - "unsupported: placeholder {seed}", - ); - refused( - set(queue(), "/flow/poll/call/query", json!({"id": "{job_id}", "x": "{param.size}"})), - "flow.poll.call.query", - "unsupported: placeholder {param.size}", - ); -} - -#[test] -fn a_body_key_cannot_be_a_template() { - refused(set(queue(), "/flow/submit/call/body", json!({"{prompt}": 1, "p": "{prompt}"})), "flow.submit.call.body", "a key cannot hold a brace"); -} - -#[test] -fn the_polling_and_cancel_calls_must_name_the_job() { - refused(set(queue(), "/flow/poll/call/query", json!({"id": "fixed"})), "flow.poll.call", "never uses {job_id}"); - refused(set(queue(), "/flow/cancel/path", json!("/jobs")), "flow.cancel", "never uses {job_id}"); - assert!(parse(&set(queue(), "/flow/cancel", Value::Null)).is_ok(), "cancel is optional"); -} - -#[test] -fn the_prompt_must_be_sent_and_every_model_must_require_it() { - refused(set(queue(), "/flow/submit/call/body", json!({"n": 1})), "flow", "the prompt is never sent"); - refused(set(queue(), "/models/0/requires", json!([])), "models[0].requires", "needs every model to require a prompt"); -} - -#[test] -fn a_body_belongs_to_a_post_and_stays_small() { - refused(set(queue(), "/flow/poll/call/body", json!({"id": "{job_id}"})), "flow.poll.call.body", "only a POST has a body"); - let pad = "x".repeat(4096); - refused(set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "pad": pad})), "flow.submit.call.body", "at most 4 KiB"); - let fits = "x".repeat(4096 - r#"{"p":"{prompt}","pad":""}"#.len()); - assert!(parse(&set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "pad": fits}))).is_ok()); -} - -#[test] -fn query_values_are_few_plain_and_short() { - let q = |v: Value| set(queue(), "/flow/poll/call/query", v); - refused(q(json!({"bad name": "{job_id}"})), "flow.poll.call.query", "plain"); - refused(q(json!({"id": "x".repeat(257)})), "flow.poll.call.query", "plain"); - let nine: serde_json::Map = (0..9).map(|i| (format!("k{i}"), json!("{job_id}"))).collect(); - refused(q(Value::Object(nine)), "flow.poll.call.query", "at most 8"); - let eight: serde_json::Map = (0..8).map(|i| (format!("k{i}"), json!("{job_id}"))).collect(); - assert!(parse(&q(Value::Object(eight))).is_ok()); -} - -#[test] -fn a_literal_brace_is_written_doubled() { - let body = json!({"p": "{prompt}", "note": "{{not a slot}}"}); - assert!(parse(&set(queue(), "/flow/submit/call/body", body)).is_ok()); - refused(set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "note": "{oops"})), "flow.submit.call.body", "never closed"); -} diff --git a/crates/ai-core/tests/spec_rules.rs b/crates/ai-core/tests/spec_rules.rs index 28a24087d1..93857f9864 100644 --- a/crates/ai-core/tests/spec_rules.rs +++ b/crates/ai-core/tests/spec_rules.rs @@ -1,55 +1,10 @@ //! Rules a declarative spec must keep (task u2). Each case feeds an input that only the named rule //! refuses, and checks where the error points and what it says. -mod spec_support; +use super::spec_support; -use craft_ai_core::spec::{MAX_SPEC_BYTES, Spec}; -use serde_json::{Value, json}; -use spec_support::{direct, parse, queue, refused, set}; - -#[test] -fn both_documented_shapes_are_accepted_and_round_trip() { - for v in [queue(), direct()] { - let spec = parse(&v).unwrap(); - assert_eq!(Spec::parse(&serde_json::to_string(&spec).unwrap()).unwrap(), spec); - } -} - -#[test] -fn the_file_size_limit_holds_at_its_edge() { - let text = queue().to_string(); - let pad = MAX_SPEC_BYTES - text.len(); - assert!(Spec::parse(&format!("{text}{}", " ".repeat(pad))).is_ok()); - let e = Spec::parse(&format!("{text}{}", " ".repeat(pad + 1))).unwrap_err(); - assert!(e.why.contains("too large"), "{e}"); -} - -#[test] -fn a_feature_this_version_lacks_is_refused_by_name_never_ignored() { - refused(set(queue(), "/flow/submit", json!({"webhook": "x"})), "spec", "webhook"); - let mut v = queue(); - v["streaming"] = json!(true); - refused(v, "spec", "streaming"); - let mut v = queue(); - v["models"][0]["params"] = json!(["seed"]); - refused(v, "spec", "params"); -} - -#[test] -fn only_version_one_is_read() { - refused(set(queue(), "/spec_version", json!(2)), "spec_version", "only version 1"); -} - -#[test] -fn the_base_address_follows_the_connection_rules() { - refused(set(queue(), "/base", json!("http://api.example.com")), "base", "plain http"); - refused(set(queue(), "/base", json!("https://u:p@api.example.com")), "base", "user-info"); - refused(set(queue(), "/base", json!("https://api.example.com/v2?x=1")), "base", "no query"); - refused(set(queue(), "/base", json!("https://api.example.com/v2#top")), "base", "no query"); - refused(set(queue(), "/base", json!("ftp://api.example.com")), "base", "http"); - refused(set(queue(), "/base", json!("https://api.example.com/v2/../x")), "base", "'..'"); - assert!(parse(&set(queue(), "/base", json!("https://api.example.com"))).is_ok()); -} +use serde_json::json; +use spec_support::{parse, queue, refused, set}; #[test] fn a_path_cannot_leave_the_base() { @@ -70,98 +25,3 @@ fn a_path_cannot_leave_the_base() { refused(path(&format!("/{}", "a".repeat(256))), at, "too long"); assert!(parse(&path(&format!("/{}", "a".repeat(255)))).is_ok()); } - -#[test] -fn the_key_header_follows_the_connection_rules() { - let name = |n: &str| set(queue(), "/auth/name", json!(n)); - refused(name("authorization"), "auth", "Authorization"); - refused(name("host"), "auth", "cannot carry a key"); - refused(name("proxy-x"), "auth", "network"); - refused(name("bad name"), "auth", "letters, digits"); - refused(name(""), "auth", "1 to 64"); - assert!(parse(&set(queue(), "/auth", json!({"kind": "bearer"}))).is_ok()); - assert!(parse(&set(queue(), "/auth", json!({"kind": "none"}))).is_ok()); -} - -#[test] -fn a_model_is_declared_completely_or_not_at_all() { - let m = |field: &str, to: Value| set(queue(), &format!("/models/0/{field}"), to); - refused(m("id", json!("bad id")), "models[0].id", ""); - refused(m("capability", json!("nope")), "models[0].capability", ""); - refused(m("label", json!(" ")), "models[0].label", "label"); - refused(m("accepts", json!({})), "models[0].accepts", "at least one"); - refused(m("accepts", json!({"prompt": 0})), "models[0].accepts", "must be 1"); - refused(m("accepts", json!({"prompt": 2})), "models[0].accepts", "must be 1"); - refused(m("accepts", json!({"source": 1})), "models[0].accepts", "unsupported: input 'source'"); - refused(m("requires", json!(["source"])), "models[0].requires", "must also be accepted"); - refused(m("max_outputs", json!(0)), "models[0].max_outputs", "1 to 4"); - refused(m("max_outputs", json!(5)), "models[0].max_outputs", "1 to 4"); - refused(set(queue(), "/models", json!([])), "models", "at least one"); - let one = queue()["models"][0].clone(); - refused(set(queue(), "/models", json!([one.clone(), one.clone()])), "models[1].id", "twice"); - let many: Vec = (0..17).map(|i| set(one.clone(), "/id", json!(format!("m{i}")))).collect(); - refused(set(queue(), "/models", json!(many)), "models", "at most 16"); - let sixteen: Vec = (0..16).map(|i| set(one.clone(), "/id", json!(format!("m{i}")))).collect(); - assert!(parse(&set(queue(), "/models", json!(sixteen))).is_ok()); -} - -#[test] -fn the_status_table_maps_words_to_the_four_states() { - let states = |v: Value| set(queue(), "/flow/poll/states", v); - let at = "flow.poll.states"; - refused(states(json!({"Error": "failed"})), at, "succeeded"); - refused(states(json!({"Ready": "succeeded"})), at, "failed"); - refused(states(json!({})), at, "succeeded"); - let table = |running: usize| { - let mut t = serde_json::Map::new(); - for i in 0..running { - t.insert(format!("w{i}"), json!("running")); - } - t.insert("ok".into(), json!("succeeded")); - t.insert("bad".into(), json!("failed")); - Value::Object(t) - }; - assert!(parse(&states(table(14))).is_ok(), "16 entries are allowed"); - refused(states(table(15)), at, "at most 16"); -} - -#[test] -fn a_pointer_is_a_bounded_rfc_6901_path() { - let at = |p: &str| set(queue(), "/flow/poll/result/at", json!(p)); - refused(at("result/sample"), "flow.poll.result.at", "starts with /"); - refused(at("/a/b/c/d/e/f/g/h/i"), "flow.poll.result.at", "8 levels"); - assert!(parse(&at("/a/b/c/d/e/f/g/h")).is_ok()); - refused(set(queue(), "/flow/submit/job_id_at", json!("id")), "flow.submit.job_id_at", "starts with /"); - refused(set(queue(), "/flow/poll/status_at", json!("")), "flow.poll.status_at", "starts with /"); -} - -#[test] -fn a_result_says_what_it_is() { - let ex = |v: Value| set(queue(), "/flow/poll/result", v); - refused(ex(json!({"at": "/x", "as": "url"})), "flow.poll.result", "media_type"); - refused(ex(json!({"at": "/x", "as": "base64"})), "flow.poll.result", "media_type"); - refused(ex(json!({"at": "/x", "as": "text", "media_type": "text/plain"})), "flow.poll.result", "text"); - refused(ex(json!({"at": "/x", "as": "url", "media_type": "not a type"})), "flow.poll.result", "media_type"); - assert!(parse(&ex(json!({"at": "/x", "as": "text"}))).is_ok()); -} - -#[test] -fn limits_are_bounded() { - let l = |field: &str, to: Value| { - let mut v = queue(); - v["limits"] = json!({ field: to }); - v - }; - refused(l("max_polls", json!(0)), "limits.max_polls", "1 to 10000"); - refused(l("max_polls", json!(10001)), "limits.max_polls", "1 to 10000"); - refused(l("max_seconds", json!(0)), "limits.max_seconds", "1 to 3600"); - refused(l("max_seconds", json!(3601)), "limits.max_seconds", "1 to 3600"); - assert!(parse(&l("max_polls", json!(10000))).is_ok()); -} - -#[test] -fn the_probe_is_a_free_read() { - refused(set(queue(), "/probe/method", json!("POST")), "probe", "GET"); - refused(set(queue(), "/probe/body", json!({"a": 1})), "probe", "only a POST has a body"); - refused(set(queue(), "/probe/path", json!("/a/../b")), "probe.path", "'..'"); -} diff --git a/crates/ai-core/tests/spec_support/mod.rs b/crates/ai-core/tests/spec_support/mod.rs index 6750aba4b7..659094f1fa 100644 --- a/crates/ai-core/tests/spec_support/mod.rs +++ b/crates/ai-core/tests/spec_support/mod.rs @@ -24,19 +24,6 @@ pub fn queue() -> Value { }) } -pub fn direct() -> Value { - json!({ - "spec_version": 1, "id": "plain-images", "label": "Plain Images", - "base": "http://127.0.0.1:8080", - "models": [{"id": "m", "label": "M", "capability": "image.generate", - "accepts": {"prompt": 1}, "requires": ["prompt"]}], - "flow": {"kind": "request_response", - "call": {"method": "POST", "path": "/images", - "body": {"model": "{model}", "prompt": "{prompt}"}}, - "result": {"at": "/data/0/b64_json", "as": "base64", "media_type": "image/png"}} - }) -} - /// Replaces the value at `pointer`, or adds it when the parent object lacks that key. pub fn set(mut v: Value, pointer: &str, to: Value) -> Value { let (parent, key) = pointer.rsplit_once('/').unwrap_or(("", pointer)); diff --git a/crates/ai-core/tests/spec_template.rs b/crates/ai-core/tests/spec_template.rs index 8c7deeeded..e909e35135 100644 --- a/crates/ai-core/tests/spec_template.rs +++ b/crates/ai-core/tests/spec_template.rs @@ -1,32 +1,13 @@ //! Substitution rules for declarative specs: what a template may name, and that the structure of //! a request can never come from the user's text. -use craft_ai_core::spec::template::{Slot, Values, render_text, render_value, slots, value_slots}; +use craft_ai_core::spec::template::{Values, render_text, render_value}; use serde_json::json; fn values() -> Values<'static> { Values { prompt: Some("a red door"), model: Some("img-1"), job_id: Some("job-7") } } -#[test] -fn the_three_names_are_known_and_nothing_else() { - assert_eq!(slots("{prompt} {model} {job_id}").unwrap(), vec![Slot::Prompt, Slot::Model, Slot::JobId]); - assert_eq!(slots("no slots here").unwrap(), vec![]); - for other in ["{seed}", "{param.size}", "{Prompt}", "{}", "{ prompt }"] { - let why = slots(other).unwrap_err(); - assert!(why.contains("unsupported: placeholder"), "{other}: {why}"); - } - assert_eq!(slots("{seed}").unwrap_err(), "unsupported: placeholder {seed}"); -} - -#[test] -fn braces_are_closed_or_doubled() { - assert!(slots("a { b").unwrap_err().contains("never closed")); - assert!(slots("a } b").unwrap_err().contains("lone }")); - assert_eq!(render_text("{{literal}}", &values()).unwrap(), "{literal}"); - assert_eq!(render_text("{{{prompt}}}", &values()).unwrap(), "{a red door}"); -} - #[test] fn text_is_inserted_and_never_read_again() { let v = Values { prompt: Some("{job_id} and {{ and }"), ..values() }; @@ -43,37 +24,3 @@ fn a_prompt_cannot_add_a_field_or_change_a_key() { assert!(body.get("admin").is_none()); assert_eq!(body["n"], json!(1)); } - -#[test] -fn keys_are_literal_and_nested_values_are_rendered() { - let template = json!({"a": [{"b": "{model}"}, "{job_id}"], "c": {"d": "{prompt}"}}); - let body = render_value(&template, &values()).unwrap(); - assert_eq!(body, json!({"a": [{"b": "img-1"}, "job-7"], "c": {"d": "a red door"}})); - assert_eq!(value_slots(&template).unwrap(), vec![Slot::Model, Slot::JobId, Slot::Prompt]); - assert!(value_slots(&json!({"{prompt}": 1})).unwrap_err().contains("key")); -} - -#[test] -fn a_key_is_never_substituted_even_when_it_looks_like_a_slot() { - let body = render_value(&json!({"{prompt}": "{model}"}), &values()).unwrap(); - assert_eq!(body, json!({"{prompt}": "img-1"})); -} - -#[test] -fn a_slot_with_no_value_is_an_error_not_an_empty_string() { - let v = Values { prompt: Some("x"), ..Values::default() }; - let why = render_text("/jobs/{job_id}", &v).unwrap_err(); - assert!(why.contains("{job_id} is not available"), "{why}"); -} - -#[test] -fn repeated_slots_share_one_rendered_budget() { - let prompt = "x".repeat(64 * 1024); - let v = Values { prompt: Some(&prompt), ..values() }; - let slots = vec![json!("{prompt}"); 16]; - assert!(render_value(&json!({ "a": slots }), &v).is_ok()); - let slots = vec![json!("{prompt}{prompt}{prompt}{prompt}"); 32]; - let why = render_value(&json!({ "a": slots }), &v).unwrap_err(); - assert!(why.contains("at most"), "{why}"); - assert!(render_text(&"{prompt}".repeat(128), &v).is_err()); -} diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml index cc54d2513c..114c4ae426 100644 --- a/crates/android-res/Cargo.toml +++ b/crates/android-res/Cargo.toml @@ -13,3 +13,6 @@ workspace = true [dependencies] serde = { workspace = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs index 3525e0434c..d45b064464 100644 --- a/crates/android-res/src/axml.rs +++ b/crates/android-res/src/axml.rs @@ -631,9 +631,13 @@ mod tests { #[test] fn shared_offsets_spend_a_pool_byte_budget() { - for utf8 in [true, false] { + // Each parse keeps 64 MiB of strings: the gate runs the UTF-8 pool with the appended bytes + // (the budget and the appended bytes together), nightly all four. + let full = craft_testkit::hostile::divisor() == 1; + let (encodings, appends): (&[bool], &[bool]) = if full { (&[true, false], &[false, true]) } else { (&[true], &[true]) }; + for &utf8 in encodings { let mut data = shared_ascii_pool(utf8, 8192); - for appended in [false, true] { + for &appended in appends { if appended { // Unrelated bytes after the chunk cannot buy more retained copies. data.resize(24 << 20, 0); diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml new file mode 100644 index 0000000000..ad602e383a --- /dev/null +++ b/crates/appkit/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "craft-appkit" +description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through +# `NSNotificationCenter` with a block. +[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"] } + +# 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 +# workspace lint. +[lints.rust] +unsafe_code = "deny" +missing_docs = "warn" +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } + +[lints.clippy] +cognitive_complexity = "deny" +too_many_arguments = "deny" +wildcard_imports = "deny" +dbg_macro = "warn" +todo = "warn" diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs new file mode 100644 index 0000000000..78dd786b15 --- /dev/null +++ b/crates/appkit/src/lib.rs @@ -0,0 +1,37 @@ +//! 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. +//! +//! 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. +#![warn(missing_docs)] +#![cfg(target_os = "macos")] +#![allow(unsafe_code)] + +use std::ptr::NonNull; +use std::sync::{Arc, Once}; + +use block2::RcBlock; +use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; +use objc2_foundation::{NSNotification, NSNotificationCenter}; + +/// 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. +pub fn observe_menu_tracking(on_change: Arc) { + static OBSERVE: Once = Once::new(); + OBSERVE.call_once(|| { + // SAFETY: AppKit initializes these immutable notification-name constants before any code of the app runs. + let names = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] }; + let center = NSNotificationCenter::defaultCenter(); + for (name, tracking) in names { + let on_change = on_change.clone(); + let block = RcBlock::new(move |_: NonNull| on_change(tracking)); + // SAFETY: `name` is one of AppKit's notification names and the block takes the notification by pointer + // without reading it. The center copies the block and keeps the observer for the process's lifetime; + // nothing removes it, so the returned token is not needed. + unsafe { + center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block); + } + } + }); +} diff --git a/crates/atomic/Cargo.toml b/crates/atomic/Cargo.toml index cc31d02b18..2b0b43a475 100644 --- a/crates/atomic/Cargo.toml +++ b/crates/atomic/Cargo.toml @@ -1,4 +1,5 @@ [package] +autotests = false name = "craft-atomic" version.workspace = true edition.workspace = true @@ -10,5 +11,8 @@ description = "Crash-safe atomic file writing and replacement for the Craft suit [lints] workspace = true +# Plain fsync where F_FULLFSYNC is refused, and the replaced file's extended attributes (`fs`), with +# explicit size queries (`fgetxattr_query`). + [target.'cfg(target_vendor = "apple")'.dependencies] -rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } +rustix = { version = "1.1.6", default-features = false, features = ["std", "fs"] } diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 08b881e17b..5aa3c75cd4 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -34,6 +34,13 @@ //! Existing destinations always stage privately and retain their original Unix mode. Restoring //! an already-matching mode needs no chmod, including on fixed-mode network filesystems. //! +//! ### Attributes +//! A replaced file is the same document: its stage gets the file's extended attributes (macOS), +//! its hidden and system attributes (Windows, at creation) and its creation date (macOS, +//! Windows) before it is flushed. An extended attribute that cannot be read or copied whole, or +//! passes a bound, refuses the save and leaves the original as it was. Saving through a symbolic +//! link keeps the link and replaces the file it names, so the attributes kept are that file's. +//! //! ### Platform Characteristics //! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files //! open with sharing violations. The rename is retried with exponential backoff (`RenameRetry`). @@ -45,6 +52,7 @@ //! - **Web / WASM**: On `wasm32`, returns standard unsupported `io::Error` rather than panicking. //! - **Failure Injection**: [`atomic_write_custom`] accepts an [`AtomicFs`] implementation so //! callers and test suites can inject disk-full, lock-contention, or permission errors at each stage. +#![warn(missing_docs)] use std::fs::{File, OpenOptions}; use std::io::{self, Write}; @@ -58,6 +66,15 @@ pub trait AtomicFs { /// request mode `0600` for `Private` or `0666` for `PlatformDefault`; the OS applies its /// umask/default ACL. Other platforms keep their native creation behavior. fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result; + /// Create the stage like [`AtomicFs::create_new`], carrying over the attributes of the file it + /// replaces that can only be given at creation (Windows: hidden and system). `keep` is the + /// `metadata` of the regular file being replaced: a save through a symbolic link keeps the + /// link and replaces the file it names, so `keep` describes that file, never the link. `None` + /// for a new file. The default ignores `keep` and calls `create_new`. + fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result { + let _ = keep; + self.create_new(path, permissions) + } /// Flush a written file to durable storage. fn sync(&self, file: &File) -> io::Result<()>; /// Rename `from` over `to`, replacing it atomically. @@ -98,6 +115,21 @@ impl AtomicFs for RealFs { options.open(path) } + fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result { + // Given as the file is created, so a hidden file's stage is never visible: Windows has no + // safe call that sets them on an open file afterwards. + #[cfg(windows)] + if let Some(keep) = keep { + use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; + let mut options = OpenOptions::new(); + options.write(true).create_new(true).attributes(keep.file_attributes() & KEPT_ATTRIBUTES); + return options.open(path); + } + #[cfg(not(windows))] + let _ = keep; + self.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { sync_file(file) } @@ -314,12 +346,16 @@ fn replace_with_options( check_writable(&target).map_err(|e| read_only_error(e, path))?; } - let tmp = stage(fs, &dir, &name, path, existing.as_ref(), new_permissions, fill)?; + let tmp = stage(fs, &dir, &name, path, existing.as_ref().map(|m| (target.as_path(), m)), new_permissions, fill)?; if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { let _ = fs.remove(&tmp); return Err(rename_error(e, path, existed)); } + #[cfg(windows)] + if let Some(replaced) = existing.as_ref().filter(|m| m.is_file()) { + restore_kept_attributes(&target, replaced); + } // The new bytes are in place; a failed directory fsync can't be undone and must not report // the save as failed, so it is best effort. @@ -368,31 +404,35 @@ fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32 } /// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of -/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when +/// the file it replaces (`replaced`: its resolved path and `metadata`, Unix), keep that file's +/// other attributes ([`keep_attributes`]) and flush it. Permission restoration is skipped when /// the mode already matches after `fill`; the group bits are dropped when the file cannot be put /// in the replaced file's group, so they never open the file to a group that was not granted -/// them. A leftover file with the same name is skipped. When any step fails, the temporary file -/// is removed. +/// them. A name something already has (a leftover file, a link, a folder) is skipped, never +/// opened, so nothing planted there receives or redirects the write. When any step fails, the +/// temporary file is removed. fn stage( fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, - replaced: Option<&std::fs::Metadata>, + replaced: Option<(&Path, &std::fs::Metadata)>, new_permissions: NewFilePermissions, fill: impl FnOnce(&mut File) -> io::Result<()>, ) -> io::Result { let existed = replaced.is_some(); // Windows files carry only a read-only flag, and a read-only file can't be replaced. - let perms = replaced.filter(|_| cfg!(unix)).map(|m| m.permissions()); + let perms = replaced.filter(|_| cfg!(unix)).map(|(_, m)| m.permissions()); + // A folder or other non-file at the target has no attributes a stage could carry. + let keep = replaced.map(|(_, m)| m).filter(|m| m.is_file()); // New documents inherit the directory's policy directly: no probe or chmod is needed. // Existing destinations still stage privately, including when their final mode is shared. let creation = if existed { NewFilePermissions::Private } else { new_permissions }; for _ in 0..8 { let tmp = dir.join(temp_name(name)); - let mut file = match fs.create_new(&tmp, creation) { + let mut file = match fs.create_new_keeping(&tmp, creation, keep) { Ok(f) => f, - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) if name_taken(&e, &tmp) => continue, Err(e) => return Err(write_error(e, path, dir, existed)), }; let written = fill(&mut file) @@ -412,7 +452,7 @@ fn stage( } // The group bits belong to the replaced file's group, which a new // inode need not be in (setgid directory, another primary group). - if let Some(replaced) = replaced { + if let Some((_, replaced)) = replaced { let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?); let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced); let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?; @@ -423,7 +463,12 @@ fn stage( }) .map_err(|e| permissions_error(e, path)) }) + .and_then(|()| keep_attributes(&file, replaced.filter(|(_, m)| m.is_file())).map_err(|e| attributes_error(e, path))) .and_then(|()| fs.sync(&file).map_err(|e| write_error(e, path, dir, existed))); + #[allow( + clippy::drop_non_drop, + reason = "File has no drop glue on wasm32-unknown-unknown; on other targets the drop closes it before the next step" + )] drop(file); if written.is_err() { let _ = fs.remove(&tmp); @@ -433,6 +478,168 @@ fn stage( Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display()))) } +/// Whether creating the stage failed because something already has its name: a file, a link +/// (even a dangling one) or a folder. Windows reports a folder there as access denied. +fn name_taken(e: &io::Error, tmp: &Path) -> bool { + match e.kind() { + io::ErrorKind::AlreadyExists => true, + io::ErrorKind::PermissionDenied => cfg!(windows) && std::fs::symlink_metadata(tmp).is_ok(), + _ => false, + } +} + +/// The Windows attributes a replaced file passes on to its stage: hidden and system, the two that +/// say who should see the file. A read-only file is never replaced, the archive bit is the +/// system's to set on a changed file, and the others describe how the volume stores it. +#[cfg(windows)] +const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4; + +/// A server that hides dot-named files (Samba, NAS) marks the stage hidden and keeps the mark +/// through the rename: the saved file then gets the replaced file's attributes back. Only when the +/// kept bits differ, since restoring the whole attribute word on a local disk would clear the +/// archive bit backup tools read. Best effort: the new bytes are already in place. +#[cfg(windows)] +fn restore_kept_attributes(target: &Path, replaced: &std::fs::Metadata) { + use std::os::windows::fs::MetadataExt; + let saved = std::fs::symlink_metadata(target).map(|m| m.file_attributes() & KEPT_ATTRIBUTES); + if saved.is_ok_and(|bits| bits != replaced.file_attributes() & KEPT_ATTRIBUTES) { + let _ = std::fs::set_permissions(target, replaced.permissions()); + } +} + +/// Give the stage what the replaced regular file (`replaced`: its resolved path and `metadata`) +/// carries besides its bytes and mode, before the stage is flushed: on macOS its extended +/// attributes (`copy_xattrs`; an attribute that cannot be kept refuses the save), on macOS and +/// Windows its creation date (best effort: a volume that stores none keeps the stage's own). A +/// saved document is the same document. A new file has nothing to keep. +fn keep_attributes(stage: &File, replaced: Option<(&Path, &std::fs::Metadata)>) -> io::Result<()> { + let Some((target, meta)) = replaced else { return Ok(()) }; + #[cfg(target_os = "macos")] + copy_xattrs(target, stage)?; + #[cfg(not(target_os = "macos"))] + let _ = target; + #[cfg(any(target_os = "macos", windows))] + if let Ok(created) = meta.created() { + #[cfg(target_os = "macos")] + use std::os::macos::fs::FileTimesExt; + #[cfg(windows)] + use std::os::windows::fs::FileTimesExt; + let _ = stage.set_times(std::fs::FileTimes::new().set_created(created)); + } + #[cfg(not(any(target_os = "macos", windows)))] + let _ = (stage, meta); + Ok(()) +} + +/// The longest list of extended attribute names read from a replaced file. +#[cfg(target_os = "macos")] +const MAX_XATTR_NAMES_BYTES: usize = 64 * 1024; +/// The most extended attributes copied from a replaced file. +#[cfg(target_os = "macos")] +const MAX_XATTRS: usize = 1024; +/// The largest extended attribute value copied (a resource fork can be larger than ordinary ones). +#[cfg(target_os = "macos")] +const MAX_XATTR_VALUE_BYTES: usize = 16 * 1024 * 1024; +/// The most extended attribute bytes copied from one file in all. +#[cfg(target_os = "macos")] +const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; + +/// Copy the extended attributes of the regular file at `target` (Finder tags, the "Open with" +/// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the +/// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound, +/// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without +/// extended attributes (`ENOTSUP`) is skipped. So is a file whose data the user may not read when +/// its attribute names can't be listed either, as with mode 0200: its attributes are dropped, as +/// before attributes were kept, since the user can't read them (or its bytes) at all. One whose +/// data is denied but whose names can be listed (an ACL that denies reading) refuses the save. +/// `com.apple.provenance` belongs to macOS, which gives the new file its own. Compression +/// bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). +#[cfg(target_os = "macos")] +fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { + use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open}; + use rustix::io::Errno; + + // Never read through a link: the target is already resolved, and a link swapped in since + // names another file. NONBLOCK keeps a FIFO put at the name from hanging the open. + let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) { + Ok(fd) => File::from(fd), + Err(Errno::NOENT | Errno::LOOP) => return Ok(()), + Err(Errno::ACCESS) => return unreadable_has_no_attributes(target), + Err(e) => return Err(e.into()), + }; + if !source.metadata()?.is_file() { + return Ok(()); + } + let names_too_long = || io::Error::other("the extended attribute names exceed 64 KiB"); + let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES]; + let len = match flistxattr(&source, names.as_mut_slice()) { + Ok(len) => len, + Err(Errno::NOTSUP) => return Ok(()), + Err(Errno::RANGE) => return Err(names_too_long()), + Err(e) => return Err(e.into()), + }; + let names = names.get(..len).ok_or_else(names_too_long)?; + let mut total = 0usize; + for (index, name) in names.split(|b| *b == 0).filter(|name| !name.is_empty()).enumerate() { + if index >= MAX_XATTRS { + return Err(io::Error::other("more than 1024 extended attributes")); + } + if name == b"com.apple.provenance" { + continue; + } + let name = std::ffi::CString::new(name).map_err(|_| io::Error::other("an extended attribute name is not valid"))?; + // An empty read buffer reads zero bytes in rustix, not the size: query it explicitly. + let size = fgetxattr_query(&source, &name)?; + if size > MAX_XATTR_VALUE_BYTES || size > MAX_XATTR_TOTAL_BYTES.saturating_sub(total) { + return Err(io::Error::other("the extended attributes exceed 16 MiB per value or 64 MiB in total")); + } + let value = read_xattr_value(size, |buffer| Ok(fgetxattr(&source, &name, buffer)?), || Ok(fgetxattr_query(&source, &name)?))?; + fsetxattr(stage, &name, &value, XattrFlags::empty())?; + total = total.saturating_add(value.len()); + } + Ok(()) +} + +/// For a target whose data can't be opened for reading: `Ok` when the user can list no extended +/// attribute names on it (none, only `com.apple.provenance`, none supported, or listing is denied too, +/// as for mode 0200, whose attributes are then dropped); otherwise refuse the save, as the attributes +/// can't be copied without opening the file. The names are read without following a link, by path. +#[cfg(target_os = "macos")] +fn unreadable_has_no_attributes(target: &Path) -> io::Result<()> { + use rustix::fs::llistxattr; + use rustix::io::Errno; + let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES]; + match llistxattr(target, names.as_mut_slice()) { + Ok(0) | Err(Errno::NOTSUP | Errno::ACCESS | Errno::NOENT) => Ok(()), + Ok(len) if names.get(..len).is_some_and(|names| names.split(|b| *b == 0).all(|name| name.is_empty() || name == b"com.apple.provenance")) => { + Ok(()) + } + Ok(_) | Err(Errno::RANGE) => { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "the file can't be read, so its extended attributes can't be copied")) + } + Err(e) => Err(e.into()), + } +} + +/// Read one attribute value of `size` bytes (already within the bounds) with `read`, then ask +/// its size again with `query_size`. A read that does not fill `size`, or a size that changed, +/// is refused: a growing resource fork returns the prefix that fits instead of an error. +#[cfg(target_os = "macos")] +fn read_xattr_value( + size: usize, + read: impl FnOnce(&mut [u8]) -> io::Result, + query_size: impl FnOnce() -> io::Result, +) -> io::Result> { + let mut value = vec![0u8; size.max(1)]; + let len = read(value.as_mut_slice())?; + let after = query_size()?; + if len != size || after != size { + return Err(io::Error::other("an extended attribute changed size while saving")); + } + value.truncate(len); + Ok(value) +} + /// Exclusively creates and writes `path` with normal OS permissions, without replacing existing files. /// Use [`WriteOptions`] for private data. pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { @@ -523,6 +730,10 @@ fn copy_new(fs: &dyn AtomicFs, tmp: &Path, target: &Path, permissions: NewFilePe } fs.sync(&to) }); + #[allow( + clippy::drop_non_drop, + reason = "File has no drop glue on wasm32-unknown-unknown; on other targets the drop closes it before the next step" + )] drop(to); if copied.is_err() { let _ = fs.remove(target); @@ -588,11 +799,18 @@ fn resolve_links(path: &Path) -> io::Result { Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display()))) } -/// Generates a unique, hidden temporary file name beside `file`. +/// The most bytes of the target's name a temporary name keeps: with the leading `.`, the pid, the +/// counter and `.craft_tmp` the name stays within the 255-byte (Linux, macOS) and 255-unit +/// (Windows) limits however long the target's name is. +const TEMP_STEM_BYTES: usize = 128; + +/// Generates a unique, hidden temporary file name beside `file`: `.{file}.{pid}-{n}.craft_tmp`, +/// with `file` cut to its first 128 bytes between characters. pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let stem: String = file.chars().take(64).collect(); + let end = file.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|&end| end <= TEMP_STEM_BYTES).last().unwrap_or(0); + let stem = file.get(..end).unwrap_or_default(); #[cfg(not(target_arch = "wasm32"))] let pid = std::process::id(); #[cfg(target_arch = "wasm32")] @@ -624,6 +842,11 @@ fn permissions_error(e: io::Error, path: &Path) -> io::Error { io::Error::new(e.kind(), msg) } +fn attributes_error(e: io::Error, path: &Path) -> io::Error { + let msg = format!("cannot save {}: the original's extended attributes cannot be kept ({e}){}", path.display(), unchanged(true)); + io::Error::new(e.kind(), msg) +} + fn read_only_error(e: io::Error, path: &Path) -> io::Error { let kept = unchanged(true); let msg = match e.kind() { @@ -652,698 +875,11 @@ fn is_cross_device(e: &io::Error) -> bool { } #[cfg(test)] -mod tests { - use super::*; - use std::cell::Cell; +mod tests; - struct TempDir(PathBuf); - impl TempDir { - fn new(tag: &str) -> Self { - static N: AtomicU64 = AtomicU64::new(0); - #[cfg(not(target_arch = "wasm32"))] - let pid = std::process::id(); - #[cfg(target_arch = "wasm32")] - let pid = 0; - let d = std::env::temp_dir().join(format!("craft-atomic-{tag}-{pid}-{}", N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).ok(); - Self(d) - } - } - impl Drop for TempDir { - fn drop(&mut self) { - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); - } - let _ = std::fs::remove_dir_all(&self.0); - } - } +#[cfg(test)] +extern crate self as craft_atomic; - fn assert_no_temp(dir: &Path) { - let leftovers: Vec<_> = std::fs::read_dir(dir) - .ok() - .map(|entries| entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".craft_tmp")).collect()) - .unwrap_or_default(); - assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}"); - } - - const ORIGINAL: &[u8] = b"the user's precious original document"; - - #[derive(Default)] - struct Faulty { - events: std::cell::RefCell>, - #[cfg(unix)] - created_modes: std::cell::RefCell>, - #[cfg(unix)] - permission_lengths: std::cell::RefCell>, - fail_sync: bool, - /// Syncs fail once this many have succeeded. - syncs_before_failure: Option, - syncs: Cell, - fail_rename: Option, - locked_renames: Cell, - renames: Cell, - no_hard_links: bool, - fail_permissions: bool, - permission_error: Option, - /// Simulate a network filesystem exposing the same fixed mode on every new file. - #[cfg(unix)] - fixed_mode: Option, - fail_sync_dir: bool, - fail_normal_create: bool, - /// Simulate a filesystem that refuses the stage's group change. - #[cfg(unix)] - fail_set_group: bool, - normal_collisions: Cell, - /// Another process creates the target just before the hard link. - created_meanwhile: Option<&'static [u8]>, - } - - impl AtomicFs for Faulty { - /// Create a real stage with injected failures or a simulated fixed network mode, - /// recording the creation policy and the Unix mode exposed by the filesystem. - fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { - let normal = permissions == NewFilePermissions::PlatformDefault; - self.events.borrow_mut().push(if normal { "create_new_normal" } else { "create_new" }); - if normal && self.fail_normal_create { - return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: normal creation failed")); - } - if normal && self.normal_collisions.get() > 0 { - self.normal_collisions.set(self.normal_collisions.get() - 1); - return Err(io::Error::from(io::ErrorKind::AlreadyExists)); - } - let file = RealFs.create_new(path, permissions)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - if let Some(mode) = self.fixed_mode { - file.set_permissions(std::fs::Permissions::from_mode(mode))?; - } - self.created_modes.borrow_mut().push(file.metadata()?.permissions().mode() & 0o777); - } - Ok(file) - } - fn sync(&self, file: &File) -> io::Result<()> { - self.events.borrow_mut().push("sync_file"); - let done = self.syncs.replace(self.syncs.get() + 1); - if self.fail_sync || self.syncs_before_failure.is_some_and(|n| done >= n) { - return Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")); - } - RealFs.sync(file) - } - fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { - self.events.borrow_mut().push("rename"); - self.renames.set(self.renames.get() + 1); - if let Some(kind) = self.fail_rename { - return Err(io::Error::new(kind, "injected rename failure")); - } - if self.locked_renames.get() > 0 { - self.locked_renames.set(self.locked_renames.get() - 1); - return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: sharing violation")); - } - RealFs.rename(from, to) - } - fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { - self.events.borrow_mut().push("hard_link"); - if let Some(bytes) = self.created_meanwhile { - std::fs::write(to, bytes)?; - } - if self.no_hard_links { - return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: hard links not supported")); - } - RealFs.hard_link(from, to) - } - fn remove(&self, path: &Path) -> io::Result<()> { - self.events.borrow_mut().push("remove"); - RealFs.remove(path) - } - fn sync_dir(&self, dir: &Path) -> io::Result<()> { - self.events.borrow_mut().push("sync_dir"); - if self.fail_sync_dir { - return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: directory sync failed")); - } - RealFs.sync_dir(dir) - } - /// Record permission restoration and payload length, then inject a configured error - /// or delegate the mode change to the real filesystem. - #[cfg(unix)] - fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { - self.events.borrow_mut().push("set_group"); - if self.fail_set_group { - return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: set_group failed")); - } - RealFs.set_group(file, gid) - } - - fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { - self.events.borrow_mut().push("set_permissions"); - #[cfg(unix)] - self.permission_lengths.borrow_mut().push(file.metadata()?.len()); - if let Some(kind) = self.permission_error { - return Err(io::Error::new(kind, "injected permission failure")); - } - if self.fail_permissions { - return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: operation not permitted")); - } - RealFs.set_permissions(file, perms) - } - } - - const NO_RETRY: RenameRetry = RenameRetry { attempts: 0, first_delay_ms: 0 }; - - #[test] - fn replaces_and_creates() { - let d = TempDir::new("ok"); - let p = d.0.join("doc.craft"); - atomic_write(&p, b"first").ok(); - assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); - atomic_write(&p, b"second, longer").ok(); - assert_eq!(std::fs::read(&p).ok(), Some(b"second, longer".to_vec())); - assert_no_temp(&d.0); - } - - #[test] - fn a_missing_folder_is_an_error_naming_it() { - let d = TempDir::new("parent"); - let folder = d.0.join("a"); - let p = folder.join("b/out.png"); - for r in [atomic_write(&p, b"x"), write_new(&p, b"x")] { - let msg = r.err().map(|e| e.to_string()).unwrap_or_default(); - assert!(msg.contains(&folder.join("b").display().to_string()), "{msg}"); - } - assert!(!folder.exists(), "no folder is created"); - } - - #[test] - fn failed_flush_keeps_original() { - let d = TempDir::new("write"); - let p = d.0.join("doc.craft"); - std::fs::write(&p, ORIGINAL).ok(); - let fs = Faulty { fail_sync: true, ..Default::default() }; - let e = atomic_write_custom(&fs, NO_RETRY, &p, &[7u8; 4096]); - assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::StorageFull)); - assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); - assert_eq!(fs.renames.get(), 0); - assert_no_temp(&d.0); - } - - #[test] - fn streaming_writes_go_through_the_injected_fs() { - let d = TempDir::new("stream"); - let p = d.0.join("doc.craft"); - std::fs::write(&p, ORIGINAL).ok(); - let chunks = |f: &mut File| { - f.write_all(b"chunk1 ")?; - f.write_all(b"chunk2") - }; - let fs = Faulty { fail_sync: true, ..Default::default() }; - assert!(replace(&fs, NO_RETRY, &p, chunks).is_err()); - let fs = Faulty { fail_rename: Some(io::ErrorKind::Other), ..Default::default() }; - assert!(replace(&fs, NO_RETRY, &p, chunks).is_err()); - assert_eq!(fs.renames.get(), 1); - assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); - assert_no_temp(&d.0); - let fs = Faulty::default(); - assert!(replace(&fs, NO_RETRY, &p, chunks).is_ok()); - assert_eq!(std::fs::read(&p).ok(), Some(b"chunk1 chunk2".to_vec())); - } - - #[test] - fn rename_failure_keeps_original() { - let d = TempDir::new("rename"); - let p = d.0.join("doc.craft"); - std::fs::write(&p, ORIGINAL).ok(); - let fs = Faulty { fail_rename: Some(io::ErrorKind::Other), ..Default::default() }; - assert!(atomic_write_custom(&fs, NO_RETRY, &p, b"new").is_err()); - assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); - assert_no_temp(&d.0); - } - - #[test] - fn locked_target_rename_is_retried() { - let d = TempDir::new("locked"); - let p = d.0.join("doc.craft"); - std::fs::write(&p, ORIGINAL).ok(); - let fs = Faulty { locked_renames: Cell::new(2), ..Default::default() }; - atomic_write_custom(&fs, RenameRetry { attempts: 3, first_delay_ms: 1 }, &p, b"new").ok(); - assert_eq!(std::fs::read(&p).ok(), Some(b"new".to_vec())); - assert_eq!(fs.renames.get(), 3); - assert_no_temp(&d.0); - } - - #[test] - fn options_inject_policy_failures_and_retry_budget() -> io::Result<()> { - let d = TempDir::new("options-injection"); - for policy in [NewFilePermissions::Private, NewFilePermissions::PlatformDefault] { - let options = WriteOptions::default().with_new_file_permissions(policy); - for streaming in [false, true] { - let path = d.0.join(format!("{policy:?}-{streaming}")); - let fs = Faulty { locked_renames: Cell::new(1), ..Default::default() }; - let retry = RenameRetry { attempts: 1, first_delay_ms: 0 }; - if streaming { - options.atomic_write_with_custom(&fs, retry, &path, |f| f.write_all(b"payload"))?; - } else { - options.atomic_write_custom(&fs, retry, &path, b"payload")?; - } - assert_eq!(fs.renames.get(), 2); - assert_eq!(std::fs::read(&path)?, b"payload"); - let event = if policy == NewFilePermissions::Private { "create_new" } else { "create_new_normal" }; - assert_eq!(fs.events.borrow()[0], event); - std::fs::remove_file(&path)?; - let fs = Faulty { fail_sync: true, ..Default::default() }; - let result = if streaming { - options.write_new_with_custom(&fs, &path, |f| f.write_all(b"payload")) - } else { - options.write_new_custom(&fs, &path, b"payload") - }; - assert_eq!(result.err().map(|e| e.kind()), Some(io::ErrorKind::StorageFull)); - assert_eq!(fs.events.borrow()[0], event); - assert!(!path.exists()); - assert_no_temp(&d.0); - } - } - Ok(()) - } - - #[test] - fn write_new_never_overwrites_existing() { - let d = TempDir::new("new"); - let p = d.0.join("file.craft"); - write_new(&p, b"first").ok(); - assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); - let res = write_new(&p, b"second"); - assert!(res.is_err()); - assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); - assert_no_temp(&d.0); - } - - #[test] - fn write_new_copies_where_hard_links_fail_and_never_replaces() { - let d = TempDir::new("new-copy"); - let p = d.0.join("export.png"); - let fs = Faulty { no_hard_links: true, ..Default::default() }; - assert!(create(&fs, &p, |f| f.write_all(b"copied")).is_ok()); - assert_eq!(std::fs::read(&p).ok(), Some(b"copied".to_vec())); - assert_no_temp(&d.0); - - // A file that appears after the existence check is kept, whether the copy or the hard - // link finds it. - for no_hard_links in [true, false] { - let p = d.0.join(format!("raced-{no_hard_links}.png")); - let fs = Faulty { no_hard_links, created_meanwhile: Some(ORIGINAL), ..Default::default() }; - let e = create(&fs, &p, |f| f.write_all(b"mine")); - assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists)); - assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); - assert_eq!(fs.renames.get(), 0); - } - assert_no_temp(&d.0); - - // A failed new file has no original to speak of. - let p = d.0.join("full.png"); - let fs = Faulty { fail_sync: true, ..Default::default() }; - let msg = create(&fs, &p, |f| f.write_all(b"x")).err().map(|e| e.to_string()).unwrap_or_default(); - assert!(msg.contains("disk is full") && !msg.contains("original"), "{msg}"); - assert!(!p.exists()); - assert_no_temp(&d.0); - } - - #[test] - fn a_failed_copy_leaves_no_partial_file() { - let d = TempDir::new("new-copy-fails"); - let p = d.0.join("export.png"); - // The temporary file flushes; the copy made in its place does not. - let fs = Faulty { no_hard_links: true, syncs_before_failure: Some(1), ..Default::default() }; - let e = write_new_custom(&fs, &p, b"copied"); - assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::StorageFull)); - assert_eq!(fs.syncs.get(), 2); - assert!(!p.exists()); - assert_no_temp(&d.0); - } - - #[cfg(unix)] - #[test] - fn exclusive_copy_starts_private_and_keeps_callback_mode() -> io::Result<()> { - use std::fs::Permissions; - use std::os::unix::fs::PermissionsExt; - - let d = TempDir::new("private-copy"); - for mode in [0o600, 0o640] { - let p = d.0.join(format!("export-{mode:o}.craft")); - let fs = Faulty { no_hard_links: true, ..Default::default() }; - create_with_options(&fs, &p, NewFilePermissions::Private, |f| { - f.write_all(b"private export")?; - f.set_permissions(Permissions::from_mode(mode)) - })?; - // Check both the staging file and the exclusive-copy destination at creation. - assert_eq!(*fs.created_modes.borrow(), [0o600, 0o600]); - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); - assert_eq!(std::fs::read(&p)?, b"private export"); - } - assert_no_temp(&d.0); - Ok(()) - } - - /// Matching fixed modes permit byte and streaming replacements under both creation - /// policies without calling a permission operation that the mount rejects. - #[cfg(unix)] - #[test] - fn unchanged_replacement_modes_need_no_chmod() -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - let d = TempDir::new("fixed-replacement-mode"); - // GVfs SMB reports 0700 regardless of the requested creation mode; also cover a - // private stage whose normal 0600 mode already matches the original. - for mode in [0o600, 0o700] { - for policy in [NewFilePermissions::Private, NewFilePermissions::PlatformDefault] { - for streaming in [false, true] { - let p = d.0.join(format!("{mode:o}-{policy:?}-{streaming}")); - std::fs::write(&p, ORIGINAL)?; - std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode))?; - let fs = Faulty { fixed_mode: Some(mode), permission_error: Some(io::ErrorKind::Unsupported), ..Default::default() }; - let options = WriteOptions::default().with_new_file_permissions(policy); - if streaming { - options.atomic_write_with_custom(&fs, NO_RETRY, &p, |f| f.write_all(b"replacement"))?; - } else { - options.atomic_write_custom(&fs, NO_RETRY, &p, b"replacement")?; - } - assert_eq!(std::fs::read(&p)?, b"replacement"); - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o7777, mode); - assert!(!fs.events.borrow().contains(&"set_permissions")); - assert_eq!(fs.renames.get(), 1); - assert_no_temp(&d.0); - } - } - } - Ok(()) - } - - /// A required mode change that fails must preserve the original bytes and mode, - /// report the error, and remove the stage without publishing it. - #[cfg(unix)] - #[test] - fn failing_to_keep_permissions_fails_the_save() -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - let d = TempDir::new("perms"); - for kind in [io::ErrorKind::Unsupported, io::ErrorKind::PermissionDenied, io::ErrorKind::Other] { - let p = d.0.join(format!("{kind:?}.craft")); - std::fs::write(&p, ORIGINAL)?; - std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o640))?; - let fs = Faulty { permission_error: Some(kind), ..Default::default() }; - let error = - atomic_write_custom(&fs, NO_RETRY, &p, b"new").err().ok_or_else(|| io::Error::other("a required mode change must succeed"))?; - assert_eq!(error.kind(), kind); - assert!(error.to_string().contains("permissions"), "{error}"); - assert_eq!(std::fs::read(&p)?, ORIGINAL); - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o7777, 0o640); - assert_eq!(fs.renames.get(), 0); - assert_no_temp(&d.0); - } - Ok(()) - } - - /// A streaming callback that changes permissions or setuid/setgid/sticky bits must not - /// bypass restoration of the original mode, even when the modes matched at creation. - #[cfg(unix)] - #[test] - fn replacement_checks_mode_after_streaming_callback() -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - let d = TempDir::new("callback-mode-change"); - for callback_mode in [0o640, 0o1600, 0o2600, 0o4600] { - let p = d.0.join(format!("doc-{callback_mode:o}.craft")); - std::fs::write(&p, ORIGINAL)?; - std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600))?; - let fs = Faulty::default(); - WriteOptions::default().atomic_write_with_custom(&fs, NO_RETRY, &p, |f| { - f.write_all(b"replacement")?; - f.set_permissions(std::fs::Permissions::from_mode(callback_mode))?; - assert_eq!(f.metadata()?.permissions().mode() & 0o7777, callback_mode); - Ok(()) - })?; - assert_eq!(std::fs::read(&p)?, b"replacement"); - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o7777, 0o600); - assert!(fs.events.borrow().contains(&"set_permissions")); - assert_no_temp(&d.0); - } - Ok(()) - } - - #[cfg(unix)] - #[test] - fn normal_creation_needs_no_chmod_even_when_hard_links_fail() -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - use std::process::Command; - if std::env::var_os("CRAFT_ATOMIC_COPY_CHILD").is_none() { - // Test both publication paths under real umasks without changing the test runner's - // process-global mask. In particular, 002 must produce a shared 0664 final file. - for mask in ["000", "002", "022", "027", "077"] { - let output = Command::new("sh") - .args([ - "-c", - "umask \"$1\"; exec \"$2\" --exact tests::normal_creation_needs_no_chmod_even_when_hard_links_fail --nocapture", - "copy-permissions", - mask, - ]) - .arg(std::env::current_exe()?) - .env("CRAFT_ATOMIC_COPY_CHILD", "1") - .output()?; - assert!(output.status.success(), "umask {mask}: {}", String::from_utf8_lossy(&output.stdout)); - assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); - } - return Ok(()); - } - let d = TempDir::new("normal-copy"); - let reference = d.0.join("reference"); - std::fs::write(&reference, b"normal creation")?; - let expected = std::fs::metadata(reference)?.permissions().mode() & 0o777; - for no_hard_links in [false, true] { - let p = d.0.join(format!("export-{no_hard_links}")); - let fs = Faulty { no_hard_links, normal_collisions: Cell::new(2), fail_permissions: true, ..Default::default() }; - create_with_options(&fs, &p, NewFilePermissions::PlatformDefault, |f| { - assert_eq!(f.metadata()?.permissions().mode() & 0o777, expected); - f.write_all(b"document payload") - })?; - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, expected); - assert_eq!(std::fs::read(&p)?, b"document payload"); - assert!(fs.created_modes.borrow().iter().all(|m| *m == expected), "stage and copy match ordinary creation"); - assert!(!fs.events.borrow().contains(&"set_permissions")); - } - let p = d.0.join("new-document"); - let fs = Faulty { fail_permissions: true, ..Default::default() }; - atomic_write_custom(&fs, NO_RETRY, &p, b"document")?; - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, expected); - assert!(!fs.events.borrow().contains(&"set_permissions")); - assert_no_temp(&d.0); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn group_bits_are_dropped_when_the_stage_cannot_join_the_replaced_group() -> io::Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - let d = TempDir::new("group-fallback"); - let file = File::create(d.0.join("stage"))?; - let gid = file.metadata()?.gid(); - let elsewhere = gid.wrapping_add(1); - - let fs = Faulty { fail_set_group: true, ..Default::default() }; - let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o640))?.mode(); - assert_eq!(mode & 0o777, 0o600, "group bits are dropped when the group cannot be joined"); - assert!(fs.events.borrow().contains(&"set_group")); - - // No group bits: the group change is never attempted. - let fs = Faulty { fail_set_group: true, ..Default::default() }; - let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o600))?.mode(); - assert_eq!(mode & 0o777, 0o600); - assert!(!fs.events.borrow().contains(&"set_group")); - - // A stage already in the replaced file's group keeps its bits untouched. - let fs = Faulty { fail_set_group: true, ..Default::default() }; - let mode = adopt_group(&fs, &file, gid, gid, std::fs::Permissions::from_mode(0o640))?.mode(); - assert_eq!(mode & 0o777, 0o640); - assert!(!fs.events.borrow().contains(&"set_group")); - - assert_no_temp(&d.0); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn normal_policy_preserves_existing_modes_with_private_staging() -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - let d = TempDir::new("normal-existing"); - for mode in [0o600, 0o640, 0o664] { - let p = d.0.join(format!("existing-{mode:o}")); - std::fs::write(&p, ORIGINAL)?; - std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode))?; - let fs = Faulty { fail_normal_create: true, ..Default::default() }; - replace_with_options(&fs, NO_RETRY, &p, NewFilePermissions::PlatformDefault, |f| f.write_all(b"replacement"))?; - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); - assert_eq!( - std::os::unix::fs::MetadataExt::gid(&std::fs::metadata(&p)?), - std::os::unix::fs::MetadataExt::gid(&d.0.metadata()?), - "kept in the directory's group" - ); - assert!(!fs.events.borrow().contains(&"create_new_normal")); - assert_eq!(*fs.created_modes.borrow(), [0o600]); - } - assert_no_temp(&d.0); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn normal_permission_failures_abort_before_publication() -> io::Result<()> { - let d = TempDir::new("normal-failures"); - for exclusive in [false, true] { - for (tag, fs, kind, callback_runs) in [ - ("create", Faulty { fail_normal_create: true, ..Default::default() }, io::ErrorKind::PermissionDenied, false), - ("collisions", Faulty { normal_collisions: Cell::new(8), ..Default::default() }, io::ErrorKind::AlreadyExists, false), - ("sync", Faulty { fail_sync: true, ..Default::default() }, io::ErrorKind::StorageFull, true), - ] { - let p = d.0.join(format!("{tag}-{exclusive}")); - let called = Cell::new(false); - let fill = |f: &mut File| { - called.set(true); - f.write_all(b"payload") - }; - let result = if exclusive { - create_with_options(&fs, &p, NewFilePermissions::PlatformDefault, fill) - } else { - replace_with_options(&fs, NO_RETRY, &p, NewFilePermissions::PlatformDefault, fill) - }; - assert_eq!(result.map_err(|e| e.kind()), Err(kind), "{tag}"); - assert_eq!(called.get(), callback_runs, "{tag}"); - assert!(!p.exists(), "{tag}"); - assert_no_temp(&d.0); - } - } - Ok(()) - } - - #[cfg(unix)] - #[test] - fn normal_copy_preserves_callback_modes_and_refuses_permission_failures() -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - let d = TempDir::new("normal-callback-copy"); - for mode in [0o600, 0o640, 0o660] { - for no_hard_links in [false, true] { - let p = d.0.join(format!("{mode:o}-{no_hard_links}")); - let fs = Faulty { no_hard_links, ..Default::default() }; - create(&fs, &p, |f| { - f.set_permissions(std::fs::Permissions::from_mode(mode))?; - f.write_all(b"callback payload") - })?; - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); - assert_eq!(std::fs::read(&p)?, b"callback payload"); - assert!(fs.permission_lengths.borrow().iter().all(|len| *len == 0), "adjust normal copies before exposing any payload"); - } - } - let p = d.0.join("permission-failure"); - let fs = Faulty { no_hard_links: true, fail_permissions: true, ..Default::default() }; - let result = create(&fs, &p, |f| { - // Toggle a bit from ordinary creation so the fallback really needs a mode change, - // independently of the test runner's umask. - let mode = f.metadata()?.permissions().mode() ^ 0o040; - f.set_permissions(std::fs::Permissions::from_mode(mode))?; - f.write_all(b"must not survive") - }); - assert_eq!(result.map_err(|e| e.kind()), Err(io::ErrorKind::PermissionDenied)); - assert_eq!(*fs.permission_lengths.borrow(), [0], "refuse before copying payload"); - assert!(!p.exists()); - assert_no_temp(&d.0); - Ok(()) - } - - #[cfg(target_os = "linux")] - #[test] - #[ignore = "requires setfacl/getfacl and a filesystem with POSIX ACL support"] - fn normal_permissions_follow_inherited_acl_with_hard_links_and_copy() -> io::Result<()> { - use std::process::Command; - let d = TempDir::new("normal-acl"); - let output = Command::new("setfacl").args(["-m", "d:u::rwx,d:u:12345:r--,d:g::r-x,d:m::r-x,d:o::---"]).arg(&d.0).output()?; - assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); - let acl = |path: &Path| -> io::Result> { - let output = Command::new("getfacl").args(["-c", "-n"]).arg(path).output()?; - assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); - Ok(output.stdout) - }; - let reference = d.0.join("reference"); - std::fs::write(&reference, b"normal creation")?; - let expected = acl(&reference)?; - for no_hard_links in [false, true] { - let fs = Faulty { no_hard_links, fail_permissions: true, ..Default::default() }; - let p = d.0.join(format!("export-{no_hard_links}")); - create_with_options(&fs, &p, NewFilePermissions::PlatformDefault, |f| f.write_all(b"export"))?; - assert_eq!(acl(&p)?, expected, "same inherited ACL as ordinary creation"); - assert_eq!(std::fs::read(&p)?, b"export"); - } - assert_no_temp(&d.0); - Ok(()) - } - - #[test] - fn retry_delays_are_capped() { - let d = TempDir::new("cap"); - let p = d.0.join("doc.craft"); - let fs = Faulty { locked_renames: Cell::new(2), ..Default::default() }; - let started = std::time::Instant::now(); - assert!(atomic_write_custom(&fs, RenameRetry { attempts: 2, first_delay_ms: 60_000 }, &p, b"new").is_ok()); - assert!(started.elapsed() < std::time::Duration::from_secs(5)); - assert_eq!(fs.renames.get(), 3); - } - - #[test] - fn distinguishes_atomicity_and_durability_order() { - let d = TempDir::new("durability_order"); - let p = d.0.join("doc.craft"); - std::fs::write(&p, ORIGINAL).ok(); - - let fs = Faulty::default(); - atomic_write_custom(&fs, NO_RETRY, &p, b"durable payload").expect("successful atomic write"); - - let events = fs.events.into_inner(); - let sync_file_idx = events.iter().position(|&e| e == "sync_file").expect("file content must be flushed"); - let rename_idx = events.iter().position(|&e| e == "rename").expect("atomic rename must be performed"); - - // 1. Content Durability: staging file must be synced to stable media BEFORE pointer switch (rename) - assert!( - sync_file_idx < rename_idx, - "Durability invariant violated: file content must be flushed to stable storage before rename (sync={sync_file_idx}, rename={rename_idx})" - ); - - // 2. Directory Durability: on Unix, parent directory must be synced AFTER rename to commit directory entry - #[cfg(unix)] - { - let sync_dir_idx = events.iter().position(|&e| e == "sync_dir").expect("directory must be flushed on Unix"); - assert!( - rename_idx < sync_dir_idx, - "Durability invariant violated: parent directory must be flushed after rename (rename={rename_idx}, sync_dir={sync_dir_idx})" - ); - } - } - - #[test] - fn sync_dir_failure_is_best_effort() { - let d = TempDir::new("best_effort_sync_dir"); - let p = d.0.join("doc.craft"); - let fs = Faulty { fail_sync_dir: true, ..Default::default() }; - assert!(atomic_write_custom(&fs, NO_RETRY, &p, b"best effort data").is_ok()); - assert_eq!(std::fs::read(&p).ok(), Some(b"best effort data".to_vec())); - assert_no_temp(&d.0); - } - - #[test] - fn temp_name_format_is_valid() { - let name = temp_name("document.craft"); - assert!(name.starts_with(".document.craft.")); - assert!(name.ends_with(".craft_tmp")); - } - - #[cfg(target_arch = "wasm32")] - #[test] - 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(test)] +#[path = "../tests/main.rs"] +mod integration; diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs new file mode 100644 index 0000000000..78cc37ae16 --- /dev/null +++ b/crates/atomic/src/tests.rs @@ -0,0 +1,584 @@ +//! Tests for the atomic save engine. + +use super::*; +use std::cell::Cell; + +struct TempDir(PathBuf); +impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + #[cfg(not(target_arch = "wasm32"))] + let pid = std::process::id(); + #[cfg(target_arch = "wasm32")] + let pid = 0; + let d = std::env::temp_dir().join(format!("craft-atomic-{tag}-{pid}-{}", N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).ok(); + Self(d) + } +} +impl Drop for TempDir { + fn drop(&mut self) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn assert_no_temp(dir: &Path) { + let leftovers: Vec<_> = std::fs::read_dir(dir) + .ok() + .map(|entries| entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".craft_tmp")).collect()) + .unwrap_or_default(); + assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}"); +} + +const ORIGINAL: &[u8] = b"the user's precious original document"; + +#[derive(Default)] +struct Faulty { + events: std::cell::RefCell>, + fail_sync: bool, + locked_renames: Cell, + renames: Cell, + permission_error: Option, + /// Simulate a network filesystem exposing the same fixed mode on every new file. + #[cfg(unix)] + fixed_mode: Option, + /// Simulate a filesystem that refuses the stage's group change. + #[cfg(unix)] + fail_set_group: bool, +} + +impl AtomicFs for Faulty { + /// Create a real stage, optionally exposing a simulated fixed network mode. + fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { + self.events.borrow_mut().push("create_new"); + let file = RealFs.create_new(path, permissions)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if let Some(mode) = self.fixed_mode { + file.set_permissions(std::fs::Permissions::from_mode(mode))?; + } + } + Ok(file) + } + fn sync(&self, file: &File) -> io::Result<()> { + self.events.borrow_mut().push("sync_file"); + if self.fail_sync { + return Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")); + } + RealFs.sync(file) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + self.events.borrow_mut().push("rename"); + self.renames.set(self.renames.get() + 1); + if self.locked_renames.get() > 0 { + self.locked_renames.set(self.locked_renames.get() - 1); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: sharing violation")); + } + RealFs.rename(from, to) + } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + self.events.borrow_mut().push("hard_link"); + RealFs.hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + self.events.borrow_mut().push("remove"); + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + self.events.borrow_mut().push("sync_dir"); + RealFs.sync_dir(dir) + } + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + self.events.borrow_mut().push("set_group"); + if self.fail_set_group { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: set_group failed")); + } + RealFs.set_group(file, gid) + } + /// Record permission restoration, then inject a configured error or delegate the + /// mode change to the real filesystem. + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + self.events.borrow_mut().push("set_permissions"); + if let Some(kind) = self.permission_error { + return Err(io::Error::new(kind, "injected permission failure")); + } + RealFs.set_permissions(file, perms) + } +} + +const NO_RETRY: RenameRetry = RenameRetry { attempts: 0, first_delay_ms: 0 }; + +#[test] +fn failed_flush_keeps_original() { + let d = TempDir::new("write"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let fs = Faulty { fail_sync: true, ..Default::default() }; + let e = atomic_write_custom(&fs, NO_RETRY, &p, &[7u8; 4096]); + assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::StorageFull)); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_eq!(fs.renames.get(), 0); + assert_no_temp(&d.0); +} + +#[test] +fn locked_target_rename_is_retried() { + let d = TempDir::new("locked"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let fs = Faulty { locked_renames: Cell::new(2), ..Default::default() }; + atomic_write_custom(&fs, RenameRetry { attempts: 3, first_delay_ms: 1 }, &p, b"new").ok(); + assert_eq!(std::fs::read(&p).ok(), Some(b"new".to_vec())); + assert_eq!(fs.renames.get(), 3); + assert_no_temp(&d.0); +} + +/// Matching fixed modes permit byte and streaming replacements under both creation +/// policies without calling a permission operation that the mount rejects. +#[cfg(unix)] +#[test] +fn unchanged_replacement_modes_need_no_chmod() -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("fixed-replacement-mode"); + // GVfs SMB reports 0700 regardless of the requested creation mode; also cover a + // private stage whose normal 0600 mode already matches the original. + for mode in [0o600, 0o700] { + for policy in [NewFilePermissions::Private, NewFilePermissions::PlatformDefault] { + for streaming in [false, true] { + let p = d.0.join(format!("{mode:o}-{policy:?}-{streaming}")); + std::fs::write(&p, ORIGINAL)?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode))?; + let fs = Faulty { fixed_mode: Some(mode), permission_error: Some(io::ErrorKind::Unsupported), ..Default::default() }; + let options = WriteOptions::default().with_new_file_permissions(policy); + if streaming { + options.atomic_write_with_custom(&fs, NO_RETRY, &p, |f| f.write_all(b"replacement"))?; + } else { + options.atomic_write_custom(&fs, NO_RETRY, &p, b"replacement")?; + } + assert_eq!(std::fs::read(&p)?, b"replacement"); + assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o7777, mode); + assert!(!fs.events.borrow().contains(&"set_permissions")); + assert_eq!(fs.renames.get(), 1); + assert_no_temp(&d.0); + } + } + } + Ok(()) +} + +#[cfg(unix)] +#[test] +fn group_bits_are_dropped_when_the_stage_cannot_join_the_replaced_group() -> io::Result<()> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let d = TempDir::new("group-fallback"); + let file = File::create(d.0.join("stage"))?; + let gid = file.metadata()?.gid(); + let elsewhere = gid.wrapping_add(1); + + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o640))?.mode(); + assert_eq!(mode & 0o777, 0o600, "group bits are dropped when the group cannot be joined"); + assert!(fs.events.borrow().contains(&"set_group")); + + // No group bits: the group change is never attempted. + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o600))?.mode(); + assert_eq!(mode & 0o777, 0o600); + assert!(!fs.events.borrow().contains(&"set_group")); + + // A stage already in the replaced file's group keeps its bits untouched. + let fs = Faulty { fail_set_group: true, ..Default::default() }; + let mode = adopt_group(&fs, &file, gid, gid, std::fs::Permissions::from_mode(0o640))?.mode(); + assert_eq!(mode & 0o777, 0o640); + assert!(!fs.events.borrow().contains(&"set_group")); + + assert_no_temp(&d.0); + Ok(()) +} + +#[test] +fn distinguishes_atomicity_and_durability_order() { + let d = TempDir::new("durability_order"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + + let fs = Faulty::default(); + atomic_write_custom(&fs, NO_RETRY, &p, b"durable payload").expect("successful atomic write"); + + let events = fs.events.into_inner(); + let sync_file_idx = events.iter().position(|&e| e == "sync_file").expect("file content must be flushed"); + let rename_idx = events.iter().position(|&e| e == "rename").expect("atomic rename must be performed"); + + // 1. Content Durability: staging file must be synced to stable media BEFORE pointer switch (rename) + assert!( + sync_file_idx < rename_idx, + "Durability invariant violated: file content must be flushed to stable storage before rename (sync={sync_file_idx}, rename={rename_idx})" + ); + + // 2. Directory Durability: on Unix, parent directory must be synced AFTER rename to commit directory entry + #[cfg(unix)] + { + let sync_dir_idx = events.iter().position(|&e| e == "sync_dir").expect("directory must be flushed on Unix"); + assert!( + rename_idx < sync_dir_idx, + "Durability invariant violated: parent directory must be flushed after rename (rename={rename_idx}, sync_dir={sync_dir_idx})" + ); + } +} + +#[test] +fn temp_name_format_is_valid() { + let name = temp_name("document.craft"); + assert!(name.starts_with(".document.craft.")); + assert!(name.ends_with(".craft_tmp")); +} + +/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there. +#[derive(Clone, Copy, Debug)] +enum Obstacle { + File, + Folder, + /// A link to the file `outside` beside the stage. + #[cfg(unix)] + Link, + /// A link to `missing` beside the stage, which does not exist. + #[cfg(unix)] + DanglingLink, +} + +/// The real filesystem, except that the first `obstacles.len()` stage names get an obstacle +/// planted at them first, as someone racing the save would. +struct Planting { + obstacles: Vec, + planted: std::cell::RefCell>, +} + +impl Planting { + fn new(obstacles: Vec) -> Self { + Self { obstacles, planted: Default::default() } + } + + fn plant(&self, at: &Path) -> io::Result<()> { + let next = self.planted.borrow().len(); + let Some(&obstacle) = self.obstacles.get(next) else { return Ok(()) }; + match obstacle { + Obstacle::File => std::fs::write(at, b"PLANTED")?, + Obstacle::Folder => std::fs::create_dir(at)?, + #[cfg(unix)] + Obstacle::Link => std::os::unix::fs::symlink(at.with_file_name("outside"), at)?, + #[cfg(unix)] + Obstacle::DanglingLink => std::os::unix::fs::symlink(at.with_file_name("missing"), at)?, + } + self.planted.borrow_mut().push(at.to_path_buf()); + Ok(()) + } +} + +impl AtomicFs for Planting { + fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { + self.plant(path)?; + RealFs.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { + RealFs.sync(file) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.rename(from, to) + } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + RealFs.set_permissions(file, perms) + } + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + RealFs.set_group(file, gid) + } +} + +/// A stage name something already has (a file, a folder, a link, a dangling link) is skipped, +/// never opened: writing through it would put the user's document where the planter chose. With +/// every name taken the save fails and the original is kept. +#[test] +fn a_name_taken_at_the_stage_is_skipped_and_never_written_through() { + let d = TempDir::new("planted"); + let p = d.0.join("doc.craft"); + let outside = d.0.join("outside"); + std::fs::write(&p, ORIGINAL).unwrap(); + std::fs::write(&outside, b"OUTSIDE").unwrap(); + + #[cfg(unix)] + let obstacles = vec![Obstacle::File, Obstacle::Folder, Obstacle::Link, Obstacle::DanglingLink]; + #[cfg(not(unix))] + let obstacles = vec![Obstacle::File, Obstacle::Folder]; + let fs = Planting::new(obstacles.clone()); + atomic_write_custom(&fs, NO_RETRY, &p, b"new").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + let planted = fs.planted.into_inner(); + assert_eq!(planted.len(), obstacles.len(), "every obstacle was met"); + for (at, obstacle) in planted.iter().zip(&obstacles) { + let meta = std::fs::symlink_metadata(at).unwrap(); + match obstacle { + Obstacle::File => assert_eq!(std::fs::read(at).unwrap(), b"PLANTED", "the planted file is not written"), + Obstacle::Folder => assert!(meta.is_dir() && std::fs::read_dir(at).unwrap().next().is_none(), "the folder is left empty"), + #[cfg(unix)] + Obstacle::Link | Obstacle::DanglingLink => assert!(meta.file_type().is_symlink(), "the link is left as a link"), + } + } + assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE", "nothing was written through a link"); + assert!(!outside.with_file_name("missing").exists(), "a dangling link's file was not created"); + for at in &planted { + let _ = std::fs::remove_file(at).or_else(|_| std::fs::remove_dir(at)); + } + assert_no_temp(&d.0); + + // Every name taken: the save is refused and the original kept. + let fs = Planting::new(vec![Obstacle::File; 64]); + let e = atomic_write_custom(&fs, NO_RETRY, &p, b"newer").unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{e}"); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + for at in fs.planted.into_inner() { + assert_eq!(std::fs::read(&at).unwrap(), b"PLANTED"); + let _ = std::fs::remove_file(at); + } + assert_no_temp(&d.0); +} + +/// A name near the 255-byte limit, in four-byte characters, still stages: the temporary name +/// keeps at most 128 bytes of it, cut between characters, and only the target is left. +#[test] +fn a_long_name_stages_and_leaves_only_the_target() { + let d = TempDir::new("long-name"); + // 2 + 61 × 4 + 4 = 250 bytes, 67 characters: the first 64 characters alone are 247 bytes. + let name = format!("ab{}.pdf", "\u{1F600}".repeat(61)); + assert_eq!(name.len(), 250); + let p = d.0.join(&name); + atomic_write(&p, b"first").unwrap(); + atomic_write(&p, b"second").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"second"); + let left: Vec<_> = std::fs::read_dir(&d.0).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(left, [std::ffi::OsString::from(&name)], "only the target is left"); + + let staged = temp_name(&name); + assert!(staged.len() <= 255, "{} bytes", staged.len()); + assert!(staged.starts_with(&format!(".ab{}.", "\u{1F600}".repeat(31))), "128 bytes of the name, cut between characters: {staged}"); +} + +/// Reads the extended attribute `name` of `path`, following no further than the path itself. +#[cfg(target_os = "macos")] +fn xattr(path: &Path, name: &str) -> Option> { + let size = rustix::fs::getxattr_query(path, name).ok()?; + let mut value = vec![0u8; size.max(1)]; + let len = rustix::fs::getxattr(path, name, &mut value[..]).ok()?; + value.truncate(len); + Some(value) +} + +/// A save keeps the replaced file's extended attributes (Finder tags, the "Open with" binding, +/// quarantine, binary, empty and resource-fork values), save after save, including one another +/// process sets while the stage is written. Through a symbolic link the link stays and the file it +/// names keeps them. A link swapped in at the target while staging is never read through: its +/// file's attributes stay its own. (`com.apple.provenance` cannot be set by a test; a file that +/// has it saves only because the copy skips it, as macOS refuses writing it.) +#[cfg(target_os = "macos")] +#[test] +fn attributes_set_while_staging_are_kept() { + use rustix::fs::{XattrFlags, setxattr}; + let d = TempDir::new("xattrs"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + let attributes: &[(&str, &[u8])] = &[ + ("com.apple.metadata:_kMDItemUserTags", b"Craft\n6"), + ("com.apple.LaunchServices.OpenWith", b"bplist00\xd1\x01\x02Wversion\x10\x00"), + ("com.apple.quarantine", b"0081;5e0d1d05;Craft;"), + ("com.craft.test.binary", b"\0\xff\x80original\0"), + ("com.craft.test.empty", b""), + ("com.apple.ResourceFork", b"\0\xfffork"), + ]; + for (name, value) in attributes { + setxattr(&target, *name, value, XattrFlags::empty()).unwrap(); + } + // What the system stored (quarantine may be normalised): the saved file must hold the same. + let stored: Vec<_> = attributes.iter().map(|(name, _)| (*name, xattr(&target, name).unwrap())).collect(); + + for save in 0..2 { + atomic_write_with(&target, |f| { + // Another process tags the original while the new bytes are written. + setxattr(&target, "com.craft.test.late", format!("late {save}").as_bytes(), XattrFlags::empty())?; + f.write_all(b"new") + }) + .unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + for (name, value) in &stored { + assert_eq!(xattr(&target, name).as_ref(), Some(value), "save {save} keeps {name}"); + } + assert_eq!(xattr(&target, "com.craft.test.late"), Some(format!("late {save}").into_bytes()), "set while staging"); + assert_no_temp(&d.0); + } + + // Through a link: the link stays, the file it names is replaced and keeps its attributes. + let link = d.0.join("link.pdf"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + atomic_write(&link, b"through the link").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link"); + assert_eq!(std::fs::read(&target).unwrap(), b"through the link"); + for (name, value) in &stored { + assert_eq!(xattr(&target, name).as_ref(), Some(value), "the linked file keeps {name}"); + } + + // A link put at the target while staging names another file: nothing is read through it. + let outside = d.0.join("outside.pdf"); + std::fs::write(&outside, b"OUTSIDE").unwrap(); + setxattr(&outside, "com.craft.test.private", b"private", XattrFlags::empty()).unwrap(); + atomic_write_with(&target, |f| { + std::fs::remove_file(&target)?; + std::os::unix::fs::symlink(&outside, &target)?; + f.write_all(b"swapped") + }) + .unwrap(); + assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE"); + assert_eq!(xattr(&outside, "com.craft.test.private"), Some(b"private".to_vec())); + assert!(!std::fs::symlink_metadata(&target).unwrap().file_type().is_symlink()); + assert_eq!(xattr(&target, "com.craft.test.private"), None, "the swapped-in link's file lent nothing"); + assert_no_temp(&d.0); +} + +/// An attribute past the 16 MiB value bound refuses the save instead of dropping it: the target +/// keeps its bytes and its attribute, and no stage is left. +#[cfg(target_os = "macos")] +#[test] +fn oversized_attributes_refuse_the_save_and_keep_the_target() { + use rustix::fs::{XattrFlags, getxattr_query, setxattr}; + let d = TempDir::new("xattrs-bound"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + // Only a resource fork may be this large; the bytes exist only in this temporary file. + let fork = vec![42u8; 16 * 1024 * 1024 + 1]; + setxattr(&target, "com.apple.ResourceFork", &fork, XattrFlags::empty()).unwrap(); + let e = atomic_write(&target, b"new").unwrap_err(); + assert!(e.to_string().contains("extended attributes"), "{e}"); + assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL); + assert_eq!(getxattr_query(&target, "com.apple.ResourceFork").unwrap(), fork.len()); + assert_no_temp(&d.0); +} + +/// A value read must fill the size first queried and keep it in a second query: a growing +/// resource fork returns the prefix that fits instead of an error. Complete values, empty and +/// binary, are kept as read. +#[cfg(target_os = "macos")] +#[test] +fn an_attribute_read_must_fill_its_size_and_keep_it() { + for bytes in [&b""[..], &b"\0\xffB"[..]] { + let value = read_xattr_value( + bytes.len(), + |buffer| { + buffer[..bytes.len()].copy_from_slice(bytes); + Ok(bytes.len()) + }, + || Ok(bytes.len()), + ) + .unwrap(); + assert_eq!(value, bytes); + } + // A short read, a size that grew after the read, a prefix of a grown value. + for (before, read_len, after) in [(3, 2, 3), (3, 3, 4), (0, 1, 1), (3, 2, 2)] { + let e = read_xattr_value(before, |_| Ok(read_len), || Ok(after)).unwrap_err(); + assert!(e.to_string().contains("changed size"), "{before} {read_len} {after}: {e}"); + } + let e = read_xattr_value(3, |_| Ok(3), || Err(io::Error::new(io::ErrorKind::PermissionDenied, "recheck refused"))).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); +} + +/// A saved document is the same document: it keeps its creation date. A new file gets its own. +#[cfg(any(target_os = "macos", windows))] +#[test] +fn a_replaced_files_creation_date_is_kept() { + #[cfg(target_os = "macos")] + use std::os::macos::fs::FileTimesExt; + #[cfg(windows)] + use std::os::windows::fs::FileTimesExt; + let d = TempDir::new("created"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + // 2020-01-02 03:04:05 UTC. + let then = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_577_934_245); + let file = OpenOptions::new().write(true).open(&target).unwrap(); + file.set_times(std::fs::FileTimes::new().set_created(then)).unwrap(); + drop(file); + assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the fixture's date is set"); + atomic_write(&target, b"new").unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the saved file keeps its creation date"); + let fresh = d.0.join("new.pdf"); + atomic_write(&fresh, b"new").unwrap(); + assert!(std::fs::metadata(&fresh).unwrap().created().unwrap() > then, "a new file has a date of its own"); +} + +/// A hidden or system file stays hidden or system, and its stage already is while written; a +/// plain file stays plain though the stage's name starts with a dot; a new file gets neither. +/// Through a symbolic link the file it names is the replaced file and keeps its attributes. +#[cfg(windows)] +#[test] +fn hidden_and_system_attributes_are_kept() { + use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; + const HIDDEN: u32 = 0x2; + const SYSTEM: u32 = 0x4; + let d = TempDir::new("attributes"); + let kept = |p: &Path| std::fs::metadata(p).unwrap().file_attributes() & (HIDDEN | SYSTEM); + let plant = |p: &Path, attributes: u32| { + let mut fixture = OpenOptions::new().write(true).create_new(true).attributes(attributes).open(p).unwrap(); + fixture.write_all(ORIGINAL).unwrap(); + }; + for (i, keep) in [0, HIDDEN, SYSTEM, HIDDEN | SYSTEM].into_iter().enumerate() { + let target = d.0.join(format!("doc{i}.pdf")); + plant(&target, keep); + assert_eq!(kept(&target), keep, "the fixture has attributes {keep:#x}"); + let mut staged = u32::MAX; + atomic_write_with(&target, |f| { + staged = f.metadata()?.file_attributes() & (HIDDEN | SYSTEM); + f.write_all(b"new") + }) + .unwrap(); + assert_eq!(staged, keep, "the stage has the target's attributes before it is flushed"); + assert_eq!(kept(&target), keep, "the saved file keeps attributes {keep:#x}"); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + } + let fresh = d.0.join("new.pdf"); + atomic_write(&fresh, b"new").unwrap(); + assert_eq!(kept(&fresh), 0, "a new file is neither hidden nor system"); + + let referent = d.0.join("referent.pdf"); + plant(&referent, HIDDEN); + let link = d.0.join("link.pdf"); + if let Err(e) = std::os::windows::fs::symlink_file(&referent, &link) { + eprintln!("skipped the link case: creating a symbolic link needs Developer Mode or administrator rights ({e})"); + return; + } + atomic_write(&link, b"through the link").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link"); + assert_eq!(std::fs::read(&referent).unwrap(), b"through the link"); + assert_eq!(kept(&referent), HIDDEN, "the file the link names stays hidden"); + assert_no_temp(&d.0); +} + +#[cfg(target_arch = "wasm32")] +#[test] +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); +} diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index b5001bc724..fcafd2ca78 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -1,7 +1,8 @@ -#[cfg(unix)] -use craft_atomic::{NewFilePermissions, WriteOptions, atomic_write, write_new}; -use craft_atomic::{atomic_write_with, or_plain_fsync, write_new_with}; -use std::cell::Cell; +//! Integration tests of craft-atomic: atomic tests. + +#![cfg(unix)] + +use craft_atomic::{atomic_write, atomic_write_with}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -37,97 +38,6 @@ fn assert_no_temp(dir: &Path) { const ORIGINAL: &[u8] = b"original precious document"; -#[test] -fn atomic_write_with_streaming_writer() { - let d = TempDir::new("stream"); - let p = d.0.join("doc.dat"); - std::fs::write(&p, ORIGINAL).ok(); - - atomic_write_with(&p, |f| { - f.write_all(b"chunk1 ")?; - f.write_all(b"chunk2") - }) - .ok(); - - assert_eq!(std::fs::read(&p).ok(), Some(b"chunk1 chunk2".to_vec())); - assert_no_temp(&d.0); -} - -#[test] -fn write_new_with_streaming_writer() { - let d = TempDir::new("write_new_stream"); - let p = d.0.join("new.dat"); - - write_new_with(&p, |f| f.write_all(b"new content")).ok(); - - assert_eq!(std::fs::read(&p).ok(), Some(b"new content".to_vec())); - assert_no_temp(&d.0); - - // Second write to existing file must fail with AlreadyExists - let res = write_new_with(&p, |f| f.write_all(b"overwritten?")); - assert!(res.is_err()); - assert_eq!(std::fs::read(&p).ok(), Some(b"new content".to_vec())); -} - -#[test] -fn streaming_failure_aborts_and_keeps_original() { - let d = TempDir::new("stream_fail"); - let p = d.0.join("doc.dat"); - std::fs::write(&p, ORIGINAL).ok(); - - let res = atomic_write_with(&p, |f| { - f.write_all(b"half a file")?; - Err(io::Error::new(io::ErrorKind::StorageFull, "disk full")) - }); - - assert!(res.is_err()); - assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); - assert_no_temp(&d.0); -} - -#[test] -fn apple_full_fsync_fallback_behavior() { - let refused = |errno| Err(io::Error::from_raw_os_error(errno)); - for (errno, name) in [(45, "ENOTSUP (SMB)"), (25, "ENOTTY")] { - let fsynced = Cell::new(false); - let r = or_plain_fsync(refused(errno), || { - fsynced.set(true); - Ok(()) - }); - let apple = cfg!(target_vendor = "apple"); - assert_eq!(r.is_ok(), apple, "{name}"); - assert_eq!(fsynced.get(), apple, "{name}: fsync fallback only runs on Apple"); - } - - // Unrelated errors (e.g. EIO = 5) must not fallback - let r = or_plain_fsync(refused(5), || panic!("should not run for EIO")); - assert_eq!(r.map_err(|e| e.raw_os_error()), Err(Some(5))); -} - -#[cfg(unix)] -#[test] -fn mode_and_symlink_preservation() { - use std::os::unix::fs::PermissionsExt; - let d = TempDir::new("mode_symlink"); - - // Permissions - let p = d.0.join("secret.key"); - std::fs::write(&p, ORIGINAL).ok(); - std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).ok(); - atomic_write(&p, b"updated secret").ok(); - let mode = std::fs::metadata(&p).map(|m| m.permissions().mode() & 0o777).ok(); - assert_eq!(mode, Some(0o600)); - - // Symlink - let real = d.0.join("real.txt"); - let link = d.0.join("link.txt"); - std::fs::write(&real, ORIGINAL).ok(); - std::os::unix::fs::symlink(&real, &link).ok(); - atomic_write(&link, b"through symlink").ok(); - assert!(std::fs::symlink_metadata(&link).map(|m| m.file_type().is_symlink()).unwrap_or(false)); - assert_eq!(std::fs::read(&real).ok(), Some(b"through symlink".to_vec())); -} - #[cfg(unix)] #[test] fn dangling_relative_symlink_stays_a_link() { @@ -143,18 +53,6 @@ fn dangling_relative_symlink_stays_a_link() { assert_no_temp(&d.0.join("real")); } -#[cfg(unix)] -#[test] -fn symlink_loop_is_an_error() { - let d = TempDir::new("loop"); - std::os::unix::fs::symlink("b", d.0.join("a")).ok(); - std::os::unix::fs::symlink("a", d.0.join("b")).ok(); - assert!(atomic_write(&d.0.join("a"), b"x").is_err_and(|e| e.to_string().starts_with("cannot save") && e.to_string().contains("symbolic links"))); - assert!(write_new(&d.0.join("a"), b"x").is_err()); - assert!(std::fs::symlink_metadata(d.0.join("a")).map(|m| m.file_type().is_symlink()).unwrap_or(false)); - assert_no_temp(&d.0); -} - #[cfg(unix)] #[test] fn read_only_target_is_not_replaced() { @@ -202,39 +100,48 @@ fn private_staging_preserves_existing_modes_after_callback() -> io::Result<()> { Ok(()) } -#[cfg(unix)] -#[test] -fn explicit_private_files_keep_callback_permissions() -> io::Result<()> { - use std::fs::Permissions; - use std::os::unix::fs::PermissionsExt; +/// Extended attribute names on `path`, read by path. +#[cfg(target_os = "macos")] +fn xattr_names(path: &Path) -> Vec> { + let mut names = vec![0u8; 64 * 1024]; + let len = rustix::fs::listxattr(path, names.as_mut_slice()).unwrap_or(0); + names.truncate(len); + names.split(|b| *b == 0).filter(|n| !n.is_empty()).map(<[u8]>::to_vec).collect() +} - let d = TempDir::new("private_new"); - let options = WriteOptions::default().with_new_file_permissions(NewFilePermissions::Private); - for exclusive in [false, true] { - let p = d.0.join(format!("new-{exclusive}.craft")); - let fill = |f: &mut std::fs::File| { - assert_eq!(f.metadata()?.permissions().mode() & 0o777, 0o600); - f.write_all(b"new payload")?; - // A new file has no existing mode to restore, so the callback may select it. - f.set_permissions(Permissions::from_mode(0o640)) - }; - if exclusive { - options.write_new_with(&p, fill)?; - } else { - options.atomic_write_with(&p, fill)?; - } - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, 0o640); - assert_eq!(std::fs::read(&p)?, b"new payload"); - } - for exclusive in [false, true] { - let p = d.0.join(format!("default-{exclusive}.craft")); - if exclusive { - options.write_new(&p, b"explicitly private")?; - } else { - options.atomic_write(&p, b"explicitly private")?; - } - assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, 0o600); - } - assert_no_temp(&d.0); +/// A write-only file (mode 0200) saves: macOS lets its owner neither read its data nor list its +/// attributes, so its attributes are dropped, as before attributes were kept. +#[cfg(target_os = "macos")] +#[test] +fn a_write_only_file_saves_and_drops_the_attributes_it_cannot_read() -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("write_only_xattrs"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL)?; + rustix::fs::setxattr(&p, "com.craft.t", b"tag", rustix::fs::XattrFlags::empty())?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o200))?; + atomic_write(&p, b"new")?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600))?; + assert_eq!(std::fs::read(&p)?, b"new"); + assert!(!xattr_names(&p).iter().any(|n| n == b"com.craft.t"), "the unreadable attribute is dropped"); + Ok(()) +} + +/// A file whose data an ACL denies but whose attribute names can be listed is not replaced: its +/// attributes can't be copied without its data, and the save refuses rather than drop them. +#[cfg(target_os = "macos")] +#[test] +fn an_unreadable_file_with_listable_attributes_is_not_replaced() -> io::Result<()> { + let d = TempDir::new("acl_denied_xattrs"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL)?; + rustix::fs::setxattr(&p, "com.craft.t", b"tag", rustix::fs::XattrFlags::empty())?; + let denied = std::process::Command::new("/bin/chmod").arg("+a").arg("everyone deny read").arg(&p).status()?; + assert!(denied.success(), "the ACL is set"); + let result = atomic_write(&p, b"new"); + let _ = std::process::Command::new("/bin/chmod").arg("-N").arg(&p).status(); + assert!(result.is_err(), "the save is refused"); + assert_eq!(std::fs::read(&p)?, ORIGINAL, "the original is unchanged"); + assert!(xattr_names(&p).iter().any(|n| n == b"com.craft.t"), "and keeps its attribute"); Ok(()) } diff --git a/crates/atomic/tests/main.rs b/crates/atomic/tests/main.rs new file mode 100644 index 0000000000..ec0e4ec606 --- /dev/null +++ b/crates/atomic/tests/main.rs @@ -0,0 +1,4 @@ +//! Integration tests, built into the library's own test executable. + +mod atomic_tests; +mod permissions; diff --git a/crates/atomic/tests/permissions.rs b/crates/atomic/tests/permissions.rs index 1d0c894601..95702cfe70 100644 --- a/crates/atomic/tests/permissions.rs +++ b/crates/atomic/tests/permissions.rs @@ -1,14 +1,21 @@ +//! Integration tests of craft-atomic: permissions. + #![cfg(unix)] use craft_atomic::{NewFilePermissions, WriteOptions, atomic_write, write_new}; use std::fs::{self, File, Permissions}; use std::io::{self, Write}; use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; +use std::path::Path; +#[cfg(target_os = "linux")] +use std::path::PathBuf; use std::process::Command; +#[cfg(target_os = "linux")] use std::sync::atomic::{AtomicU64, Ordering}; +#[cfg(target_os = "linux")] struct TempDir(PathBuf); +#[cfg(target_os = "linux")] impl TempDir { fn new() -> io::Result { static N: AtomicU64 = AtomicU64::new(0); @@ -17,6 +24,7 @@ impl TempDir { Ok(Self(path)) } } +#[cfg(target_os = "linux")] impl Drop for TempDir { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); @@ -27,10 +35,11 @@ fn mode(path: &Path) -> io::Result { Ok(fs::metadata(path)?.permissions().mode() & 0o777) } +#[cfg(target_os = "linux")] /// Set umask only in a separate shell process; changing it in a parallel test process races. fn child(dir: &Path, mask: &str, expected: &str, check_acl: bool) -> io::Result<()> { let output = Command::new("sh") - .args(["-c", "umask \"$1\"; exec \"$2\" --exact permission_child --nocapture", "permissions", mask]) + .args(["-c", "umask \"$1\"; exec \"$2\" --exact integration::permissions::permission_child --nocapture", "permissions", mask]) .arg(std::env::current_exe()?) .env("CRAFT_PERMISSION_TEST_DIR", dir) .env("CRAFT_PERMISSION_TEST_EXPECTED", expected) @@ -41,15 +50,6 @@ fn child(dir: &Path, mask: &str, expected: &str, check_acl: bool) -> io::Result< Ok(()) } -#[test] -fn normal_creation_matches_os_permissions() -> io::Result<()> { - for (mask, expected) in [("000", "666"), ("002", "664"), ("022", "644"), ("027", "640"), ("077", "600")] { - let dir = TempDir::new()?; - child(&dir.0, mask, expected, false)?; - } - Ok(()) -} - #[test] fn permission_child() -> io::Result<()> { let Some(dir) = std::env::var_os("CRAFT_PERMISSION_TEST_DIR") else { return Ok(()) }; diff --git a/crates/audio-dsp/Cargo.toml b/crates/audio-dsp/Cargo.toml index 5d192e9d31..46e708b732 100644 --- a/crates/audio-dsp/Cargo.toml +++ b/crates/audio-dsp/Cargo.toml @@ -12,3 +12,6 @@ workspace = true # No dependencies: planar `&mut [f32]` slices in, planar slices out. [dependencies] + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/audio-dsp/src/biquad.rs b/crates/audio-dsp/src/biquad.rs index 12d00f5a9a..6b10add2b7 100644 --- a/crates/audio-dsp/src/biquad.rs +++ b/crates/audio-dsp/src/biquad.rs @@ -448,7 +448,7 @@ mod tests { #[test] fn every_effect_recovers_after_one_non_finite_sample() { let mut failures = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { for setting in [Setting::Default, Setting::Moved, Setting::Min] { let (l, r, _) = run_effect(e.id, setting, None); let clean = tail_rms(&l, &r); @@ -505,7 +505,7 @@ mod tests { #[test] fn nan_parameter_values_never_produce_non_finite_output() { let mut bad = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { let ids: Vec<&str> = crate::create_effect(e.id, SR as f32, 2).unwrap().params().iter().map(|p| p.id).collect(); for id in ids { let mut fx = crate::create_effect(e.id, SR as f32, 2).unwrap(); @@ -525,7 +525,7 @@ mod tests { #[test] fn subnormal_input_stays_finite_and_decays() { let mut bad = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { for setting in [Setting::Default, Setting::Min] { let mut fx = crate::create_effect(e.id, SR as f32, 2).unwrap(); for p in fx.params() { diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 29c406d7a1..679b7c5f9a 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -234,7 +234,7 @@ mod tests { let src_l = noise(1, n, 0.7); let src_r = noise(2, n, 0.7); let change_at = 11111; - for e in effects() { + for e in crate::testutil::sampled_effects() { let run = |sizes: &mut dyn FnMut() -> usize| { let mut fx = (e.create)(SR, 2); let (mut l, mut r) = (src_l.clone(), src_r.clone()); @@ -289,8 +289,9 @@ mod tests { // One thread per effect. The tail stays 40 s long: delays, reverbs and graphic EQs still // produce output in its last second, some of it within 3x of the smallest normal f32. std::thread::scope(|scope| { - for e in effects() { + for e in crate::testutil::sampled_effects() { scope.spawn(move || { + let started = std::time::Instant::now(); for setting in [0.0f32, 1.0] { let mut fx = (e.create)(SR, 2); for p in e.params { @@ -318,6 +319,9 @@ mod tests { ); } } + if started.elapsed() > std::time::Duration::from_secs(1) { + eprintln!("DIAG extreme settings: {} took {:?}", e.id, started.elapsed()); + } }); } }); @@ -325,7 +329,7 @@ mod tests { #[test] fn reset_restores_initial_behavior() { - for e in effects() { + for e in crate::testutil::sampled_effects() { let mut fx = (e.create)(SR, 2); let x = noise(8, 6000, 0.5); let (mut a1, mut a2) = (x.clone(), x.clone()); diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index dee405664d..0b6f05a802 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -429,7 +429,7 @@ fn convolution_reverb_impulses() { for (k, want_rt) in [(0usize, 0.45), (2, 1.9), (4, 1.6)] { let mut e = fx("convolution_reverb", &[("impulse", k as f32), ("mix", 100.0), ("width", 100.0)]); let lat = e.latency(); - let n = (SR * 4.0) as usize; + let n = (SR * 3.0) as usize; let mut imp = vec![0.0f32; n]; imp[0] = 1.0; let (l, r) = run(e.as_mut(), &imp, &imp); @@ -444,7 +444,7 @@ fn convolution_reverb_impulses() { } // Room size shortens the tail. let mut a = fx("convolution_reverb", &[("impulse", 2.0), ("mix", 100.0), ("room_size", 40.0)]); - let n = (SR * 3.0) as usize; + let n = (SR * 2.5) as usize; let mut imp = vec![0.0f32; n]; imp[0] = 1.0; let (l, _) = run(a.as_mut(), &imp, &imp); diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index 160362fc9e..c4b9ed7070 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -470,7 +470,7 @@ mod tests { use crate::AudioEffect; use crate::effects::DeNoise; const SR: f32 = 48_000.0; - let len = 512 * 940; + let len = 512 * 320; let mut rng = Rng::new(9); let a: Vec = (0..len).map(|_| 0.1 * rng.uniform()).collect(); let t = crate::testutil::sine(700.0, 0.2, SR as f64, len, 0.0); diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 2c6e4c733f..59bfaa1741 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -2,7 +2,7 @@ //! //! * [`loudness`]: ITU-R BS.1770-4 / EBU R128 loudness meter (momentary, short-term, //! integrated, loudness range, sample peak, true peak) and the loudness-normalization helper. -//! * [`effects`]: audio effects behind the common [`AudioEffect`] trait, with a registry +//! * [`mod@effects`]: audio effects behind the common [`AudioEffect`] trait, with a registry //! ([`effects()`]) describing every effect's parameters (range, unit, default) so a host and //! its interface can build controls generically. //! * [`biquad`]: RBJ-cookbook biquads (TDF-II) with analytic magnitude response. @@ -434,6 +434,12 @@ pub(crate) fn block_len(channels: &[&mut [f32]]) -> usize { #[cfg(test)] pub(crate) mod testutil { + /// Every `CRAFT_HOSTILE_DIVISOR`-th registered effect: the gate's sample of a sweep over all + /// effects; the nightly run (no divisor) covers them all. + pub fn sampled_effects() -> impl Iterator { + crate::effects().iter().step_by(craft_testkit::hostile::divisor()) + } + /// Tiny deterministic PRNG (xorshift64*) for tests. pub struct Rng(u64); impl Rng { diff --git a/crates/audio-dsp/src/loudness.rs b/crates/audio-dsp/src/loudness.rs index 4be4016c71..a89a22593b 100644 --- a/crates/audio-dsp/src/loudness.rs +++ b/crates/audio-dsp/src/loudness.rs @@ -12,7 +12,7 @@ //! to the placement of blocks within 0.01 LU of the relative threshold. //! * Loudness range (EBU Tech 3342): short-term values, −70 LUFS absolute and −20 LU relative //! gate, LRA = 95th − 10th percentile. -//! * Sample peak and true peak (polyphase oversampling to ≥ 176.4 kHz, see [`crate::oversample`]). +//! * Sample peak and true peak (polyphase oversampling to ≥ 176.4 kHz, in the crate's internal `oversample` module). use crate::biquad::{Biquad, Coeffs}; use crate::oversample::{Interpolator, PolyphaseBank, TAPS_PER_PHASE, true_peak_factor}; @@ -625,7 +625,7 @@ mod tests { fn tech3341_case1_and_2_stereo_sine() { for (sr, freq) in [(48000.0, 1000.0), (44100.0, 997.0), (96000.0, 1000.0)] { for level in [-23.0, -33.0] { - let x = segments(freq, sr, &[(20.0, level)]); + let x = segments(freq, sr, &[(6.0, level)]); let m = stereo_measure(&x, sr); assert!((m.integrated() - level).abs() < 0.1, "sr {sr} I {}", m.integrated()); assert!((m.momentary() - level).abs() < 0.1, "M {}", m.momentary()); @@ -639,7 +639,7 @@ mod tests { #[test] fn interleaved_matches_planar() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(5.0, -20.0)]); + let x = segments(1000.0, sr, &[(2.0, -20.0)]); let il: Vec = x.iter().flat_map(|&v| [v, v]).collect(); let mut m = LoudnessMeter::new(sr, 2); m.process_interleaved(&il); @@ -650,12 +650,12 @@ mod tests { #[test] fn tech3341_case3_4_gating() { let sr = 48000.0; - // Case 3: -36 / -23 / -36 dBFS for 10 / 60 / 10 s → -23.0 LUFS. - let x = segments(1000.0, sr, &[(10.0, -36.0), (60.0, -23.0), (10.0, -36.0)]); + // Case 3: -36 / -23 / -36 dBFS for 3 / 18 / 3 s → -23.0 LUFS. + let x = segments(1000.0, sr, &[(3.0, -36.0), (18.0, -23.0), (3.0, -36.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); - // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 10/10/60/10/10 s → -23.0 LUFS. - let x = segments(1000.0, sr, &[(10.0, -72.0), (10.0, -36.0), (60.0, -23.0), (10.0, -36.0), (10.0, -72.0)]); + // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 3/3/18/3/3 s → -23.0 LUFS. + let x = segments(1000.0, sr, &[(3.0, -72.0), (3.0, -36.0), (18.0, -23.0), (3.0, -36.0), (3.0, -72.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); } @@ -663,7 +663,7 @@ mod tests { #[test] fn tech3341_case5_relative_gate() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(20.0, -26.0), (20.1, -20.0), (20.0, -26.0)]); + let x = segments(1000.0, sr, &[(5.0, -26.0), (5.025, -20.0), (5.0, -26.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); } @@ -683,7 +683,8 @@ mod tests { #[test] fn tech3342_loudness_range() { - let sr = 48000.0; + // The range is level-relative, so a low rate gives the same reading for far fewer samples. + let sr = 16000.0; let cases: [(&[(f64, f64)], f64); 4] = [ (&[(20.0, -20.0), (20.0, -30.0)], 10.0), (&[(20.0, -20.0), (20.0, -15.0)], 5.0), @@ -712,15 +713,17 @@ mod tests { assert_eq!(before, 0.0); assert!((m.file_loudness_range() - s.loudness_range_lu).abs() < 1e-12); assert_eq!(m.loudness_range(), before); - // A steady program keeps a file range near 0. - let y = segments(1000.0, sr, &[(30.0, -20.0)]); - assert!(measure(&[&y, &y], sr).loudness_range_lu < 1.0); + // A steady program keeps a file range near 0. It must be long beside the 1.5 s silence tail, so it runs at a + // low rate (the range is level-relative). + let low = 16000.0; + let y = segments(1000.0, low, &[(30.0, -20.0)]); + assert!(measure(&[&y, &y], low).loudness_range_lu < 1.0); } #[test] fn log_sweep_matches_analytic_k_weighting() { let sr = 48000.0; - let secs = 20.0; + let secs = 6.0; let n = (sr * secs) as usize; let (f1, f2) = (20.0f64, 20000.0f64); let k = (f2 / f1).ln(); @@ -749,7 +752,7 @@ mod tests { #[test] fn surround_weights() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); let z = vec![0.0f32; x.len()]; // Signal only in Ls of a 5.1 layout → +1.5 dB weighting vs. front channel. let mut front = LoudnessMeter::new(sr, 6); @@ -767,7 +770,7 @@ mod tests { #[test] fn surround_weights_follow_speaker_positions() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); let z = vec![0.0f32; x.len()]; let only = |n: usize, ch: usize| { let mut m = LoudnessMeter::new(sr, n); @@ -776,7 +779,8 @@ mod tests { m.integrated() }; let front = only(8, 0); - assert!((only(8, 4) - front).abs() < 0.01, "back {}", only(8, 4) - front); + let back = only(8, 4) - front; + assert!(back.abs() < 0.01, "back {back}"); assert!((only(8, 6) - front - 10.0 * 1.41f64.log10()).abs() < 0.01); assert_eq!(only(8, 3), f64::NEG_INFINITY); assert_eq!(default_channel_weights(12), vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.41, 1.41, 1.0, 1.0, 1.0, 1.0]); @@ -864,14 +868,14 @@ mod tests { assert_eq!((m.sample_rate(), m.channels()), (f64::from(crate::FALLBACK_SAMPLE_RATE), 1)); assert_eq!(LoudnessMeter::new(48_000.0, usize::MAX).channels(), crate::MAX_CHANNELS); let sr = 48_000.0; - let mut x = segments(1000.0, sr, &[(5.0, -23.0)]); + let mut x = segments(1000.0, sr, &[(2.0, -23.0)]); x[1000] = f32::NAN; x[2000] = f32::INFINITY; let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "I {}", m.integrated()); assert!(m.true_peak().is_finite() && m.momentary().is_finite()); // A NaN or negative weight leaves its channel out instead of poisoning the sum. - let x = segments(1000.0, sr, &[(5.0, -23.0)]); + let x = segments(1000.0, sr, &[(2.0, -23.0)]); let mut m = LoudnessMeter::new(sr, 3); m.set_channel_weights(&[1.0, f64::NAN, -2.0]); m.process(&[&x, &x, &x]); @@ -883,12 +887,12 @@ mod tests { #[test] fn reset_clears_everything() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(5.0, -20.0)]); + let x = segments(1000.0, sr, &[(2.0, -20.0)]); let mut m = stereo_measure(&x, sr); m.reset(); assert_eq!(m.integrated(), f64::NEG_INFINITY); assert_eq!(m.true_peak(), 0.0); - let x = segments(1000.0, sr, &[(5.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); m.process(&[&x, &x]); assert!((m.integrated() + 30.0).abs() < 0.1); } @@ -942,7 +946,7 @@ mod tests { assert_eq!(normalize_gain_db_peak_limited(-30.0, -23.0, -10.0, -1.0), 7.0); // Applying the gain lands on target. let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -31.3)]); + let x = segments(1000.0, sr, &[(4.0, -31.3)]); let m = stereo_measure(&x, sr); let g = 10f64.powf(normalize_gain_db(m.integrated(), -16.0) / 20.0) as f32; let y: Vec = x.iter().map(|v| v * g).collect(); diff --git a/crates/audio-dsp/src/resample.rs b/crates/audio-dsp/src/resample.rs index 150eba11cc..12b5664706 100644 --- a/crates/audio-dsp/src/resample.rs +++ b/crates/audio-dsp/src/resample.rs @@ -418,13 +418,16 @@ mod tests { /// returns `MAX_RESAMPLE_BLOCK` frames. #[test] fn source_held_and_block_length_are_bounded() { + // At this ratio a pull holds about 42 output frames' worth of source, so 64 frames take two pulls; each output + // frame pulls 1,536 source frames of 64 channels, so nightly runs a longer block. + let frames = if craft_testkit::hostile::divisor() == 1 { 1_024 } else { 64 }; let mut r = StreamResampler::new(1_536_000, 1_000); let mut widest = 0; - let out = r.process(0, 1_024, |_, frames| { + let out = r.process(0, frames, |_, frames| { widest = widest.max(frames); vec![vec![0.5; frames]; 64] }); - assert_eq!((out.len(), out[0].len()), (64, 1_024)); + assert_eq!((out.len(), out[0].len()), (64, frames)); assert!(widest <= MAX_RESAMPLE_HELD / 64, "{widest}"); assert!(r.held.iter().map(Vec::len).sum::() <= MAX_RESAMPLE_HELD); let mut r = StreamResampler::new(48_000, 48_000); diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index 56416ef875..d117ecba3f 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -454,11 +454,11 @@ mod tests { #[test] fn pure_delay_exact_both_signs() { let sr = 48_000; - let s = speechy(sr as f64, 12.0, 1); - for delay in [0i64, 1, 7, 12_345, 96_001, -4_321, -50_000] { + let s = speechy(sr as f64, 6.0, 1); + for delay in [0i64, 1, 7, 12_345, -4_321, -50_000] { // b = s shifted: b[n] = s[n + delay] let b: Vec = - (0..400_000i64).map(|n| if n + delay >= 0 && ((n + delay) as usize) < s.len() { s[(n + delay) as usize] } else { 0.0 }).collect(); + (0..200_000i64).map(|n| if n + delay >= 0 && ((n + delay) as usize) < s.len() { s[(n + delay) as usize] } else { 0.0 }).collect(); let r = find_offset(&s, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.lag, delay, "{r:?}"); assert!(r.reliable(), "{r:?}"); @@ -471,8 +471,8 @@ mod tests { #[test] fn multi_mic_offsets_within_one_sample() { let sr = 48_000u32; - let src = speechy(sr as f64, 30.0, 7); - let len = 30 * sr as usize; + let src = speechy(sr as f64, 12.0, 7); + let len = 12 * sr as usize; // mic k records src delayed by d_k: mic_k[n] = src[n - d_k] let cases: [(f64, f32, Option, f32); 4] = [(0.0, 1.0, None, 40.0), (2_345.0, 0.1, None, 25.0), (-31_337.4, 3.0, Some(0.3), 10.0), (150_000.6, 0.5, None, 3.0)]; @@ -551,7 +551,7 @@ mod tests { #[test] fn max_lag_limits_the_search() { let sr = 48_000; - let s = speechy(sr as f64, 10.0, 5); + let s = speechy(sr as f64, 5.0, 5); let b: Vec = s[48_000..].to_vec(); let r = find_offset(&s, &b, sr, &SyncOptions { max_lag: Some(60_000), ..Default::default() }).unwrap(); assert_eq!(r.lag, 48_000); @@ -560,7 +560,7 @@ mod tests { // Non-finite samples count as silence (also in the refinement's window search). let mut t = s.clone(); t[1_000] = f32::NAN; - t[300_000] = f32::INFINITY; + t[200_000] = f32::INFINITY; let r = find_offset(&t, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.lag, 48_000); assert!(r.confidence.is_finite() && r.lag_fine.is_finite(), "{r:?}"); @@ -586,15 +586,15 @@ mod tests { assert!(r.reliable(), "{r:?}"); } - /// A coarse budget that asks for more than [`MAX_DECIMATION`] still scales the coarse lag by - /// the factor applied: 2 × 9 M samples at 8 kHz with a 4,096-sample budget asks for 4,395. + /// A decimation factor asked for beyond [`MAX_DECIMATION`] still scales the coarse lag by the + /// factor applied. A sample rate of 2,048,001 Hz against a 500 Hz coarse rate asks for 4,097. #[test] fn a_coarse_factor_above_the_cap_still_finds_the_lag() { - let sr = 8_000; - let s = speechy(sr as f64, 2_300.0, 9); - let lag = 400_000usize; + let sr = 2_048_001; + let s = speechy(sr as f64, 0.8, 9); + let lag = 100_000usize; let b: Vec = s[lag..].to_vec(); - let opts = SyncOptions { max_coarse_samples: 4_096, ..Default::default() }; + let opts = SyncOptions { coarse_rate: 500, ..Default::default() }; let r = find_offset(&s, &b, sr, &opts).unwrap(); assert_eq!(r.lag, lag as i64, "{r:?}"); } @@ -623,11 +623,11 @@ mod tests { let sr = 48_000u32; let delay = 112_560i64; for seed in [1, 3, 7] { - let src = speechy(sr as f64, 24.0, seed); + let src = speechy(sr as f64, 10.0, seed); let scratch = scratch_track(&src, sr, 100 + seed); for sign in [1.0f32, -1.0] { // b[n] = scratch[n + delay] - let b: Vec = (0..16 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect(); + let b: Vec = (0..7 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect(); let r = find_offset(&src, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.inverted, sign < 0.0, "seed {seed}, sign {sign}: {r:?}"); // the filters delay the scratch track by a few samples diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index ae633a05d7..7981f3a013 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -1,4 +1,5 @@ [package] +autotests = false name = "craft-audio" description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus decoder and encoder, Vorbis encoder, MP1/MP2 decoders." version.workspace = true @@ -104,66 +105,6 @@ craft-media = { workspace = true, features = ["vmd"] } proptest = { workspace = true } serde_json = { workspace = true } -[[test]] -name = "audio" -required-features = ["decode", "lossless-encode", "peaks"] - -[[test]] -name = "vmd" -required-features = ["vmd-decode"] - -[[test]] -name = "codecs" -required-features = ["decode", "encode"] - -[[test]] -name = "mp2_encoder_oracle" -required-features = ["mpa-encode"] - -[[test]] -name = "adpcm_oracle" -required-features = ["adpcm"] - -[[test]] -name = "flac_decode" -required-features = ["flac-decode", "flac-encode"] - -[[test]] -name = "vorbis_decode_oracle" -required-features = ["vorbis-decode", "vorbis-encode", "decode"] - -[[test]] -name = "vorbis_decode_hostile" -required-features = ["vorbis-decode", "vorbis-encode"] - -[[test]] -name = "vorbis_decode_synthetic" -required-features = ["vorbis-decode"] - -[[test]] -name = "gsm_oracle" -required-features = ["gsm"] - -[[test]] -name = "qoa_oracle" -required-features = ["qoa"] - -[[test]] -name = "dsd_oracle" -required-features = ["dsd"] - -[[test]] -name = "g722_oracle" -required-features = ["g722"] - -[[test]] -name = "g726_oracle" -required-features = ["g726"] - -[[test]] -name = "sbc_oracle" -required-features = ["sbc"] - [[example]] name = "info" required-features = ["decode"] @@ -179,11 +120,3 @@ required-features = ["decode"] [[example]] name = "encode" required-features = ["lossless-encode", "aac-encode"] - -[[test]] -name = "dsd_bounds" -required-features = ["dsd"] - -[[test]] -name = "dsd_metadata" -required-features = ["dsd"] diff --git a/crates/audio/src/aac/config.rs b/crates/audio/src/aac/config.rs index 3d12b03438..ed7ecf2a59 100644 --- a/crates/audio/src/aac/config.rs +++ b/crates/audio/src/aac/config.rs @@ -545,25 +545,6 @@ mod tests { } } - #[test] - fn an_index_with_no_rate_does_not_panic_and_is_refused() { - for sf_index in 13..=15 { - let asc = AudioSpecificConfig::lc(sf_index, 2); - assert_eq!(asc.sample_rate, 0); - #[cfg(feature = "aac-decode")] - assert!(crate::aac::Decoder::from_config(asc).is_err()); - } - } - - #[test] - fn configs_that_would_not_parse_back_are_not_written() { - assert!(AudioSpecificConfig::lc(4, 0).to_bytes().is_err()); - assert!(AudioSpecificConfig::lc(13, 2).to_bytes().is_err(), "a sampling rate of 0"); - let pce = ProgramConfig { front: vec![(true, 0)], ..Default::default() }; - let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) }; - assert_eq!(AudioSpecificConfig::parse(&asc.to_bytes().unwrap()).unwrap(), asc); - } - #[test] fn adts_config_preserves_prefix_and_frame_limits() { let config = AdtsConfig::from_asc_prefix(&[0x12, 0x10]).unwrap(); @@ -573,75 +554,6 @@ mod tests { assert!(matches!(AdtsConfig::from_asc_prefix(&[0x2a, 0x10]), Err(AdtsConfigError::Unsupported { object_type: 5, .. }))); } - #[test] - fn adts_headers_refuse_fields_they_cannot_hold() { - for (object_type, sf_index, channel_config) in [(0, 4, 2), (5, 4, 2), (29, 4, 2), (2, 13, 2), (2, 15, 2), (2, 4, 8), (2, 4, 11), (2, 4, 12)] { - assert!(AdtsHeader::write(object_type, sf_index, channel_config, 100, 0x7FF).is_err(), "{object_type} {sf_index} {channel_config}"); - } - for object_type in 1..=4 { - let h = AdtsHeader::parse(&AdtsHeader::write(object_type, 12, 7, 100, 0x7FF).unwrap()).unwrap(); - assert_eq!((h.object_type, h.sf_index, h.channel_config, h.frame_length), (object_type, 12, 7, 107)); - } - } - - #[test] - fn program_configs_refuse_more_elements_than_their_counts_hold() { - let fits = ProgramConfig { front: vec![(false, 0); 15], lfe: vec![0; 3], assoc_data: vec![0; 7], ..Default::default() }; - assert!(fits.write(&mut BitWriter::new()).is_ok()); - for pce in [ - ProgramConfig { front: vec![(false, 0); 16], ..Default::default() }, - ProgramConfig { side: vec![(false, 0); 16], ..Default::default() }, - ProgramConfig { back: vec![(false, 0); 16], ..Default::default() }, - ProgramConfig { lfe: vec![0; 4], ..Default::default() }, - ProgramConfig { assoc_data: vec![0; 8], ..Default::default() }, - ProgramConfig { cc: vec![(false, 0); 16], ..Default::default() }, - ] { - assert!(pce.write(&mut BitWriter::new()).is_err(), "{pce:?}"); - let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) }; - assert!(asc.to_bytes().is_err()); - } - } - - #[test] - fn adts_headers_refuse_frames_too_long_for_their_length() { - let longest = AdtsHeader::write(2, 4, 2, 0x1FFF - 7, 0x7FF).unwrap(); - assert_eq!(AdtsHeader::parse(&longest).unwrap().frame_length, 0x1FFF); - for payload in [0x1FFF - 6, 0x1FFF, usize::MAX] { - assert!(AdtsHeader::write(2, 4, 2, payload, 0x7FF).is_err(), "{payload}"); - } - } - - /// An explicit sampling rate of 0 is not a rate. - #[test] - fn a_zero_explicit_rate_is_refused() { - let mut bw = BitWriter::new(); - bw.write_bits(2, 5); - bw.write_bits(15, 4); - bw.write_bits(0, 24); - bw.write_bits(2, 4); - bw.write_bits(0, 3); - assert!(AudioSpecificConfig::parse(&bw.finish()).is_err()); - } - - #[test] - fn asc_roundtrip() { - let a = AudioSpecificConfig::lc(4, 2); - let b = a.to_bytes().unwrap(); - assert_eq!(b, vec![0x12, 0x10]); - assert_eq!(AudioSpecificConfig::parse(&b).unwrap(), a); - // 48 kHz 5.1 - let a = AudioSpecificConfig::lc(3, 6); - assert_eq!(AudioSpecificConfig::parse(&a.to_bytes().unwrap()).unwrap().channels(), 6); - } - - #[test] - fn amd4_channel_configurations() { - // 6.1 and 7.1 back (#922); 22.2 and 7.1 with heights stay unsupported - let channels = |c| AudioSpecificConfig::parse(&AudioSpecificConfig::lc(3, c).to_bytes().unwrap()).map(|a| a.channels()).ok(); - assert_eq!([7, 11, 12].map(channels), [Some(8), Some(7), Some(8)]); - assert_eq!([13, 14].map(config_layout), [None, None]); - } - #[test] fn asc_with_pce() { let pce = ProgramConfig { @@ -658,33 +570,4 @@ mod tests { assert_eq!(p.channels(), 7); assert_eq!(p, a); } - - #[test] - fn he_aac_asc_parses_core() { - // AOT 5, 24 kHz core, stereo, ext 48 kHz, core AOT 2 - let mut bw = BitWriter::new(); - bw.write_bits(5, 5); - bw.write_bits(6, 4); - bw.write_bits(2, 4); - bw.write_bits(3, 4); - bw.write_bits(2, 5); - bw.write_bits(0, 3); - let a = AudioSpecificConfig::parse(&bw.finish()).unwrap(); - assert!(a.sbr); - assert_eq!(a.sample_rate, 24000); - assert_eq!(a.extension_sample_rate, Some(48000)); - } - - #[test] - fn adts_roundtrip() { - let h = AdtsHeader::write(2, 4, 2, 100, 0x7FF).unwrap(); - let mut frame = h.to_vec(); - frame.extend(std::iter::repeat_n(0u8, 100)); - let p = AdtsHeader::parse(&frame).unwrap(); - assert_eq!(p.frame_length, 107); - assert_eq!((p.object_type, p.sf_index, p.channel_config), (2, 4, 2)); - let frames = split_adts(&frame).unwrap(); - assert_eq!(frames.len(), 1); - assert_eq!(frames[0].1.len(), 100); - } } diff --git a/crates/audio/src/aac/decoder.rs b/crates/audio/src/aac/decoder.rs index 825ebb23a2..a66db6d4ee 100644 --- a/crates/audio/src/aac/decoder.rs +++ b/crates/audio/src/aac/decoder.rs @@ -682,25 +682,6 @@ mod tests { use super::*; use craft_media::bitstream::BitWriter; - /// Implicitly signalled HE-AAC (an AAC-LC config) is recognised from the SBR fill element. - #[test] - fn sbr_fill_element_marks_implicit_he_aac() { - // AAC-LC, 22.05 kHz, stereo - let mut dec = Decoder::new(&[0x13, 0x90]).unwrap(); - assert!(!dec.sbr()); - // ID_FIL, count 1, extension_type EXT_SBR_DATA (+ 4 bits of payload), ID_END - let _ = dec.decode(&[0b1100_0011, 0b1010_0001, 0b1100_0000]); - assert!(dec.sbr()); - // other fill payloads (EXT_FILL) don't - let mut dec = Decoder::new(&[0x13, 0x90]).unwrap(); - let _ = dec.decode(&[0b1100_0010, 0b0000_0001, 0b1100_0000]); - assert!(!dec.sbr()); - // explicit signalling: AOT 5, core 22.05 kHz, stereo, extension 44.1 kHz, core AOT 2 - let dec = Decoder::new(&[0x2B, 0x92, 0x08, 0x00]).unwrap(); - assert!(dec.sbr()); - assert_eq!(dec.sample_rate(), 22_050); - } - /// With SBR on, an access unit decodes to 2048 samples, and over a silent core the high band /// its SBR fill element describes is there; with SBR off, the core alone (silence). #[test] @@ -779,7 +760,6 @@ mod tests { bw.write_bits(ID_END, 3); bw.finish() } - /// An access unit whose elements are all empty: `elements` are (id, tag), then ID_END. fn silent_au(pce: Option<&ProgramConfig>, elements: &[(u32, u32)]) -> Vec { let mut bw = BitWriter::new(); @@ -812,35 +792,6 @@ mod tests { assert_eq!(dec.find_slot(ElementType::Cpe, 0, &[true, true, false]), Ok(2)); } - #[test] - fn program_configs_place_elements_by_tag() { - let pce = ProgramConfig { front: vec![(true, 3), (true, 5)], ..Default::default() }; - let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) }; - let dec = Decoder::from_config(asc).unwrap(); - assert_eq!(dec.find_slot(ElementType::Cpe, 5, &[false, false]), Ok(1)); - } - - /// A program config lists its elements: one it does not list has no place. - #[test] - fn program_configs_refuse_unlisted_tags() { - let pce = ProgramConfig { front: vec![(true, 3), (true, 5)], ..Default::default() }; - let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) }; - let dec = Decoder::from_config(asc).unwrap(); - assert!(dec.find_slot(ElementType::Cpe, 9, &[false, false]).is_err()); - assert!(dec.find_slot(ElementType::Sce, 3, &[false, false]).is_err()); - } - - /// Some encoders code 5.1's LFE as an SCE, as ffmpeg allows. Nothing else changes type: an LFE - /// is not written to the centre channel. - #[test] - fn indexed_configurations_refuse_elements_of_another_type() { - let dec = Decoder::from_config(AudioSpecificConfig::lc(4, 6)).unwrap(); - // SCE, CPE, CPE, LFE - assert_eq!(dec.find_slot(ElementType::Sce, 1, &[true, false, false, false]), Ok(3)); - assert!(dec.find_slot(ElementType::Lfe, 1, &[false, false, false, true]).is_err()); - assert!(dec.find_slot(ElementType::Cpe, 2, &[false, true, true, false]).is_err()); - } - /// A PCE in an access unit that then fails leaves the layout as it was. #[test] fn a_damaged_in_band_pce_does_not_change_the_layout() { @@ -873,15 +824,6 @@ mod tests { assert_eq!((dec.channels[0].prev_shape, dec.noise_state), (WindowShape::Kbd, noise)); } - #[test] - fn a_reset_restarts_the_noise_generator() { - let mut dec = Decoder::from_config(AudioSpecificConfig::lc(4, 1)).unwrap(); - let first = dec.next_random(); - dec.next_random(); - dec.reset(); - assert_eq!(dec.next_random(), first); - } - #[test] fn non_finite_spectra_do_not_reach_the_output_or_the_overlap() { let mut state = ChannelState { overlap: vec![0.0; 1024], prev_shape: WindowShape::Sine }; diff --git a/crates/audio/src/aac/encoder/mod.rs b/crates/audio/src/aac/encoder/mod.rs index c641b790b8..343e2e4c04 100644 --- a/crates/audio/src/aac/encoder/mod.rs +++ b/crates/audio/src/aac/encoder/mod.rs @@ -958,17 +958,6 @@ mod tests { units } - #[test] - fn cbr_bitrate_limits_use_the_exact_bits_per_frame() { - // 288000 b/s at 48 kHz is exactly 6144 bits per frame; one more cannot fit a mono frame. - assert!(Encoder::new(EncoderConfig::cbr(48_000, 1, 288_000)).is_ok()); - assert!(Encoder::new(EncoderConfig::cbr(48_000, 1, 288_001)).is_err()); - // 4500 b/s at 96 kHz is exactly 48 bits per frame, the size of a silent mono frame. - assert!(Encoder::new(EncoderConfig::cbr(96_000, 1, 4_500)).is_ok()); - assert!(Encoder::new(EncoderConfig::cbr(96_000, 1, 4_499)).is_err()); - assert!(Encoder::new(EncoderConfig::cbr(96_000, 2, 2_000)).is_err()); - } - #[test] fn cbr_access_units_fit_the_decoder_buffer() { let sil = vec![0f32; 48_000]; @@ -1000,17 +989,6 @@ mod tests { } } - #[test] - fn maximum_rate_frames_are_filled_to_the_limit() { - let sil = vec![0f32; 48_000]; - for bandwidth in [None, Some(1000)] { - let units = encode_all(EncoderConfig::cbr(48_000, 1, 288_000).with_bandwidth(bandwidth), &sil); - for u in &units[..units.len() - 1] { - assert_eq!(u.len(), 768, "bandwidth {bandwidth:?}"); - } - } - } - #[test] fn cbr_fill_never_spends_more_than_the_reservoir_holds() { // Encode frame by frame, as `flush` does, so the bits each frame may spend are known: the @@ -1043,31 +1021,6 @@ mod tests { } } - #[test] - fn fill_never_passes_the_request() { - for bits in 0..3000u64 { - let mut bw = BitWriter::new(); - let n = write_fill(&mut bw, bits); - assert_eq!(n, bw.bit_len() as u64); - assert!(n <= bits && n + 6 >= bits, "asked {bits}, wrote {n}"); - } - } - - #[test] - fn vbr_quality_must_be_a_number() { - assert!(Encoder::new(EncoderConfig::vbr(48_000, 2, f32::NAN)).is_err()); - // Infinities and other out-of-range values are clamped: they encode exactly as the nearest - // end of the range, within the frame limit. - let nz = noise(48_000); - for (q, end) in [(f32::INFINITY, 6.0), (f32::NEG_INFINITY, 0.5), (100.0, 6.0), (-3.0, 0.5)] { - let units = encode_all(EncoderConfig::vbr(48_000, 8, q).with_adts(true), &nz); - assert!(units == encode_all(EncoderConfig::vbr(48_000, 8, end).with_adts(true), &nz), "quality {q}"); - for u in &units { - assert!(u.len() <= 6144 + 7 && u.starts_with(&[0xFF]), "quality {q}: {}-byte unit", u.len()); - } - } - } - #[test] fn one_long_encode_call_buffers_one_frame_at_a_time() { let input = noise(44_100 * 2); diff --git a/crates/audio/src/aac/huffman.rs b/crates/audio/src/aac/huffman.rs index 0c29673e70..785fe39e47 100644 --- a/crates/audio/src/aac/huffman.rs +++ b/crates/audio/src/aac/huffman.rs @@ -274,33 +274,6 @@ pub fn write_spectral(bw: &mut BitWriter, cb: u8, vals: &[i32]) { mod tests { use super::*; - fn check_complete(codes: &[(u32, u8)]) { - // Kraft sum exactly one and prefix-free. - let max = codes.iter().map(|c| c.1).max().unwrap() as u32; - let mut kraft = 0u64; - for &(_, l) in codes { - kraft += 1u64 << (max - l as u32); - } - assert_eq!(kraft, 1u64 << max); - for (i, &(ci, li)) in codes.iter().enumerate() { - for (j, &(cj, lj)) in codes.iter().enumerate() { - if i != j && li <= lj { - assert_ne!(cj >> (lj - li), ci, "codeword {i} is a prefix of {j}"); - } - } - } - } - - #[test] - fn codebooks_are_complete_prefix_codes() { - check_complete(&SCALEFACTOR); - assert_eq!(SCALEFACTOR[60], (0, 1)); - for b in &BOOKS { - assert_eq!(b.codes.len() as u32, b.modulo.pow(b.dim as u32)); - check_complete(b.codes); - } - } - /// Every codeword, followed by arbitrary bits, decodes to its own symbol and length. #[test] fn lut_decodes_every_codeword() { @@ -322,64 +295,6 @@ mod tests { } } - /// A codeword cut off by the end of the data is `Eof`, also at an unaligned position. - #[test] - fn truncated_codeword_is_eof() { - for (i, lut) in luts().iter().enumerate() { - let codes: &[(u32, u8)] = if i == 0 { &SCALEFACTOR } else { BOOKS[i - 1].codes }; - let &(code, len) = codes.iter().max_by_key(|c| c.1).unwrap(); - for lead in 0..8u32 { - let mut bw = BitWriter::new(); - bw.write_bits(0, lead); - bw.write_bits(code, len as u32); - let total = lead as usize + len as usize; - let data = bw.finish(); - // drop the last byte if that cuts the codeword, else the codeword is whole - let short = &data[..data.len() - 1]; - let mut br = BitReader::new(short); - br.skip(lead as usize).unwrap(); - let r = lut.decode(&mut br); - if short.len() * 8 < total { - assert!(matches!(r, Err(Error::Eof)), "book {i} lead {lead}"); - } else { - assert!(r.is_ok()); - } - } - } - } - - #[test] - fn spectral_roundtrip_every_book() { - for cb in 1..=11u8 { - let b = book(cb); - let lim = if cb == 11 { 8191 } else { b.lav as i32 }; - let mut vals = Vec::new(); - let mut seed = 12345u32; - for _ in 0..400 { - seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); - let r = (seed >> 8) as i32; - let v = if cb == 11 && r % 3 == 0 { r % (lim + 1) } else { r % (b.lav.min(16) as i32 + 1) }; - let v = v.min(lim); - vals.push(if b.signed || r & 1 == 0 { v } else { -v }); - } - if b.signed { - for v in vals.iter_mut() { - *v = (*v).clamp(-(b.lav as i32), b.lav as i32); - } - } - let mut bw = BitWriter::new(); - write_spectral(&mut bw, cb, &vals); - assert_eq!(bw.bit_len() as u32, count_bits(cb, &vals)); - let data = bw.finish(); - let mut br = BitReader::new(&data); - let mut out = vec![0i32; vals.len()]; - for c in out.chunks_mut(b.dim) { - decode_spectral(&mut br, cb, c).unwrap(); - } - assert_eq!(out, vals, "codebook {cb}"); - } - } - #[test] fn pair_count_matches_single_count() { let mut seed = 99u32; @@ -398,17 +313,4 @@ mod tests { } } } - - #[test] - fn scalefactor_roundtrip() { - let mut bw = BitWriter::new(); - for d in -60..=60 { - write_sf(&mut bw, d); - } - let data = bw.finish(); - let mut br = BitReader::new(&data); - for d in -60..=60 { - assert_eq!(decode_sf(&mut br).unwrap(), d); - } - } } diff --git a/crates/audio/src/aac/ics.rs b/crates/audio/src/aac/ics.rs index f50b8929ca..0422fc3cf8 100644 --- a/crates/audio/src/aac/ics.rs +++ b/crates/audio/src/aac/ics.rs @@ -127,25 +127,3 @@ impl IcsInfo { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn grouping_roundtrip() { - let info = IcsInfo { - window_sequence: WindowSequence::EightShort, - window_shape: WindowShape::Kbd, - max_sfb: 12, - num_groups: 3, - group_len: [3, 1, 4, 0, 0, 0, 0, 0], - }; - let mut bw = BitWriter::new(); - info.write(&mut bw); - let d = bw.finish(); - let p = IcsInfo::parse(&mut BitReader::new(&d), 4).unwrap(); - assert_eq!(p, info); - assert_eq!(p.group_start(2), 4); - } -} diff --git a/crates/audio/src/aac/mdct.rs b/crates/audio/src/aac/mdct.rs index 4549cb7de7..dd653da293 100644 --- a/crates/audio/src/aac/mdct.rs +++ b/crates/audio/src/aac/mdct.rs @@ -192,13 +192,8 @@ impl Mdct { self.dct4(&u, out, &mut re, &mut im); } - /// Inverse MDCT (unscaled): `y[n] = Σ X[k] cos(π/M (n + ½ + M/2)(k + ½))`, `y` has length 2M. - #[cfg(test)] - pub fn inverse(&self, spec: &[f32], y: &mut [f32]) { - self.inverse_with(spec, y, &mut self.scratch()); - } - - /// [`Self::inverse`] with caller-provided working buffers from [`Self::scratch`]. + /// Inverse MDCT (unscaled): `y[n] = Σ X[k] cos(π/M (n + ½ + M/2)(k + ½))`, `y` has length 2M, + /// with caller-provided working buffers from [`Self::scratch`]. pub fn inverse_with(&self, spec: &[f32], y: &mut [f32], sc: &mut MdctScratch) { let m = self.m; let h = m / 2; @@ -301,66 +296,3 @@ pub fn window(shape: WindowShape, long: bool) -> &'static [f32] { }; &w[i] } - -#[cfg(test)] -mod tests { - use super::*; - - fn direct(x: &[f32]) -> Vec { - let m = x.len() / 2; - (0..m).map(|k| (0..2 * m).map(|n| x[n] as f64 * (PI / m as f64 * (n as f64 + 0.5 + m as f64 / 2.0) * (k as f64 + 0.5)).cos()).sum()).collect() - } - - #[test] - fn forward_matches_definition() { - for m in [128usize, 1024] { - let x: Vec = (0..2 * m).map(|i| ((i * 7919) % 101) as f32 / 50.0 - 1.0).collect(); - let mut out = vec![0f32; m]; - Mdct::new(m).forward(&x, &mut out); - let d = direct(&x); - for k in 0..m { - assert!((out[k] as f64 - d[k]).abs() < 1e-3 * (m as f64).sqrt(), "m={m} k={k} {} {}", out[k], d[k]); - } - } - } - - #[test] - fn inverse_matches_definition() { - let m = 128; - let spec: Vec = (0..m).map(|i| ((i * 31) % 17) as f32 - 8.0).collect(); - let mut y = vec![0f32; 2 * m]; - Mdct::new(m).inverse(&spec, &mut y); - for n in 0..2 * m { - let d: f64 = (0..m).map(|k| spec[k] as f64 * (PI / m as f64 * (n as f64 + 0.5 + m as f64 / 2.0) * (k as f64 + 0.5)).cos()).sum(); - assert!((y[n] as f64 - d).abs() < 1e-3, "n={n}"); - } - } - - #[test] - fn tdac_perfect_reconstruction() { - let m = 1024; - let t = Mdct::new(m); - for shape in [WindowShape::Sine, WindowShape::Kbd] { - let w = window(shape, true); - let win = |n: usize| if n < m { w[n] } else { w[2 * m - 1 - n] }; - let x: Vec = (0..4 * m).map(|i| ((i as f32) * 0.013).sin() + ((i * 13) % 7) as f32 * 0.05).collect(); - let mut out = vec![0f32; 4 * m]; - for f in 0..3 { - let seg: Vec = (0..2 * m).map(|n| x[f * m + n] * win(n)).collect(); - let mut spec = vec![0f32; m]; - t.forward(&seg, &mut spec); - for v in spec.iter_mut() { - *v *= 2.0; - } - let mut y = vec![0f32; 2 * m]; - t.inverse(&spec, &mut y); - for n in 0..2 * m { - out[f * m + n] += y[n] * win(n) / m as f32; - } - } - for n in m..3 * m { - assert!((out[n] - x[n]).abs() < 1e-4, "{shape:?} n={n} {} {}", out[n], x[n]); - } - } - } -} diff --git a/crates/audio/src/aac/sbr/mod.rs b/crates/audio/src/aac/sbr/mod.rs index 752cd03a0b..d3c18b0e3a 100644 --- a/crates/audio/src/aac/sbr/mod.rs +++ b/crates/audio/src/aac/sbr/mod.rs @@ -493,7 +493,8 @@ mod tests { }; let mut e = Element::new(1, RATE); let mut pair = Element::new(2, RATE); - for i in 0..600 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the rounds. + for i in 0..600usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut data = good.clone(); for _ in 0..1 + next() % 6 { let bit = next() as usize % (8 * data.len()); diff --git a/crates/audio/src/aac/tables.rs b/crates/audio/src/aac/tables.rs index 87fb55d007..3d2aa1da34 100644 --- a/crates/audio/src/aac/tables.rs +++ b/crates/audio/src/aac/tables.rs @@ -137,29 +137,3 @@ pub fn sf_gain(sf: i32) -> f32 { fn sf_gain_exact(sf: i32) -> f32 { (0.25 * (sf as f64 - 100.0)).exp2() as f32 } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn band_tables_are_monotonic_and_complete() { - for i in 0..13u8 { - let l = swb_offsets_long(i); - assert_eq!(*l.last().unwrap(), 1024); - assert!(l.windows(2).all(|w| w[0] < w[1] && (w[1] - w[0]) % 4 == 0)); - let s = swb_offsets_short(i); - assert_eq!(*s.last().unwrap(), 128); - assert!(s.windows(2).all(|w| w[0] < w[1] && (w[1] - w[0]) % 4 == 0)); - assert!(tns_max_bands(i, false) < l.len()); - assert!(tns_max_bands(i, true) < s.len()); - } - assert_eq!(swb_offsets_long(3).len() - 1, 49); - assert_eq!(swb_offsets_long(5).len() - 1, 51); - assert_eq!(swb_offsets_long(0).len() - 1, 41); - assert_eq!(swb_offsets_long(2).len() - 1, 47); - assert_eq!(swb_offsets_long(6).len() - 1, 47); - assert_eq!(swb_offsets_long(8).len() - 1, 43); - assert_eq!(swb_offsets_long(11).len() - 1, 40); - } -} diff --git a/crates/audio/src/aac/tns.rs b/crates/audio/src/aac/tns.rs index a538207c76..ef6303153f 100644 --- a/crates/audio/src/aac/tns.rs +++ b/crates/audio/src/aac/tns.rs @@ -271,43 +271,3 @@ pub fn levinson(r: &[f64], order: usize) -> (Vec, f64) { } (ks, r[0] / err.max(r[0] * 1e-9)) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::aac::ics::WindowSequence; - use crate::aac::mdct::WindowShape; - - #[test] - fn coef_quant_roundtrip() { - for res in [false, true] { - let n = if res { 8 } else { 4 }; - for c in -n..n { - let k = dequant_coef(c as i8, res); - assert_eq!(quant_coef(k, res), c as i8); - } - } - } - - #[test] - fn encoder_decoder_filters_are_inverse() { - let info = IcsInfo { window_sequence: WindowSequence::OnlyLong, window_shape: WindowShape::Sine, max_sfb: 49, ..Default::default() }; - let mut t = TnsData::default(); - t.windows[0].n_filt = 1; - t.windows[0].coef_res = true; - t.windows[0].filt[0] = TnsFilter { length: 40, order: 4, direction: true, coef_compress: false, coef: [3, -2, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0] }; - let orig: Vec = (0..1024).map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.1).collect(); - let mut s = orig.clone(); - apply_encoder(&mut s, &info, 4, &t); - assert_ne!(s, orig); - apply_decoder(&mut s, &info, 4, &t); - for i in 0..1024 { - assert!((s[i] - orig[i]).abs() < 1e-3); - } - let mut bw = BitWriter::new(); - t.write(&mut bw, &info); - assert_eq!(bw.bit_len() as u32, t.bit_count(&info)); - let d = bw.finish(); - assert_eq!(TnsData::parse(&mut BitReader::new(&d), &info).unwrap(), t); - } -} diff --git a/crates/audio/src/ac3/eac3.rs b/crates/audio/src/ac3/eac3.rs index 1b2ef19510..dde51b8c39 100644 --- a/crates/audio/src/ac3/eac3.rs +++ b/crates/audio/src/ac3/eac3.rs @@ -592,15 +592,6 @@ mod tests { } } - #[test] - fn default_band_structures() { - assert_eq!(DEFAULT_CPLBNDSTRC.iter().filter(|&&b| b).count(), 8); - assert!(DEFAULT_CPLBNDSTRC[8] && !DEFAULT_CPLBNDSTRC[9] && !DEFAULT_CPLBNDSTRC[12] && DEFAULT_CPLBNDSTRC[17]); - assert_eq!(DEFAULT_SPXBNDSTRC.iter().enumerate().filter(|(_, b)| **b).map(|(i, _)| i).collect::>(), vec![8, 10, 12, 14, 16]); - // every frame-based strategy sends new exponents in block 0 - assert!(FRAME_EXPSTR.iter().all(|s| s[0] != 0)); - } - #[test] fn spectral_extension_translation_and_scaling() { // begin at sub-band 2 (bin 49), end at 5 (bin 85), copy from sub-band 0 (bin 25): three diff --git a/crates/audio/src/ac3/encoder/tests.rs b/crates/audio/src/ac3/encoder/tests.rs index 3545f48caf..a60efb768b 100644 --- a/crates/audio/src/ac3/encoder/tests.rs +++ b/crates/audio/src/ac3/encoder/tests.rs @@ -1,69 +1,9 @@ use super::*; -#[test] -fn analysis_synthesis_reconstructs_overlap() { - let input: Vec = (0..1024).map(|n| (n as f32 * 0.071).sin() * 0.4).collect(); - let mut overlap = [0.0; 256]; - for offset in (0..768).step_by(256) { - let mut block = [0.0; 512]; - block.copy_from_slice(&input[offset..offset + 512]); - let coeffs = transform::analysis(&block, false); - let mut decoded = [0.0; 512]; - super::super::imdct(&coeffs, false, &mut decoded); - if offset > 0 { - for i in 0..256 { - assert!((2.0 * (decoded[i] + overlap[i]) - input[offset + i]).abs() < 1e-5); - } - } - overlap.copy_from_slice(&decoded[256..]); - } -} - fn config(codec: Codec, mode: CodingMode, lfe: bool) -> Config { Config { codec, sample_rate: 48_000, bitrate_kbps: 448, mode, lfe } } -#[test] -fn encode_tone_headers_crc_and_level() -> Result<(), Box> { - for codec in [Codec::Ac3, Codec::Eac3] { - for (mode, lfe) in [(CodingMode::Mono, false), (CodingMode::Stereo, false), (CodingMode::ThreeFrontTwoSurround, true)] { - let cfg = config(codec, mode, lfe); - let input: Vec> = (0..cfg.channels()) - .map(|ch| (0..3072).map(|n| (n as f32 * (if lfe && ch == 3 { 0.01 } else { 0.04 + ch as f32 * 0.015 })).sin() * 0.2).collect()) - .collect(); - let mut encoder = Encoder::new(cfg)?; - let mut packets = encoder.push(&input.iter().map(Vec::as_slice).collect::>())?; - let finish = encoder.finish()?; - packets.extend(finish.packets); - let mut decoder = super::super::Decoder::new(); - let mut decoded = vec![Vec::new(); cfg.channels()]; - for packet in &packets { - let header = super::super::parse_header(&packet.data)?; - assert_eq!(header.channels(), cfg.channels()); - assert_eq!(header.samples(), 1536); - assert_eq!(bitstream::crc(&packet.data[2..]), 0); - if codec == Codec::Ac3 { - let words = packet.data.len() / 2; - let split = (words / 2 + words / 8) * 2; - assert_eq!(bitstream::crc(&packet.data[2..split]), 0); - } - let frame = decoder.decode(&packet.data)?; - for (dst, src) in decoded.iter_mut().zip(frame.channels) { - dst.extend(src); - } - } - for ch in 0..cfg.channels() { - if lfe && ch == 3 { - continue; - } // The causal LFE low-pass intentionally changes phase. - let mse = input[ch].iter().zip(&decoded[ch][256..]).map(|(&a, &b)| (a - b).powi(2)).sum::() / input[ch].len() as f32; - assert!(mse < 0.0001, "{codec:?} {mode:?} ch{ch}: mse={mse}"); - } - } - } - Ok(()) -} - #[test] fn long_short_transitions_reconstruct_without_gain_or_phase_steps() { let mut seed = 23u32; @@ -113,81 +53,6 @@ fn lfe_lowpass_preserves_bass_and_rejects_full_bandwidth_content() { } } -#[test] -fn rates_modes_and_crc_boundaries() -> Result<(), Box> { - for codec in [Codec::Ac3, Codec::Eac3] { - for rate in [32000, 44100, 48000] { - for mode in [ - CodingMode::DualMono, - CodingMode::Mono, - CodingMode::Stereo, - CodingMode::ThreeFront, - CodingMode::StereoSurround, - CodingMode::ThreeFrontSurround, - CodingMode::StereoTwoSurround, - CodingMode::ThreeFrontTwoSurround, - ] { - for lfe in [false, true] { - let cfg = Config { sample_rate: rate, ..config(codec, mode, lfe) }; - let mut encoder = Encoder::new(cfg)?; - let planes = vec![vec![0.0; 1537]; cfg.channels()]; - let mut packets = encoder.push(&planes.iter().map(Vec::as_slice).collect::>())?; - let finish = encoder.finish()?; - packets.extend(finish.packets); - assert_eq!(packets.len(), 2); - assert_eq!(finish.padding_samples, 1279); - for packet in packets { - let h = super::super::parse_header(&packet.data)?; - assert_eq!(h.sample_rate, rate); - assert_eq!(h.acmod, mode as u8); - assert_eq!(h.lfeon, lfe); - assert_eq!(h.frame_bytes, packet.data.len()); - assert_eq!(bitstream::crc(&packet.data[2..]), 0); - let decoded = super::super::Decoder::new().decode(&packet.data)?; - assert!(decoded.channels.iter().flatten().all(|&v| v == 0.0)); - if codec == Codec::Ac3 { - let words = packet.data.len() / 2; - assert_eq!(bitstream::crc(&packet.data[2..(words / 2 + words / 8) * 2]), 0); - } - } - } - } - } - } - Ok(()) -} - -#[test] -fn input_validation_and_terminal_lifecycle() -> Result<(), Box> { - let cfg = config(Codec::Ac3, CodingMode::Stereo, false); - let mut encoder = Encoder::new(cfg)?; - assert!(encoder.push(&[&[0.0]]).is_err()); - assert!(encoder.push(&[&[0.0], &[]]).is_err()); - for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1.01, -1.01] { - assert!(encoder.push(&[&[value], &[0.0]]).is_err()); - } - assert_eq!(encoder.input_samples, 0); - assert!(encoder.push(&[&[], &[]])?.is_empty()); - let finish = encoder.finish()?; - assert!(finish.packets.is_empty()); - assert_eq!(finish.priming_samples, 0); - assert_eq!(finish.padding_samples, 0); - assert_eq!(encoder.push(&[&[], &[]]).err(), Some(Error::Finished)); - assert_eq!(encoder.finish().err(), Some(Error::Finished)); - // Force an internal impossible budget to exercise terminal handling without - // relying on a public configuration that new() should have rejected. - let mut failing = Encoder::new(cfg)?; - failing.config.bitrate_kbps = 1; - assert_eq!(failing.push(&[&[0.0; 1536], &[0.0; 1536]]).err(), Some(Error::BitBudget)); - assert_eq!(failing.push(&[&[], &[]]).err(), Some(Error::Finished)); - assert_eq!(failing.finish().err(), Some(Error::Finished)); - let mut overflow = Encoder::new(cfg)?; - overflow.input_samples = u64::MAX - 2000; - assert!(overflow.push(&[&[0.0; 1000], &[0.0; 1000]]).is_err()); - assert_eq!(overflow.input_samples, u64::MAX - 2000); - Ok(()) -} - #[test] fn chunk_boundaries_and_exact_trim_counts() -> Result<(), Box> { for codec in [Codec::Ac3, Codec::Eac3] { @@ -213,18 +78,6 @@ fn chunk_boundaries_and_exact_trim_counts() -> Result<(), Box Result<(), Box> { // Independently verified against a Dolby-hosted 48k/768k 7.1 sample's @@ -252,8 +105,14 @@ fn dec3_describes_dependent_rear_pair_and_aggregate_rate() -> Result<(), Box Result<(), Box> { - for rate in [32000, 44100, 48000] { - for bitrate in super::super::BITRATES { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th bit rate, from a different offset for + // each sample rate, so the rates together still reach every bit rate. + let step = craft_media_testkit::hostile::divisor(); + for (ri, rate) in [32000, 44100, 48000].into_iter().enumerate() { + for (bi, bitrate) in super::super::BITRATES.into_iter().enumerate() { + if !(bi + ri).is_multiple_of(step) { + continue; + } for mode in [CodingMode::Mono, CodingMode::ThreeFrontTwoSurround] { let cfg = Config { codec: Codec::Ac3, sample_rate: rate, bitrate_kbps: bitrate, mode, lfe: mode == CodingMode::ThreeFrontTwoSurround }; @@ -302,24 +161,6 @@ fn actual_decoder_positions_satisfy_all_three_ac3_bit_budgets() -> Result<(), Bo Ok(()) } -#[test] -fn lfe_final_nonzero_input_is_chunk_invariant() -> Result<(), Box> { - let cfg = config(Codec::Eac3, CodingMode::ThreeFrontTwoSurround, true); - let mut input = vec![vec![0.0; 1537]; 6]; - input[3][1536] = 0.75; - let mut one = Encoder::new(cfg)?; - let mut a = one.push(&input.iter().map(Vec::as_slice).collect::>())?; - a.extend(one.finish()?.packets); - let mut two = Encoder::new(cfg)?; - let mut b = Vec::new(); - for range in [0..1, 1..255, 255..1536, 1536..1537] { - b.extend(two.push(&input.iter().map(|p| &p[range.clone()]).collect::>())?); - } - b.extend(two.finish()?.packets); - assert_eq!(a.iter().map(|p| &p.data).collect::>(), b.iter().map(|p| &p.data).collect::>()); - Ok(()) -} - #[test] fn transient_adjacent_tone_refreshes_exponents_within_the_frame() -> Result<(), Box> { // Independent QC localized a previous shared-six-block exponent envelope's @@ -379,10 +220,3 @@ fn surround_compatibility_downmix_retains_correlated_signal_headroom() -> Result assert!(left.iter().all(|v| v.abs() < 1.05)); Ok(()) } - -#[test] -fn encoder_errors_convert_to_audio_errors() { - let bad = Config { codec: Codec::Ac3, sample_rate: 22_050, bitrate_kbps: 192, mode: CodingMode::Stereo, lfe: false }; - let made: crate::Result = Encoder::new(bad).map_err(Into::into); - assert!(matches!(made, Err(crate::AudioError::Encode(m)) if m.contains("sample rate"))); -} diff --git a/crates/audio/src/ac3/golden_frames.bin b/crates/audio/src/ac3/golden_frames.bin deleted file mode 100644 index 4f8a589a59..0000000000 Binary files a/crates/audio/src/ac3/golden_frames.bin and /dev/null differ diff --git a/crates/audio/src/ac3/program.rs b/crates/audio/src/ac3/program.rs index 89dacd53be..8fada2d62c 100644 --- a/crates/audio/src/ac3/program.rs +++ b/crates/audio/src/ac3/program.rs @@ -190,63 +190,6 @@ mod tests { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x93, ]; - #[test] - fn seven_one_rejects_valid_independent_prefix_before_audio_decode() -> Result<()> { - assert!(validate(&PRIMARY)?.1.is_none()); - let mut decoder = ProgrammeDecoder::new(ChannelLayout::SURROUND_7_1); - assert_eq!(decoder.decode(&PRIMARY).err(), Some(Error::Invalid("programme does not match the expected speaker layout"))); - assert!(decoder.topology.is_none()); - Ok(()) - } - - #[test] - fn validates_dependency_order_frame_bounds_and_crc() -> Result<()> { - let mut au = PRIMARY.to_vec(); - au.extend_from_slice(&DEPENDENT); - assert!(validate(&au)?.1.is_some()); - assert!(validate(&DEPENDENT).is_err()); - assert!(validate(&au[..63]).is_err()); - au.push(0); - assert!(validate(&au).is_err()); - au.pop(); - au[55] ^= 1; - assert!(validate(&au).is_err()); - let mut duplicate = PRIMARY.to_vec(); - duplicate.extend_from_slice(&PRIMARY); - assert!(validate(&duplicate).is_err()); - Ok(()) - } - - fn changed_dependent(bit: usize, width: usize, value: u16) -> Vec { - let mut frame = DEPENDENT; - for i in 0..width { - let at = bit + i; - let mask = 1 << (7 - at % 8); - frame[at / 8] = (frame[at / 8] & !mask) | if value & (1 << (width - 1 - i)) != 0 { mask } else { 0 }; - } - let crc = crc16(&frame[2..30]); - frame[30..].copy_from_slice(&crc.to_be_bytes()); - let mut au = PRIMARY.to_vec(); - au.extend_from_slice(&frame); - au - } - - #[test] - fn rejects_crc_valid_but_inconsistent_programme_descriptions() { - // Fields are normative bit offsets in the independent structural BSI fixture. - let wrong_map = changed_dependent(60, 16, 0x1800); - assert_eq!(validate(&wrong_map).err(), Some(Error::Unsupported("dependent channel map must be Ls Rs Lrs Rrs".into()))); - let missing_last_marker = changed_dependent(50, 1, 0); - assert_eq!(validate(&missing_last_marker).err(), Some(Error::Invalid("last dependent substream must signal compre"))); - let wrong_rate = changed_dependent(32, 2, 2); - assert_eq!(validate(&wrong_rate).err(), Some(Error::Invalid("dependent rate or block count differs from independent"))); - let short_frame = changed_dependent(34, 2, 0); - assert_eq!(validate(&short_frame).err(), Some(Error::Unsupported("programme decoder requires full-rate six-block E-AC-3 bsid 16".into()))); - let mut decoder = ProgrammeDecoder::new(ChannelLayout::SURROUND_7_1); - decoder.reset(); - assert_eq!(decoder.expected_layout, ChannelLayout::SURROUND_7_1); - } - #[cfg(feature = "eac3-encode")] #[test] fn explicit_map_overrides_dependent_acmod_speaker_order() -> std::result::Result<(), Box> { @@ -287,23 +230,4 @@ mod tests { assert!(matches!(result, Ok(Err(_))), "corrupt bit {bit}"); } } - - #[test] - fn dependent_replaces_downmix_and_labels_rears() -> Result<()> { - let primary = (0..6).map(|c| vec![c as f32; 1536]).collect(); - let dependent = (10..14).map(|c| vec![c as f32; 1536]).collect(); - let result = assemble_7_1(primary, dependent)?; - assert_eq!(result.iter().map(|c| c[0]).collect::>(), [0., 1., 2., 3., 12., 13., 10., 11.]); - assert_eq!(ChannelLayout::SURROUND_7_1.mask(), Some(0x63f)); - Ok(()) - } - - #[test] - fn incomplete_programme_never_produces_partial_channels() { - assert!(assemble_7_1(vec![vec![0.; 1536]; 6], vec![vec![0.; 1535]; 4]).is_err()); - let mut decoder = ProgrammeDecoder::new(ChannelLayout::SURROUND_7_1); - decoder.topology = Some((48_000, 7, true, true)); - assert!(decoder.decode(&[0; 8193]).is_err()); - assert!(decoder.topology.is_none()); - } } diff --git a/crates/audio/src/ac3/tables.rs b/crates/audio/src/ac3/tables.rs index 0128e89606..4c14e632af 100644 --- a/crates/audio/src/ac3/tables.rs +++ b/crates/audio/src/ac3/tables.rs @@ -48,24 +48,3 @@ pub(crate) const HTH: [[u16; 50]; 3] = [ 880, 864, 848, 832, 816, 800, 784, 768, 752, 752, 752, 768, 784, 816, 848, 960, 1040, 1136, 1184, 1120, 1088, 1104, 1248, ], ]; -/// Table 7.33 as printed (5 decimals), for checking the computed window. -#[cfg(test)] -#[allow(clippy::approx_constant)] -pub(crate) const WINDOW_TABLE: [f32; 256] = [ - 0.00014, 0.00024, 0.00037, 0.00051, 0.00067, 0.00086, 0.00107, 0.0013, 0.00157, 0.00187, 0.0022, 0.00256, 0.00297, 0.00341, 0.0039, 0.00443, - 0.00501, 0.00564, 0.00632, 0.00706, 0.00785, 0.00871, 0.00962, 0.01061, 0.01166, 0.01279, 0.01399, 0.01526, 0.01662, 0.01806, 0.01959, 0.02121, - 0.02292, 0.02472, 0.02662, 0.02863, 0.03073, 0.03294, 0.03527, 0.0377, 0.04025, 0.04292, 0.04571, 0.04862, 0.05165, 0.05481, 0.0581, 0.06153, - 0.06508, 0.06878, 0.07261, 0.07658, 0.08069, 0.08495, 0.08935, 0.09389, 0.09859, 0.10343, 0.10842, 0.11356, 0.11885, 0.12429, 0.12988, 0.13563, - 0.14152, 0.14757, 0.15376, 0.16011, 0.16661, 0.17325, 0.18005, 0.18699, 0.19407, 0.2013, 0.20867, 0.21618, 0.22382, 0.23161, 0.23952, 0.24757, - 0.25574, 0.26404, 0.27246, 0.281, 0.28965, 0.29841, 0.30729, 0.31626, 0.32533, 0.3345, 0.34376, 0.35311, 0.36253, 0.37204, 0.38161, 0.39126, - 0.40096, 0.41072, 0.42054, 0.4304, 0.4403, 0.45023, 0.4602, 0.47019, 0.4802, 0.49022, 0.50025, 0.51028, 0.52031, 0.53033, 0.54033, 0.55031, - 0.56026, 0.57019, 0.58007, 0.58991, 0.5997, 0.60944, 0.61912, 0.62873, 0.63827, 0.64774, 0.65713, 0.66643, 0.67564, 0.68476, 0.69377, 0.70269, - 0.7115, 0.72019, 0.72877, 0.73723, 0.74557, 0.75378, 0.76186, 0.76981, 0.77762, 0.7853, 0.79283, 0.80022, 0.80747, 0.81457, 0.82151, 0.82831, - 0.83496, 0.84145, 0.84779, 0.85398, 0.86001, 0.86588, 0.8716, 0.87716, 0.88257, 0.88782, 0.89291, 0.89785, 0.90264, 0.90728, 0.91176, 0.9161, - 0.92028, 0.92432, 0.92822, 0.93197, 0.93558, 0.93906, 0.9424, 0.9456, 0.94867, 0.95162, 0.95444, 0.95713, 0.95971, 0.96217, 0.96451, 0.96674, - 0.96887, 0.97089, 0.97281, 0.97463, 0.97635, 0.97799, 0.97953, 0.98099, 0.98236, 0.98366, 0.98488, 0.98602, 0.9871, 0.98811, 0.98905, 0.98994, - 0.99076, 0.99153, 0.99225, 0.99291, 0.99353, 0.99411, 0.99464, 0.99513, 0.99558, 0.996, 0.99639, 0.99674, 0.99706, 0.99736, 0.99763, 0.99788, - 0.99811, 0.99831, 0.9985, 0.99867, 0.99882, 0.99895, 0.99908, 0.99919, 0.99929, 0.99938, 0.99946, 0.99953, 0.99959, 0.99965, 0.99969, 0.99974, - 0.99978, 0.99981, 0.99984, 0.99986, 0.99988, 0.9999, 0.99992, 0.99993, 0.99994, 0.99995, 0.99996, 0.99997, 0.99998, 0.99998, 0.99998, 0.99999, - 0.99999, 0.99999, 0.99999, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -]; diff --git a/crates/audio/src/ac3/tests.rs b/crates/audio/src/ac3/tests.rs index a9a83c10a8..6a9babd7b3 100644 --- a/crates/audio/src/ac3/tests.rs +++ b/crates/audio/src/ac3/tests.rs @@ -1,77 +1,5 @@ use super::*; -#[test] -fn computed_window_matches_table_7_33() { - let w = window(); - for (n, (&a, &b)) in w.iter().zip(tables::WINDOW_TABLE.iter()).enumerate() { - assert!((a - b).abs() <= 6e-6, "w[{n}] = {a}, table {b}"); - } - // princen-bradley: w[n]² + w[255-n]²... (the second half mirrors): w[n]² + w[511-n]² = 1 - for n in 0..256 { - let m = w[255 - n]; - assert!((w[n] * w[n] + m * m - 1.0).abs() < 1e-5); - } -} - -#[test] -fn tables_are_consistent() { - // masktab maps every bin of a band to that band - for b in 0..50 { - for bin in tables::BNDTAB[b] as usize..(tables::BNDTAB[b] + tables::BNDSZ[b]) as usize { - if bin < 253 { - assert_eq!(tables::MASKTAB[bin] as usize, b, "bin {bin}"); - } - } - } - assert_eq!(tables::BNDTAB[49] as usize + tables::BNDSZ[49] as usize, 253); - // latab is non-increasing from 64 to 0 - assert_eq!(tables::LATAB[0], 64); - assert!(tables::LATAB.windows(2).all(|w| w[0] >= w[1])); - assert!(tables::BAPTAB.windows(2).all(|w| w[0] <= w[1])); - assert_eq!((tables::BAPTAB[0], tables::BAPTAB[63]), (0, 15)); -} - -#[test] -fn inverse_fft_matches_the_definition() { - for n in [64usize, 128] { - let re0: Vec = (0..n).map(|i| ((i * 7 + 3) % 11) as f32 - 5.0).collect(); - let im0: Vec = (0..n).map(|i| ((i * 5 + 1) % 13) as f32 - 6.0).collect(); - let (mut re, mut im) = (re0.clone(), im0.clone()); - ifft(&mut re, &mut im); - for t in 0..n { - let (mut sr, mut si) = (0f64, 0f64); - for k in 0..n { - let a = 2.0 * std::f64::consts::PI * (k * t) as f64 / n as f64; - sr += re0[k] as f64 * a.cos() - im0[k] as f64 * a.sin(); - si += re0[k] as f64 * a.sin() + im0[k] as f64 * a.cos(); - } - assert!((sr - re[t] as f64).abs() < 1e-3 && (si - im[t] as f64).abs() < 1e-3, "n {n} t {t}"); - } - } -} - -#[test] -fn headers_and_gains() { - // 48 kHz, 448 kb/s, 3/2 + LFE: bsid 8, bsmod 0, acmod 7 (cmixlev, surmixlev), lfeon - let b = [0x0B, 0x77, 0, 0, 30, 8 << 3, 0b1110_0001, 0b0100_0000]; - let h = parse_header(&b).unwrap(); - assert_eq!((h.sample_rate, h.bitrate_kbps, h.frame_bytes, h.acmod, h.lfeon, h.channels()), (48_000, 448, 1792, 7, true, 6)); - assert_eq!(parse_header(&[0x0B, 0x77, 0, 0, 0, 17 << 3, 0, 0]), Err(Error::Unsupported("bsid 17".into()))); - assert_eq!(dynrng_gain(0), 1.0); - assert!((dynrng_gain(0b1110_0000) - 0.5).abs() < 1e-7); - assert!((dynrng_gain(0b0111_1111) - 16.0 * 63.0 / 64.0).abs() < 1e-5); -} - -#[test] -fn channel_order() { - let ch = |n: usize| (0..n).map(|i| vec![i as f32]).collect::>(); - let ids = |v: Vec>| v.iter().map(|c| c[0] as usize).collect::>(); - // coded L C R Ls Rs LFE → L R C LFE Ls Rs - assert_eq!(ids(wav_order(ch(6), 7, true)), vec![0, 2, 1, 5, 3, 4]); - assert_eq!(ids(wav_order(ch(3), 2, true)), vec![0, 1, 2]); - assert_eq!(ids(wav_order(ch(1), 1, false)), vec![0]); -} - #[test] fn garbage_never_panics() { let mut d = Decoder::new(); @@ -146,66 +74,6 @@ fn eac3_frame(strmtyp: u32, substreamid: u32, words: u32, numblkscod: u32, acmod b } -#[test] -fn eac3_headers() { - let f = eac3_frame(0, 0, 384, 3, 2, |_| {}); - let h = parse_header(&f).unwrap(); - assert_eq!((h.sample_rate, h.blocks, h.samples(), h.frame_bytes, h.bitrate_kbps, h.channels()), (48_000, 6, 1536, 768, 192, 2)); - assert!(h.is_eac3() && h.is_primary()); - // one block per syncframe: 256 samples - let h = parse_header(&eac3_frame(0, 0, 100, 0, 7, |_| {})).unwrap(); - assert_eq!((h.blocks, h.samples(), h.channels(), h.bitrate_kbps), (1, 256, 5, 300)); - // reduced sample rate (fscod 3, fscod2 1): six blocks at 22.05 kHz - let mut f = eac3_frame(0, 0, 384, 0, 2, |_| {}); - f[4] = 0b1101_0100; - let h = parse_header(&f).unwrap(); - assert_eq!((h.sample_rate, h.blocks, h.acmod), (22_050, 6, 2)); - f[4] = 0b1111_0100; - assert_eq!(parse_header(&f), Err(Error::Invalid("reserved fscod2"))); - // a dependent substream and a second independent program are recognised and skipped - let mut d = Decoder::new(); - for (strmtyp, id) in [(1, 0), (0, 1)] { - let f = eac3_frame(strmtyp, id, 64, 3, 2, |_| {}); - let out = d.decode(&f).unwrap(); - assert!(!out.header.is_primary() && out.channels.is_empty()); - } - assert_eq!(parse_header(&eac3_frame(3, 0, 64, 3, 2, |_| {})), Err(Error::Unsupported("reserved E-AC-3 stream type 3".into()))); -} - -#[test] -fn eac3_tools_we_do_not_decode_are_refused() { - // mono, six blocks, AHT enabled and used: chexpstr D15 then reuse, so chahtinu is sent - let aht = eac3_frame(0, 0, 64, 3, 1, |w| { - w.put(1, 1); // expstre - w.put(1, 1); // ahte - w.put(2, 0); // snroffststr - w.put(8, 0); // transproce … spxattene - w.put(2, 1); // chexpstr[0] = D15 - w.put(10, 0); // chexpstr[1..6] = reuse - w.put(5, 0); // convexpstr - w.put(1, 1); // chahtinu - }); - assert_eq!(Decoder::new().decode(&aht).unwrap_err(), Error::Unsupported("E-AC-3 adaptive hybrid transform".into())); - // stereo with coupling in block 0 using enhanced coupling - let ecpl = eac3_frame(0, 0, 64, 3, 2, |w| { - w.put(1, 1); // expstre - w.put(1, 0); // ahte - w.put(2, 0); // snroffststr - w.put(8, 0); - w.put(1, 1); // cplinu[0] - w.put(5, 0); // cplstre[1..6] - w.put(6, 0b01_01_01); // block 0: cplexpstr, chexpstr × 2 - w.put(30, 0); // blocks 1-5: reuse - w.put(10, 0); // convexpstr - w.put(10, 0); // frmcsnroffst, frmfsnroffst - w.put(1, 0); // blkstrtinfoe - w.put(1, 0); // dynrnge - w.put(1, 0); // spxinu - w.put(1, 1); // ecplinu - }); - assert_eq!(Decoder::new().decode(&ecpl).unwrap_err(), Error::Unsupported("E-AC-3 enhanced coupling".into())); -} - /// A mono E-AC-3 syncframe of one block (256 samples) that sends exponents (all 10, bandwidth /// code 0) when `new_exps`, else reuses the last ones. Zero SNR offsets allocate no bits: every /// coefficient is dither. @@ -247,53 +115,6 @@ fn eac3_single_block_frames_reuse_exponents_across_syncframes() { assert_eq!(peak(&c.channels[0]), 0.0); } -#[test] -fn eac3_garbage_never_panics() { - let mut d = Decoder::new(); - let mut x = 0x5EEDu32; - for len in [8usize, 40, 300, 1500, 4096] { - for _ in 0..300 { - let mut f: Vec = (0..len) - .map(|_| { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - x as u8 - }) - .collect(); - f[0] = 0x0B; - f[1] = 0x77; - // independent substream 0, frmsiz within the buffer, bsid 11-16 - let words = (len / 2).clamp(4, 2048) - 1; - f[2] = (words >> 8) as u8 & 7; - f[3] = words as u8; - f[5] = (f[5] & 7) | ((11 + x % 6) as u8) << 3; - let _ = d.decode(&f); - } - } -} - -/// Golden hashes of the decoder output, so that a change of the bit reader cannot change a -/// decoded sample or an error. The values were made with the private bit-by-bit reader, before it -/// was replaced by the shared one: every frame below is decoded with a -/// fresh decoder, and every output sample bit (as `f32::to_bits`, channel after channel) and every -/// error (its `Debug` text) goes into an FNV-1a 64 hash. The frames are deterministic: valid -/// AC-3 and E-AC-3 syncframe headers (all fscod, frmsizecod, bsid, acmod and lfeon values in -/// the tables below) with random, zero-heavy or all-ones payload bits, plus truncated and -/// bit-flipped variants of the same frames. -struct Fnv(u64); - -impl Fnv { - fn new() -> Self { - Fnv(0xcbf2_9ce4_8422_2325) - } - fn bytes(&mut self, b: &[u8]) { - for &x in b { - self.0 = (self.0 ^ u64::from(x)).wrapping_mul(0x0000_0100_0000_01b3); - } - } -} - struct Rng(u32); impl Rng { @@ -315,147 +136,6 @@ fn payload_byte(rng: &mut Rng, flavour: usize) -> u8 { } } -/// See `synthetic_frames`: 12 syncframes, back to back. -const REAL_FRAMES: &[u8] = include_bytes!("golden_frames.bin"); - -fn synthetic_frames() -> Vec> { - let mut rng = Rng(0x00C0_FFEE); - let mut frames = Vec::new(); - // AC-3: bsid 8 and the half / quarter rate variants 9 and 10, every fscod and a spread of - // frmsizecod, acmod 0 to 7, lfeon off and on. - for n in 0..1200usize { - let fscod = n % 3; - let frmsizecod = (n * 7 + n / 3) % 38; - let bsid = [8u8, 8, 8, 9, 10, 6][n % 6]; - let acmod = (n / 3) % 8; - let lfeon = (n / 24) % 2; - let Ok(h) = parse_header(&[0x0B, 0x77, 0, 0, ((fscod << 6) | frmsizecod) as u8, bsid << 3, (acmod as u8) << 5, 0]) else { continue }; - let mut f = vec![0u8; h.frame_bytes]; - for b in f.iter_mut() { - *b = payload_byte(&mut rng, n); - } - f[0] = 0x0B; - f[1] = 0x77; - f[4] = ((fscod << 6) | frmsizecod) as u8; - f[5] = bsid << 3; - // acmod in the top 3 bits; the mix-level bits that follow depend on acmod and are random - f[6] = (f[6] & 0x1F) | ((acmod as u8) << 5); - // lfeon follows the optional 2-bit fields (cmixlev, surmixlev, dsurmod) - let mut at = 3; - if acmod & 1 != 0 && acmod != 1 { - at += 2; - } - if acmod & 4 != 0 { - at += 2; - } - if acmod == 2 { - at += 2; - } - let bit = 48 + at; - f[bit / 8] = (f[bit / 8] & !(0x80 >> (bit % 8))) | ((lfeon as u8) * (0x80 >> (bit % 8))); - frames.push(f); - } - // E-AC-3: strmtyp 0 / 1 / 2, fscod 0..=3 (3 = reduced rate), numblkscod, acmod, lfeon - for n in 0..800usize { - let words = 24 + (n * 13) % 400; - let fscod = n % 4; - let blk = (n / 4) % 4; - let acmod = (n / 16) % 8; - let lfeon = (n / 128) % 2; - let strmtyp = [0u32, 0, 0, 1, 2][n % 5]; - let bsid = 11 + (n % 6) as u32; - let mut f = vec![0u8; words * 2]; - for b in f.iter_mut() { - *b = payload_byte(&mut rng, n); - } - let head: u32 = (strmtyp << 30) - | (((n % 7) as u32) << 27) - | (((words - 1) as u32) << 16) - | ((fscod as u32) << 14) - | ((if fscod == 3 { (n / 7 % 3) as u32 } else { blk as u32 }) << 12) - | ((acmod as u32) << 9) - | ((lfeon as u32) << 8) - | (bsid << 3) - | (f[5] as u32 & 7); - f[0] = 0x0B; - f[1] = 0x77; - f[2..6].copy_from_slice(&head.to_be_bytes()); - frames.push(f); - } - // real frames (two of each stream, made with ffmpeg's ac3 / eac3 encoders from tones and noise: - // mono 64k 32 kHz, coupled stereo 96k 44.1 kHz, noise stereo 96k, 5.1 192k; E-AC-3 noise - // stereo 96k and 5.1 192k) reach exponents, bit allocation and mantissas of every block, which - // random payload bits almost never do. Each one is decoded as is, with 60 bit-flipped copies - // and cut at every 16th byte. - let mut p = 0; - while let Ok(h) = parse_header(&REAL_FRAMES[p..]) { - let f = &REAL_FRAMES[p..p + h.frame_bytes]; - p += h.frame_bytes; - frames.push(f.to_vec()); - for _ in 0..60 { - let mut m = f.to_vec(); - for _ in 0..1 + rng.next() % 3 { - let bit = 64 + rng.next() as usize % (m.len() * 8 - 64); - m[bit / 8] ^= 0x80 >> (bit % 8); - } - frames.push(m); - } - for cut in (8..f.len()).step_by(16) { - frames.push(f[..cut].to_vec()); - } - } - // truncated and bit-flipped variants of every 5th frame - let base = frames.clone(); - for (i, f) in base.iter().enumerate().step_by(5) { - let mut t = f.clone(); - t.truncate(rng.next() as usize % f.len()); - frames.push(t); - let mut m = f.clone(); - for _ in 0..1 + rng.next() % 6 { - let bit = rng.next() as usize % (m.len() * 8); - m[bit / 8] ^= 0x80 >> (bit % 8); - } - frames.push(m); - // cut the payload to just a few bytes after the header, so that the reads run past the end - let mut s = f.clone(); - s.truncate((8 + i % 40).min(f.len())); - frames.push(s); - } - frames -} - -#[test] -fn decoded_output_matches_golden_hashes() { - let (mut all, mut ok, mut err, mut audio) = (Fnv::new(), 0usize, 0usize, 0usize); - for (i, f) in synthetic_frames().iter().enumerate() { - let mut dec = Decoder::new(); - // decode each frame twice with the same decoder: the second pass also covers the - // E-AC-3 carry-over and the overlap state - for _ in 0..2 { - match dec.decode(f) { - Ok(d) => { - ok += 1; - audio += usize::from(!d.channels.is_empty()); - all.bytes(&[1]); - for ch in &d.channels { - for s in ch { - all.bytes(&s.to_bits().to_le_bytes()); - } - } - } - Err(e) => { - err += 1; - all.bytes(format!("{i}:{e:?}").as_bytes()); - } - } - } - } - eprintln!("golden: ok {ok} ({audio} with audio) err {err} hash {:#018x}", all.0); - assert_eq!((ok, err, all.0), GOLDEN); -} - -const GOLDEN: (usize, usize, u64) = (2960, 7024, 0x1dc9_31d6_0e89_e8c8); - /// The private reader this crate used before it moved to the shared `BitReader`, verbatim. struct OldBits<'a> { d: &'a [u8], diff --git a/crates/audio/src/alac/ag.rs b/crates/audio/src/alac/ag.rs index e813441930..c86d448fe5 100644 --- a/crates/audio/src/alac/ag.rs +++ b/crates/audio/src/alac/ag.rs @@ -246,31 +246,6 @@ mod tests { use super::super::bits::{BitReader, BitSink, BitWriter}; use super::*; - fn roundtrip(values: &[i32], bits: u32) { - let mut w = BitWriter::new(); - compress(AgParams::standard(), values, &mut w, bits).unwrap(); - let len = w.bit_len(); - let bytes = w.into_bytes(); - let mut r = BitReader::new(&bytes); - let mut out = vec![0; values.len()]; - decompress(AgParams::standard(), &mut r, &mut out, bits).unwrap(); - assert_eq!(out, values); - assert_eq!(r.position(), len); - } - - #[test] - fn residuals_roundtrip() { - roundtrip(&[0, 1, -1, 2, -2, 100, -100, 30000, -32768, 32767], 16); - roundtrip(&[0; 300], 16); - let mut v = vec![0; 70_000]; - v[0] = 5; - v[69_999] = -3; - roundtrip(&v, 16); - let wide: Vec = (0..500).map(|i| ((i * 7919) % 65_536 - 32_768) << 8).collect(); - roundtrip(&wide, 25); - roundtrip(&[i32::MAX >> 1, i32::MIN >> 1, 0, 0, 0, 1], 32); - } - /// The largest escaped magnitude, 0xffffffff, is i32::MIN (the reference wraps it to 0). #[test] fn the_full_width_escape_decodes_to_the_minimum() { @@ -282,15 +257,4 @@ mod tests { decompress(AgParams::standard(), &mut BitReader::new(&bytes), &mut out, 32).unwrap(); assert_eq!(out, [i32::MIN]); } - - #[test] - fn a_truncated_stream_is_an_error() { - let mut w = BitWriter::new(); - let values: Vec = (0..64).map(|i| i * 1000 - 32_000).collect(); - compress(AgParams::standard(), &values, &mut w, 16).unwrap(); - let bytes = w.into_bytes(); - let mut r = BitReader::new(&bytes[..bytes.len() / 2]); - let mut out = vec![0; values.len()]; - assert!(decompress(AgParams::standard(), &mut r, &mut out, 16).is_err()); - } } diff --git a/crates/audio/src/alac/bits.rs b/crates/audio/src/alac/bits.rs index 1ff8d10f0d..72c3c76bb9 100644 --- a/crates/audio/src/alac/bits.rs +++ b/crates/audio/src/alac/bits.rs @@ -189,44 +189,3 @@ impl BitSink for BitCounter { self.0 } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn writer_and_reader_agree() { - let mut w = BitWriter::new(); - w.put(0b101, 3); - w.put(0xABCD, 16); - w.put(0xDEAD_BEEF, 32); - w.put(1, 1); - assert_eq!(w.bit_len(), 52); - let bytes = w.into_bytes(); - let mut r = BitReader::new(&bytes); - assert_eq!(r.read(3), Ok(0b101)); - assert_eq!(r.read(16), Ok(0xABCD)); - assert_eq!(r.read(32), Ok(0xDEAD_BEEF)); - assert_eq!(r.read(1), Ok(1)); - assert_eq!(r.read(4), Ok(0)); - assert_eq!(r.read(1), Err(Error::Eof)); - assert_eq!(r.peek(32), 0); - } - - #[test] - fn truncate_clears_the_dropped_bits() { - let mut w = BitWriter::new(); - w.put(0xFFFF, 16); - w.truncate(5); - w.put(0, 3); - assert_eq!(w.into_bytes(), vec![0xF8]); - } - - #[test] - fn sign_extension() { - assert_eq!(sign_extend(0xF, 4), -1); - assert_eq!(sign_extend(0x7, 4), 7); - assert_eq!(sign_extend(0x8000_0000, 32), i32::MIN); - assert_eq!(sign_extend(5, 0), 0); - } -} diff --git a/crates/audio/src/alac/decoder.rs b/crates/audio/src/alac/decoder.rs index f728936b3f..40f4ed8d1b 100644 --- a/crates/audio/src/alac/decoder.rs +++ b/crates/audio/src/alac/decoder.rs @@ -282,10 +282,6 @@ pub(crate) fn header_frames(packet: &[u8], frame_length: u64) -> Option { mod tests { use super::*; - fn stereo16() -> Vec { - SpecificConfig::new(44_100, 2, 16, 4096).to_cookie() - } - #[test] fn cookies_out_of_range_are_refused() { let ok = SpecificConfig::new(44_100, 2, 16, 4096); @@ -302,24 +298,6 @@ mod tests { } } - #[test] - fn an_escaped_stereo_frame() { - // CPE, instance 0, 12 zero bits, flags: partial + escape, 2 frames, then L R L R. - let mut w = super::super::bits::BitWriter::new(); - use super::super::bits::BitSink; - w.put(ID_CPE, 3); - w.put(0, 4); - w.put(0, 12); - w.put(0b1001, 4); - w.put(2, 32); - for s in [1i32, -1, 32767, -32768] { - w.put(s as u32, 16); - } - w.put(ID_END, 3); - let mut dec = Decoder::new(&stereo16()).unwrap(); - assert_eq!(dec.decode(&w.into_bytes()).unwrap(), vec![vec![1, 32767], vec![-1, -32768]]); - } - /// An escaped mono packet that lost its last byte keeps every sample but not its end tag. #[test] fn a_packet_without_its_end_tag_is_an_error() { @@ -344,27 +322,6 @@ mod tests { assert_eq!(dec.decode(&w.into_bytes()).unwrap(), vec![vec![9]]); } - #[test] - fn the_frames_of_a_packet_come_from_its_header() { - use super::super::bits::{BitSink, BitWriter}; - let dec = Decoder::new(&SpecificConfig::new(44_100, 2, 16, 4096).to_cookie()).unwrap(); - let header = |flags: u32, frames: Option| { - let mut w = BitWriter::new(); - for (value, bits) in [(ID_CPE, 3), (0, 4), (0, 12), (flags, 4)] { - w.put(value, bits); - } - if let Some(n) = frames { - w.put(n, 32); - } - w.into_bytes() - }; - assert_eq!(dec.packet_frames(&header(0b1001, Some(300))), Some(300)); - assert_eq!(dec.packet_frames(&header(0b0001, None)), Some(4096)); - assert_eq!(dec.packet_frames(&header(0b1001, Some(5000))), None); - assert_eq!(dec.packet_frames(&header(0b1001, None)), None); - assert_eq!(dec.packet_frames(&[0xE0]), None); // ID_END first - } - #[test] fn hostile_packets_fail_or_decode_without_panicking() { let mut dec = Decoder::new(&SpecificConfig::new(48_000, 8, 24, 4096).to_cookie()).unwrap(); diff --git a/crates/audio/src/alac/dp.rs b/crates/audio/src/alac/dp.rs index 3e37e30216..61e3960311 100644 --- a/crates/audio/src/alac/dp.rs +++ b/crates/audio/src/alac/dp.rs @@ -164,33 +164,3 @@ pub(crate) fn unpc_first_order_in_place(buf: &mut [i32], num: usize, chanbits: u buf[j] = wrap(buf[j].wrapping_add(buf[j - 1]), chanshift); } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_predictor_inverts() { - let input: Vec = (0..2000).map(|i: i32| ((i as f64 * 0.05).sin() * 20000.0) as i32 + (i * 31 % 17) - 8).collect(); - for numactive in [0, 1, 4, 8, 12, FIRST_ORDER] { - for num in [0, 1, 3, 9, 2000] { - let mut ce = [0i16; 32]; - init_coefs(&mut ce, DENSHIFT_DEFAULT); - let mut cd = ce; - let mut pc = vec![0; 2000]; - let mut out = vec![0; 2000]; - pc_block(&input, &mut pc, num, &mut ce, numactive, 16, DENSHIFT_DEFAULT); - unpc_block(&pc, &mut out, num, &mut cd, numactive, 16, DENSHIFT_DEFAULT); - assert_eq!(out[..num], input[..num], "numactive {numactive}, num {num}"); - assert_eq!(ce, cd); - } - } - } - - #[test] - fn coefficient_start_values() { - let mut c = [7i16; 16]; - init_coefs(&mut c, DENSHIFT_DEFAULT); - assert_eq!(&c[..4], &[1216, -928, -64, 0]); - } -} diff --git a/crates/audio/src/alac/encoder.rs b/crates/audio/src/alac/encoder.rs index a589a9060a..7fc842597b 100644 --- a/crates/audio/src/alac/encoder.rs +++ b/crates/audio/src/alac/encoder.rs @@ -563,18 +563,4 @@ mod tests { let mut dec = Decoder::new(&enc.cookie()).unwrap(); assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]); } - - #[test] - fn bad_input_is_refused() { - assert!(Encoder::new(EncoderConfig::new(44_100, 2, 8)).is_err()); - assert!(Encoder::new(EncoderConfig::new(44_100, 9, 16)).is_err()); - assert!(Encoder::new(EncoderConfig::new(44_100, 2, 16).with_frame_length(0)).is_err()); - let mut enc = Encoder::new(EncoderConfig::new(44_100, 2, 16).with_frame_length(16)).unwrap(); - assert!(enc.encode(&[&[0; 4]]).is_err()); - assert!(enc.encode(&[&[0; 4], &[0; 5]]).is_err()); - assert!(enc.encode(&[&[0; 17], &[0; 17]]).is_err()); - assert!(enc.encode(&[&[], &[]]).is_err()); - assert!(enc.encode(&[&[40_000], &[0]]).is_err()); - assert!(enc.encode(&[&[-32_768], &[32_767]]).is_ok()); - } } diff --git a/crates/audio/src/alac/matrix.rs b/crates/audio/src/alac/matrix.rs index 95dfc13c3b..4adc5482e6 100644 --- a/crates/audio/src/alac/matrix.rs +++ b/crates/audio/src/alac/matrix.rs @@ -99,22 +99,3 @@ pub(crate) fn shift_mono(input: &[i32], pred_in: &mut [i32], shift_buf: &mut [u1 } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn matrixing_inverts() { - let l: Vec = (0..100).map(|i| (i * 977 % 16_000_000) - 8_000_000).collect(); - let r: Vec = (0..100).map(|i| (i * 7919 % 16_000_000) - 8_000_000).collect(); - for (mixres, bytes) in [(0, 0), (1, 0), (2, 1), (4, 1), (3, 0)] { - let (mut u, mut v, mut s) = (vec![0; 100], vec![0; 100], vec![0u16; 200]); - let m = Mix { bits: 2, res: mixres }; - mix((&l, &r), (&mut u, &mut v), m, &mut s, bytes); - let (mut l2, mut r2) = (vec![0; 100], vec![0; 100]); - unmix((&u, &v), (&mut l2, &mut r2), m, &s, bytes, 24); - assert_eq!((l2, r2), (l.clone(), r.clone()), "mixres {mixres}"); - } - } -} diff --git a/crates/audio/src/alac/mod.rs b/crates/audio/src/alac/mod.rs index a797d1ab68..14bbbf6c50 100644 --- a/crates/audio/src/alac/mod.rs +++ b/crates/audio/src/alac/mod.rs @@ -293,24 +293,6 @@ impl SpecificConfig { mod tests { use super::*; - #[test] - fn cookies_roundtrip() { - let mut c = SpecificConfig::new(48_000, 6, 24, 4096); - c.max_frame_bytes = 12_345; - c.avg_bit_rate = 2_000_000; - let bytes = c.to_cookie(); - assert_eq!(bytes.len(), 48); - let mut parsed = SpecificConfig::parse(&bytes).unwrap(); - assert_eq!(parsed.channel_layout_tag, Some((124 << 16) | 6)); - assert!(parsed.has_standard_layout()); - parsed.channel_layout_tag = None; - assert_eq!(parsed, c); - assert_eq!(c.to_bytes(), bytes[..24]); - let stereo = SpecificConfig::new(44_100, 2, 16, 4096).to_cookie(); - assert_eq!(stereo.len(), 24); - assert_eq!(&stereo[..12], &[0, 0, 0x10, 0, 0, 16, 40, 10, 14, 2, 0, 255]); - } - #[test] fn a_little_endian_layout_tag_is_read() { // as Apple's reference encoder writes the tag of a 7.1 stream @@ -330,19 +312,4 @@ mod tests { assert!(SpecificConfig::parse(&wrapped[..30]).is_err()); assert!(SpecificConfig::parse(&[0; 5]).is_err()); } - - #[test] - fn the_orders_are_permutations() { - for n in 3..=8u8 { - let order = wav_order(n).unwrap(); - let inverse = alac_order(n).unwrap(); - assert!((0..usize::from(n)).all(|i| inverse[order[i]] == i && order[inverse[i]] == i), "{n} channels"); - let mut sorted = order.to_vec(); - sorted.sort_unstable(); - assert_eq!(sorted, (0..usize::from(n)).collect::>()); - assert_eq!(channel_mask(n).count_ones(), u32::from(n)); - let elements: usize = element_map(usize::from(n)).iter().map(|&e| if e == ID_CPE { 2 } else { 1 }).sum(); - assert_eq!(elements, usize::from(n)); - } - } } diff --git a/crates/audio/src/layout.rs b/crates/audio/src/layout.rs index e5e6723ece..08abe5423d 100644 --- a/crates/audio/src/layout.rs +++ b/crates/audio/src/layout.rs @@ -317,37 +317,3 @@ pub(crate) fn channel_map(mask: u32, order: Option<&[usize]>, layout: &ChannelLa } Some(map) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn speakers_follow_the_mask_in_wav_order() { - assert_eq!( - ChannelLayout::SURROUND_5_1_SIDE.speakers(), - [Speaker::FrontLeft, Speaker::FrontRight, Speaker::FrontCenter, Speaker::Lfe, Speaker::SideLeft, Speaker::SideRight] - ); - assert_eq!(ChannelLayout::SURROUND_7_1.index_of(Speaker::SideLeft), Some(6)); - assert_eq!(Speaker::SideRight.mask_bit(), 0x400); - } - - #[test] - fn a_mask_that_does_not_match_the_channels_is_unordered() { - assert_eq!(ChannelLayout::from_mask_and_channels(0x3F, 6), ChannelLayout::SURROUND_5_1); - assert!(!ChannelLayout::from_mask_and_channels(0x3, 4).is_ordered()); - assert!(!ChannelLayout::from_mask_and_channels(0, 4).is_ordered()); - assert!(!ChannelLayout::from_mask(1 << 20).is_ordered()); - assert_eq!(ChannelLayout::unordered(4).channels(), 4); - assert!(ChannelLayout::unordered(4).speakers().is_empty()); - } - - #[test] - fn defaults_and_names() { - assert_eq!(ChannelLayout::default_for(6), ChannelLayout::SURROUND_5_1); - assert!(!ChannelLayout::default_for(9).is_ordered()); - assert_eq!(ChannelLayout::default_for(2).to_string(), "stereo"); - assert_eq!(ChannelLayout::SURROUND_5_1_SIDE.to_string(), "5.1"); - assert_eq!(ChannelLayout::unordered(10).to_string(), "10 channels"); - } -} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 5eac73187d..29054288ec 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -809,6 +809,13 @@ impl Default for EncodeOptions { } } +#[cfg(test)] +extern crate self as craft_audio; + +#[cfg(test)] +#[path = "../tests/main.rs"] +mod integration; + // An encoder refusing its settings is an encode error, not damaged input. #[cfg(all(test, feature = "aac-encode"))] mod tests { diff --git a/crates/audio/src/mpa/mod.rs b/crates/audio/src/mpa/mod.rs index 3db2041768..09560c9d48 100644 --- a/crates/audio/src/mpa/mod.rs +++ b/crates/audio/src/mpa/mod.rs @@ -474,6 +474,3 @@ pub(crate) fn synthesize(v: &mut [f32; 1024], pos: &mut usize, n: &[[f32; 36]; 3 } *out = o; } - -#[cfg(test)] -mod tests; diff --git a/crates/audio/src/mpa/tests.rs b/crates/audio/src/mpa/tests.rs deleted file mode 100644 index 941509bc82..0000000000 --- a/crates/audio/src/mpa/tests.rs +++ /dev/null @@ -1,250 +0,0 @@ -use super::*; -use tables::window_half; - -/// A frame header: MPEG-1 unless `lsf`, `layer` 1/2, no CRC, `bitrate_index`, `rate_index` -/// (0: 44.1 kHz, 1: 48 kHz, 2: 32 kHz), `mode` 0-3 and `mode_extension`. -fn header(lsf: bool, layer: u8, bitrate_index: u8, rate_index: u8, mode: u8, ext: u8) -> [u8; 4] { - let version = if lsf { 0b10 } else { 0b11 }; - [0xFF, 0xE0 | version << 3 | (4 - layer) << 1 | 1, bitrate_index << 4 | rate_index << 2, mode << 6 | ext << 4] -} - -/// A frame of `header` with all-zero audio data: no subband has an allocation. -fn silent(h: [u8; 4]) -> Vec { - let mut f = h.to_vec(); - f.resize(parse_header(&h).unwrap().frame_bytes, 0); - f -} - -#[test] -fn headers() { - // Layer II 48 kHz stereo 192 kbit/s: 144 * 192000 / 48000 = 576 bytes - let h = parse_header(&header(false, 2, 10, 1, 0, 0)).unwrap(); - assert_eq!( - (h.version, h.layer, h.bitrate_kbps, h.sample_rate, h.frame_bytes, h.channels(), h.samples()), - (Version::Mpeg1, 2, 192, 48_000, 576, 2, 1152) - ); - // ffmpeg's default for mono: Layer II 384 kbit/s, which ISO/IEC 11172-3 does not allow - let h = parse_header(&header(false, 2, 14, 1, 3, 0)).unwrap(); - assert_eq!((h.bitrate_kbps, h.frame_bytes, h.mode, h.channels()), (384, 1152, Mode::Mono, 1)); - // Layer I 44.1 kHz 384 kbit/s with padding: (12 * 384000 / 44100 + 1) * 4 = 420 - let mut b = header(false, 1, 12, 0, 1, 2); - b[2] |= 2; - let h = parse_header(&b).unwrap(); - assert_eq!((h.layer, h.frame_bytes, h.samples(), h.mode, h.mode_extension, h.bound()), (1, 420, 384, Mode::JointStereo, 2, 12)); - // MPEG-2 Layer II 24 kHz 160 kbit/s: 144 * 160000 / 24000 = 960; Layer I 22.05 kHz 256 kbit/s - let h = parse_header(&header(true, 2, 14, 1, 0, 0)).unwrap(); - assert_eq!((h.version, h.sample_rate, h.frame_bytes), (Version::Mpeg2, 24_000, 960)); - let h = parse_header(&header(true, 1, 14, 0, 0, 0)).unwrap(); - assert_eq!((h.sample_rate, h.bitrate_kbps, h.frame_bytes), (22_050, 256, 4 * (12 * 256_000 / 22_050))); - // MPEG-2.5 and Layer III headers parse too - assert_eq!(parse_header(&[0xFF, 0xE5, 0x10, 0xC0]).unwrap().sample_rate, 11_025); - let h = parse_header(&[0xFF, 0xFB, 0x90, 0x44]).unwrap(); - assert_eq!((h.layer, h.frame_bytes), (3, 417)); -} - -#[test] -fn bad_headers_are_errors() { - assert_eq!(parse_header(&[]), Err(Error::Invalid("truncated header"))); - assert_eq!(parse_header(&[0xFF, 0xFD]), Err(Error::Invalid("truncated header"))); - assert_eq!(parse_header(&[0x00, 0xFD, 0x90, 0x00]), Err(Error::NoSync)); - assert_eq!(parse_header(&[0xFF, 0x1D, 0x90, 0x00]), Err(Error::NoSync)); - assert_eq!(parse_header(&[0xFF, 0xED, 0x90, 0x00]), Err(Error::Invalid("reserved version"))); - assert_eq!(parse_header(&[0xFF, 0xF9, 0x90, 0x00]), Err(Error::Invalid("reserved layer"))); - assert_eq!(parse_header(&[0xFF, 0xFD, 0xF0, 0x00]), Err(Error::Invalid("forbidden bit rate index"))); - assert_eq!(parse_header(&[0xFF, 0xFD, 0x9C, 0x00]), Err(Error::Invalid("reserved sampling frequency"))); - let mut d = Decoder::new(); - assert_eq!(d.decode(&[0xFF, 0xFB, 0x90, 0x44]).unwrap_err(), Error::Unsupported("Layer III")); - assert_eq!(d.decode(&[0xFF, 0xFD, 0x04, 0x00, 0, 0]).unwrap_err(), Error::Unsupported("free-format bit rate")); - assert_eq!(d.decode(&silent(header(false, 2, 10, 1, 0, 0))[..100]).unwrap_err(), Error::Invalid("truncated frame")); -} - -#[test] -fn silent_frames_decode_to_silence() { - let mut d = Decoder::new(); - for (h, ch, n) in [ - (header(false, 2, 14, 1, 3, 0), 1, 1152), - (header(false, 2, 1, 2, 0, 0), 2, 1152), - (header(true, 2, 8, 0, 1, 3), 2, 1152), - (header(false, 1, 6, 0, 2, 0), 2, 384), - (header(false, 1, 4, 1, 3, 0), 1, 384), - ] { - let f = d.decode(&silent(h)).unwrap(); - assert_eq!(f.channels.len(), ch, "{h:?}"); - assert!(f.channels.iter().all(|c| c.len() == n && c.iter().all(|&s| s == 0.0)), "{h:?}"); - } -} - -/// Table 3-B.3 as typed in must be the smooth prototype filter: with every other block of 64 -/// negated back, its third differences stay within the rounding of the 2⁻¹⁶ units (a mistyped -/// coefficient shows up as a spike of hundreds). -#[test] -fn synthesis_window_is_the_smooth_prototype() { - let h: Vec = (0..=256).map(|i| window_half(i).unwrap() as f64 * if (i / 64) % 2 == 1 { -1.0 } else { 1.0 }).collect(); - let d1: Vec = h.windows(2).map(|w| w[1] - w[0]).collect(); - let d2: Vec = d1.windows(2).map(|w| w[1] - w[0]).collect(); - let worst = d2.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0, f64::max); - assert!(worst <= 8.0, "{worst}"); - assert_eq!(window_half(257), None); - let w = tables::window(); - // symmetry of the full window and the table's endpoints - assert_eq!((w[0], w[256], w[511], w[448]), (0.0, 75_038.0 / 65_536.0, 1.0 / 65_536.0, w[64])); - assert_eq!(w[300], -w[212]); -} - -#[test] -fn layer2_allocation_tables() { - use tables::AllocTable as T; - for t in [T::A, T::B, T::C, T::D, T::Lsf] { - for sb in 0..t.sblimit() { - let row = t.row(sb); - assert!(row.len().is_power_of_two() && row[0] == 0, "{t:?} {sb}"); - } - } - // the allowed combinations (Table 3-B.2) and the ones encoders write anyway - assert_eq!(T::select(false, 48_000, 192), T::A); - assert_eq!(T::select(false, 44_100, 64), T::A); - assert_eq!(T::select(false, 44_100, 96), T::B); - assert_eq!(T::select(false, 32_000, 192), T::B); - assert_eq!(T::select(false, 48_000, 32), T::C); - assert_eq!(T::select(false, 44_100, 48), T::C); - assert_eq!(T::select(false, 32_000, 48), T::D); - assert_eq!(T::select(false, 48_000, 384), T::A); - assert_eq!(T::select(false, 44_100, 384), T::B); - assert_eq!(T::select(false, 32_000, 16), T::D); - assert_eq!(T::select(true, 24_000, 160), T::Lsf); -} - -#[test] -fn requantization_is_symmetric() { - assert_eq!([0, 1, 2].map(|v| requantize(v, 3)), [-2.0 / 3.0, 0.0, 2.0 / 3.0]); - assert_eq!(requantize(4, 9), 0.0); - assert_eq!(requantize(0, 65_535), -65_534.0 / 65_535.0); -} - -/// Random audio data behind valid headers, and damaged headers: errors or noise, never a panic. -#[test] -fn random_frames_never_panic() { - let mut x = 0x1234_5678u32; - let mut rnd = move || { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - x - }; - let mut d = Decoder::new(); - for k in 0..4000 { - let mut h = header(k % 3 == 0, 1 + (k % 2) as u8, 1 + (rnd() % 14) as u8, (rnd() % 3) as u8, (rnd() % 4) as u8, (rnd() % 4) as u8); - if k % 5 == 0 { - h[1] &= 0xFE; // CRC present - } - if k % 7 == 0 { - h[2] ^= rnd() as u8; - h[3] ^= rnd() as u8; - } - let len = parse_header(&h).map(|p| p.frame_bytes).unwrap_or(64); - let mut f = h.to_vec(); - f.extend((0..len.saturating_sub(4) + (rnd() % 8) as usize).map(|_| rnd() as u8)); - if k % 11 == 0 { - f.truncate(rnd() as usize % f.len()); - } - if let Ok(fr) = d.decode(&f) { - assert!(fr.channels.iter().flatten().all(|s| s.is_finite())); - } - } -} - -/// Output of the decoder, bit for bit, on deterministic synthetic streams. -/// -/// Each stream is a run of valid headers (mono, stereo, joint stereo at several bounds and dual -/// channel; Layer I and II; MPEG-1 and MPEG-2; several bit rates and sampling frequencies) -/// followed by xorshift noise, decoded by one `Decoder` so that the synthesis filter's history -/// carries from frame to frame. Frames the decoder rejects are counted and skipped. The hash is -/// FNV-1a over the bits of every decoded sample. -/// -/// The golden values were captured from the decoder before the synthesis filterbank was -/// rewritten (`synthesize` with the shifting `V` buffer and the 64-row matrix): check out that -/// commit, run `cargo test -p filmcraft-mpa decoded_samples_are_bit_exact -- --nocapture`, and -/// copy the printed `(ok, hash)` pairs. A change of the filter's arithmetic (summation order, -/// grouping, fused multiply-add) shows up here; a legitimate one needs new goldens and a reason. -#[test] -fn decoded_samples_are_bit_exact() { - // (lsf, layer, bitrate_index, rate_index, mode, mode_extension) - const STREAMS: &[(bool, u8, u8, u8, u8, u8)] = &[ - (false, 2, 10, 1, 0, 0), - (false, 2, 14, 1, 3, 0), - (false, 2, 6, 0, 1, 0), - (false, 2, 9, 0, 1, 3), - (false, 2, 5, 2, 2, 0), - (false, 2, 2, 1, 0, 0), - (true, 2, 8, 0, 1, 2), - (true, 2, 4, 2, 3, 0), - (false, 1, 12, 0, 1, 2), - (false, 1, 14, 1, 0, 0), - (false, 1, 8, 2, 3, 0), - (true, 1, 10, 0, 2, 0), - ]; - let mut got = vec![]; - for (n, &(lsf, layer, br, rate, mode, ext)) in STREAMS.iter().enumerate() { - let mut x = 0x9E37_79B9u32 ^ (n as u32).wrapping_mul(0x85EB_CA6B); - let mut rnd = move || { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - x - }; - let mut d = Decoder::new(); - let (mut ok, mut hash) = (0u32, 0xCBF2_9CE4_8422_2325u64); - for _ in 0..60 { - let h = header(lsf, layer, br, rate, mode, ext); - let len = parse_header(&h).map_or(0, |p| p.frame_bytes); - let mut f = h.to_vec(); - // sparse noise: most allocations are zero, so many frames are valid and quiet - f.extend((0..len.saturating_sub(4)).map(|_| (rnd() & rnd() & rnd()) as u8)); - if let Ok(fr) = d.decode(&f) { - ok += 1; - for s in fr.channels.iter().flatten() { - hash = (hash ^ u64::from(s.to_bits())).wrapping_mul(0x0000_0100_0000_01B3); - } - } - } - got.push((ok, hash)); - } - println!("{got:?}"); - const GOLDEN: &[(u32, u64)] = &[ - (59, 0xea8448e85fe3df1b), - (60, 0xc6ecc7f674c186d4), - (60, 0xb38a4d7cba7bfbde), - (59, 0xf37f8a5abff50363), - (60, 0x1e489c563c40c852), - (49, 0x52ab5c8f9db13cc1), - (60, 0x401b8039ec831783), - (60, 0x3555c5d49d12ecca), - (59, 0xb063c5f8c79edaef), - (58, 0xcedb49aa85eb2e29), - (58, 0x3ee32a2c6b9da56b), - (57, 0xbb913530021557b1), - ]; - assert_eq!(got, GOLDEN); -} - -/// `reset` forgets the filter history, including where the ring buffer of `V` starts. -#[test] -fn reset_matches_a_fresh_decoder() { - let mut x = 0x2545_F491u32; - let mut f = header(false, 2, 10, 1, 0, 0).to_vec(); - f.extend((0..572).map(|_| { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - (x & (x >> 7) & (x >> 13)) as u8 - })); - let first = Decoder::new().decode(&f).unwrap(); - let mut d = Decoder::new(); - for _ in 0..3 { - d.decode(&f).unwrap(); - } - d.reset(); - let again = d.decode(&f).unwrap(); - assert!(first.channels.iter().flatten().any(|&s| s != 0.0)); - assert_eq!(first.channels, again.channels); -} diff --git a/crates/audio/src/opus/decode/celt/bands.rs b/crates/audio/src/opus/decode/celt/bands.rs index 5544ef3264..b7b944cb7b 100644 --- a/crates/audio/src/opus/decode/celt/bands.rs +++ b/crates/audio/src/opus/decode/celt/bands.rs @@ -995,78 +995,3 @@ pub fn denormalise_bands(input: DenormaliseBandsInput<'_>) { freq[from..n].fill(0.0); } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn bitexact_trig_endpoints() { - assert_eq!(bitexact_cos(0), 32768); - - let mid = bitexact_cos(8192); - assert!((mid - 23170).abs() < 20, "{mid}"); - assert_eq!(bitexact_log2tan(16384, 16384), 0); - } - - #[test] - fn isqrt_exact() { - for v in [0u32, 1, 2, 3, 4, 15, 16, 17, 99, 100, 1 << 20, u32::MAX] { - let r = isqrt32(v) as u64; - assert!(r * r <= v as u64 && (r + 1) * (r + 1) > v as u64); - } - } - - #[test] - fn pvq_table_matches_reference_counts() { - let table = pvq_table(); - for n in 0..=PVQ_MAX_N { - for k in 0..=PVQ_MAX_K { - let want = super::super::rate::pvq_v(n, k).min(u32::MAX as u128) as u32; - // V(0, k > 0) = 0 and V(n, 0) = 1 in both. - assert_eq!(table[n * PVQ_W + k], want, "n={n} k={k}"); - } - } - } - - #[test] - fn pvq_roundtrip_all_codewords_small() { - use crate::opus::decode::range::enc::RangeEncoder; - // Enumerate every index for small N,K, decode, and check uniqueness + sum |y| == K. - for n in 1..6usize { - for k in 1..5usize { - let total = super::super::rate::pvq_v(n, k) as u32; - let mut seen = std::collections::HashSet::new(); - for idx in 0..total { - let mut e = RangeEncoder::new(16); - e.uint(idx, total); - let buf = e.done(); - let mut d = RangeDecoder::new(&buf); - let mut y = vec![0i32; n]; - let ryy = decode_pulses(&mut y, n, k, &mut d); - assert_eq!(y.iter().map(|v| v.unsigned_abs() as usize).sum::(), k); - assert_eq!(ryy as i32, y.iter().map(|v| v * v).sum::()); - assert!(seen.insert(y.clone()), "duplicate codeword n={n} k={k} idx={idx}"); - } - } - } - } - - #[test] - fn haar_is_involution() { - let mut x: Vec = (0..16).map(|i| i as f32).collect(); - let orig = x.clone(); - haar1(&mut x, 16, 1); - haar1(&mut x, 16, 1); - for (a, b) in x.iter().zip(&orig) { - assert!((a - b).abs() < 1e-4); - } - let mut tmp = Vec::new(); - for &h in &[false, true] { - let mut y = orig.clone(); - deinterleave_hadamard(&mut y, 4, 4, h, &mut tmp); - interleave_hadamard(&mut y, 4, 4, h, &mut tmp); - assert_eq!(y, orig); - } - } -} diff --git a/crates/audio/src/opus/decode/celt/energy.rs b/crates/audio/src/opus/decode/celt/energy.rs index fccb767ebe..e6ac34d7cd 100644 --- a/crates/audio/src/opus/decode/celt/energy.rs +++ b/crates/audio/src/opus/decode/celt/energy.rs @@ -117,56 +117,3 @@ pub fn unquant_energy_finalise(input: EnergyFinalise<'_, '_>) { } } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::opus::decode::range::enc::RangeEncoder; - - fn laplace_encode(e: &mut RangeEncoder, value: i32, mut fs: u32, decay: u32) { - let mut fl = 0u32; - let mut val = value; - if val != 0 { - let s: i32 = if val < 0 { -1 } else { 0 }; - val = val.abs(); - fl = fs; - fs = laplace_get_freq1(fs, decay); - let mut i = 1; - while fs > 0 && i < val { - fs *= 2; - fl += fs + 2 * LAPLACE_MINP; - fs = (fs * decay) >> 15; - i += 1; - } - if fs == 0 { - let ndi_max = (32768 - fl + LAPLACE_MINP - 1) as i32; - let ndi_max = (ndi_max - s) >> 1; - let di = (val - i).min(ndi_max - 1); - fl = (fl as i32 + (2 * di + 1 + s) * LAPLACE_MINP as i32) as u32; - fs = LAPLACE_MINP.min(32768 - fl); - } else { - fs += LAPLACE_MINP; - if s == 0 { - fl += fs; - } - } - } - e.encode(fl, fl + fs, 32768); - } - - #[test] - fn laplace_roundtrip() { - for &(fs, decay) in &[(72u32 << 7, 127u32 << 6), (24 << 7, 179 << 6), (177 << 7, 11 << 6)] { - let vals: Vec = (-12..=12).collect(); - let mut e = RangeEncoder::new(400); - for &v in &vals { - laplace_encode(&mut e, v, fs, decay); - } - let buf = e.done(); - let mut d = RangeDecoder::new(&buf); - for &v in &vals { - assert_eq!(laplace_decode(&mut d, fs, decay), v, "fs={fs} v={v}"); - } - } - } -} diff --git a/crates/audio/src/opus/decode/celt/mdct.rs b/crates/audio/src/opus/decode/celt/mdct.rs index 7503d9ebe1..eb38e941d3 100644 --- a/crates/audio/src/opus/decode/celt/mdct.rs +++ b/crates/audio/src/opus/decode/celt/mdct.rs @@ -73,111 +73,3 @@ pub struct ImdctScratch { z: Vec, scratch: Vec, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fft_matches_dft() { - for &n in &[15usize, 30, 60, 120, 240, 480, 960] { - let fft = Fft::new(n); - let x: Vec = (0..n).map(|i| Cpx { re: ((i * 7) % 13) as f32 - 6.0, im: ((i * 3) % 5) as f32 - 2.0 }).collect(); - let mut y = x.clone(); - fft.process(&mut y, &mut Vec::new()); - for k in [0, 1, 7, n / 2, n - 1] { - let mut acc = (0f64, 0f64); - for (i, v) in x.iter().enumerate() { - let ph = -2.0 * std::f64::consts::PI * (i * k) as f64 / n as f64; - acc.0 += v.re as f64 * ph.cos() - v.im as f64 * ph.sin(); - acc.1 += v.re as f64 * ph.sin() + v.im as f64 * ph.cos(); - } - assert!((acc.0 - y[k].re as f64).abs() < 1e-2 && (acc.1 - y[k].im as f64).abs() < 1e-2, "n={n} k={k}"); - } - } - } - - /// The previous generic implementation (every butterfly multiplies by every DFT root), kept - /// to measure how far the specialised kernels move the output. - fn reference_fft(n: usize, data: &mut [Cpx]) { - let fft = Fft::new(n); - let inp = data.to_vec(); - rec_ref(&fft, data, &inp, 1, n, 0, 1); - } - - fn rec_ref(f: &Fft, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) { - let p = f.factors[fi]; - let m = n / p; - if m == 1 { - for (i, o) in out.iter_mut().enumerate().take(p) { - *o = inp[i * in_stride]; - } - } else { - for q in 0..p { - rec_ref(f, &mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p); - } - } - let big = f.n; - let mut t = [Cpx::default(); 5]; - for k in 0..m { - for q in 0..p { - let w = f.twiddle[(q * k * tw_stride) % big]; - t[q] = out[q * m + k].mul(w); - } - for q2 in 0..p { - let mut acc = Cpx::default(); - for (q, tq) in t.iter().enumerate().take(p) { - let w = f.twiddle[((q * q2) % p) * (big / p)]; - acc = acc.add(tq.mul(w)); - } - out[q2 * m + k] = acc; - } - } - } - - /// Every size the CELT frame sizes use (N/4 for N = 2 * {120, 240, 480, 960}, plus the - /// short-block sizes) agrees with the previous implementation to f32 rounding. - #[test] - fn fft_matches_reference_implementation() { - for &n in &[15usize, 30, 60, 120, 240, 480, 960] { - let fft = Fft::new(n); - let x: Vec = (0..n) - .map(|i| Cpx { re: (((i * 7919) % 2003) as f32 - 1000.0) / 500.0, im: (((i * 104729) % 1009) as f32 - 500.0) / 250.0 }) - .collect(); - let mut new = x.clone(); - fft.process(&mut new, &mut Vec::new()); - let mut old = x.clone(); - reference_fft(n, &mut old); - let peak = old.iter().map(|c| c.re.abs().max(c.im.abs())).fold(0f32, f32::max); - let max_diff = new.iter().zip(&old).map(|(a, b)| (a.re - b.re).abs().max((a.im - b.im).abs())).fold(0f32, f32::max); - assert!(max_diff <= 1e-5 * peak, "n={n} max_diff={max_diff} peak={peak}"); - } - } - - /// The folded output must equal the direct IMDCT formula folded by TDAC symmetry. - #[test] - fn imdct_matches_direct_formula() { - let n = 240; - let n2 = n / 2; - let im = Imdct::new(n); - let x: Vec = (0..n2).map(|k| ((k * 37 % 11) as f32 - 5.0) / 5.0).collect(); - let overlap = 0; - let mut out = vec![0f32; n2]; - im.backward(&x, 1, &mut out, &[], overlap, &mut ImdctScratch::default()); - // Direct IMDCT y[t] = sum X[k] cos(2pi/N (t + 1/2 + N/4)(k + 1/2)), t in 0..N. - let y: Vec = (0..n) - .map(|t| { - (0..n2) - .map(|k| x[k] as f64 * (2.0 * std::f64::consts::PI / n as f64 * (t as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()) - .sum() - }) - .collect(); - // The folded half: out[i] relates to y in the middle half; check proportionality. - let mid: Vec = (0..n2).map(|i| y[n / 4 + i]).collect(); - let dot: f64 = mid.iter().zip(&out).map(|(a, b)| a * *b as f64).sum(); - let ea: f64 = mid.iter().map(|a| a * a).sum(); - let eb: f64 = out.iter().map(|b| (*b as f64).powi(2)).sum(); - let corr = dot.abs() / (ea.sqrt() * eb.sqrt()); - assert!(corr > 0.999, "corr {corr}"); - } -} diff --git a/crates/audio/src/opus/decode/celt/rate.rs b/crates/audio/src/opus/decode/celt/rate.rs index 29e8566c14..78e98e17e7 100644 --- a/crates/audio/src/opus/decode/celt/rate.rs +++ b/crates/audio/src/opus/decode/celt/rate.rs @@ -4,10 +4,6 @@ use super::tables::{EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS, OVERLAP}; use crate::opus::decode::range::{BITRES, RangeDecoder}; pub use crate::opus::rate_common::get_pulses; -#[cfg(test)] -use crate::opus::rate_common::log2_frac; -#[cfg(test)] -pub use crate::opus::rate_common::pvq_v; pub const MAX_FINE_BITS: i32 = 8; const FINE_OFFSET: i32 = 21; pub const QTHETA_OFFSET: i32 = 4; @@ -271,42 +267,3 @@ fn interp_bits2pulses(input: InterpPulsesInput<'_, '_>) -> Allocation { } Allocation { coded_bands, intensity, dual_stereo, balance, pulses: bits, fine_quant: ebits, fine_priority } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn log2_frac_values() { - assert_eq!(log2_frac(1, 3), 0); - assert_eq!(log2_frac(2, 3), 8); - assert_eq!(log2_frac(4, 3), 16); - assert_eq!(log2_frac(6, 3), 21); - assert_eq!(log2_frac(18, 3), 34); - assert_eq!(log2_frac(22, 3), 36); - } - - #[test] - fn pvq_counts() { - // V(N,1) = 2N, V(1,K) = 2 (K>0), V(2,K) = 4K. - assert_eq!(pvq_v(5, 1), 10); - assert_eq!(pvq_v(1, 7), 2); - assert_eq!(pvq_v(2, 9), 36); - assert_eq!(pvq_v(3, 2), 18); - assert_eq!(pvq_v(0, 0), 1); - assert_eq!(pvq_v(0, 3), 0); - } - - #[test] - fn caps_match_reference_shape() { - let m = Mode::new(); - // 1-bin bands at LM=0 (mono and stereo) are capped at 224. - assert!(m.caps[..8].iter().all(|&c| c == 224)); - assert!(m.caps[21..29].iter().all(|&c| c == 224)); - let first_rows: [u8; 42] = [ - 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, - 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, - ]; - assert_eq!(&m.caps[..42], &first_rows[..]); - } -} diff --git a/crates/audio/src/opus/decode/header.rs b/crates/audio/src/opus/decode/header.rs index 51ab4f534b..d7f13320d1 100644 --- a/crates/audio/src/opus/decode/header.rs +++ b/crates/audio/src/opus/decode/header.rs @@ -173,50 +173,6 @@ impl OpusHead { mod tests { use super::*; - #[test] - fn parse_family0_and_roundtrip() { - let mut h = b"OpusHead".to_vec(); - h.extend([1, 2, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0x00, 0x01, 0]); - let head = OpusHead::parse(&h).unwrap(); - assert_eq!(head.channels, 2); - assert_eq!(head.pre_skip, 312); - assert_eq!(head.input_sample_rate, 48000); - assert_eq!(head.output_gain, 256); - assert_eq!((head.streams, head.coupled_streams), (1, 1)); - assert_eq!(head.to_bytes(), h); - assert!((head.gain_linear() - 1.122).abs() < 1e-3); - } - - #[test] - fn parse_family1_51() { - let mut h = b"OpusHead".to_vec(); - h.extend([1, 6, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0, 0, 1, 4, 2, 0, 4, 1, 2, 3, 5]); - let head = OpusHead::parse(&h).unwrap(); - assert_eq!((head.channels, head.streams, head.coupled_streams), (6, 4, 2)); - assert_eq!(head.mapping, vec![0, 4, 1, 2, 3, 5]); - assert_eq!(OpusHead::parse(&head.to_bytes()).unwrap(), head); - } - - #[test] - fn rejects_garbage() { - assert!(OpusHead::parse(b"OpusHea").is_err()); - assert!(OpusHead::parse(b"OpusTags...........").is_err()); - let mut h = b"OpusHead".to_vec(); - h.extend([1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - assert!(OpusHead::parse(&h).is_err()); - let mut h = b"OpusHead".to_vec(); - h.extend([1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 5]); - assert!(OpusHead::parse(&h).is_err()); - } - - #[test] - fn dops() { - let d = [0u8, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 0]; - let head = OpusHead::from_dops(&d).unwrap(); - assert_eq!(head.pre_skip, 312); - assert_eq!(head.channels, 2); - } - #[test] fn directly_constructed_headers_are_checked_before_decoder_allocation() { let head = OpusHead { diff --git a/crates/audio/src/opus/decode/packet.rs b/crates/audio/src/opus/decode/packet.rs index 4531716209..4a28c792e6 100644 --- a/crates/audio/src/opus/decode/packet.rs +++ b/crates/audio/src/opus/decode/packet.rs @@ -268,21 +268,6 @@ pub fn packet_samples_48k(data: &[u8]) -> Result { mod tests { use super::*; - #[test] - fn toc_configs() { - for cfg in 0u8..32 { - let t = Toc::parse(cfg << 3); - let ms10 = t.frame_samples(48000) * 10 / 48; // tenths of ms - let expect = match cfg { - 0..=11 => [100, 200, 400, 600][cfg as usize & 3], - 12..=15 => [100, 200][cfg as usize & 1], - _ => [25, 50, 100, 200][cfg as usize & 3], - }; - assert_eq!(ms10, expect, "config {cfg}"); - } - assert!(Toc::parse(0x04).stereo); - } - #[test] fn frame_codes() { // code 0 @@ -309,30 +294,4 @@ mod tests { assert!(Packet::parse(&[0x03, 0x00]).is_err()); assert!(Packet::parse(&[]).is_err()); } - - #[test] - fn two_byte_sizes() { - let mut pkt = vec![0x02u8, 252, 1]; - pkt.extend(std::iter::repeat_n(7u8, 256)); - pkt.extend([1, 2]); - let p = Packet::parse(&pkt).unwrap(); - assert_eq!(p.frames[0].len(), 256); - assert_eq!(p.frames[1], &[1, 2]); - } - - #[test] - fn self_delimited() { - // code 0 with explicit size, followed by trailing data of the next stream. - let (p, used) = Packet::parse_self_delimited(&[0x00, 2, 5, 6, 0xAA, 0xBB]).unwrap(); - assert_eq!(p.frames, vec![&[5u8, 6][..]]); - assert_eq!(used, 4); - // code 1: one size for both frames. - let (p, used) = Packet::parse_self_delimited(&[0x01, 1, 5, 6, 9]).unwrap(); - assert_eq!(p.frames, vec![&[5u8][..], &[6u8][..]]); - assert_eq!(used, 4); - // code 3 VBR, 2 frames: size of frame 0, then size of last frame. - let (p, used) = Packet::parse_self_delimited(&[0x03, 0x82, 1, 2, 7, 8, 9, 0xFF]).unwrap(); - assert_eq!(p.frames, vec![&[7u8][..], &[8u8, 9][..]]); - assert_eq!(used, 7); - } } diff --git a/crates/audio/src/opus/decode/range.rs b/crates/audio/src/opus/decode/range.rs index 33ba14f2b6..72ccf26e4c 100644 --- a/crates/audio/src/opus/decode/range.rs +++ b/crates/audio/src/opus/decode/range.rs @@ -7,8 +7,6 @@ const SYM_BITS: u32 = 8; const CODE_BITS: u32 = 32; const SYM_MAX: u32 = (1 << SYM_BITS) - 1; -#[cfg(test)] -const CODE_SHIFT: u32 = CODE_BITS - SYM_BITS - 1; const CODE_TOP: u32 = 1 << (CODE_BITS - 1); const CODE_BOT: u32 = CODE_TOP >> SYM_BITS; const CODE_EXTRA: u32 = (CODE_BITS - 2) % SYM_BITS + 1; @@ -260,238 +258,3 @@ impl<'a> RangeDecoder<'a> { nbits.wrapping_sub(l) } } - -#[cfg(test)] -pub(crate) mod enc { - //! Minimal range encoder (RFC 6716 §5.1), used only to build test streams. - use super::*; - - pub struct RangeEncoder { - out: Vec, - end: Vec, - end_window: u32, - nend_bits: i32, - rng: u32, - low: u32, - rem: i32, - ext: u32, - size: usize, - } - - impl RangeEncoder { - pub fn new(size: usize) -> Self { - RangeEncoder { out: Vec::new(), end: Vec::new(), end_window: 0, nend_bits: 0, rng: CODE_TOP, low: 0, rem: -1, ext: 0, size } - } - fn carry_out(&mut self, c: u32) { - if c != SYM_MAX { - let carry = c >> SYM_BITS; - if self.rem >= 0 { - self.out.push((self.rem as u32 + carry) as u8); - } - if self.ext > 0 { - let sym = (SYM_MAX + carry) & SYM_MAX; - for _ in 0..self.ext { - self.out.push(sym as u8); - } - self.ext = 0; - } - self.rem = (c & SYM_MAX) as i32; - } else { - self.ext += 1; - } - } - fn normalize(&mut self) { - while self.rng <= CODE_BOT { - self.carry_out(self.low >> CODE_SHIFT); - self.low = (self.low << SYM_BITS) & (CODE_TOP - 1); - self.rng <<= SYM_BITS; - } - } - pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) { - let r = self.rng / ft; - if fl > 0 { - self.low += self.rng - r * (ft - fl); - self.rng = r * (fh - fl); - } else { - self.rng -= r * (ft - fh); - } - self.normalize(); - } - pub fn bit_logp(&mut self, val: bool, logp: u32) { - let r = self.rng; - let s = r >> logp; - let r2 = r - s; - if val { - self.low += r2; - self.rng = s; - } else { - self.rng = r2; - } - self.normalize(); - } - pub fn icdf(&mut self, s: usize, icdf: &[u8], ftb: u32) { - let r = self.rng >> ftb; - if s > 0 { - self.low += self.rng - r * icdf[s - 1] as u32; - self.rng = r * (icdf[s - 1] as u32 - icdf[s] as u32); - } else { - self.rng -= r * icdf[s] as u32; - } - self.normalize(); - } - pub fn uint(&mut self, fl: u32, ft: u32) { - let ft1 = ft - 1; - let ftb = ilog(ft1); - if ftb > 8 { - let ftb = (ftb - 8) as u32; - let top = (ft1 >> ftb) + 1; - let v = fl >> ftb; - self.encode(v, v + 1, top); - self.bits(fl & ((1 << ftb) - 1), ftb); - } else { - self.encode(fl, fl + 1, ft); - } - } - pub fn bits(&mut self, val: u32, bits: u32) { - let mut window = self.end_window; - let mut used = self.nend_bits; - if used as u32 + bits > CODE_BITS { - while used >= SYM_BITS as i32 { - self.end.push((window & SYM_MAX) as u8); - window >>= SYM_BITS; - used -= SYM_BITS as i32; - } - } - window |= val << used; - used += bits as i32; - self.end_window = window; - self.nend_bits = used; - } - /// Finalises and returns a buffer of exactly `size` bytes. - pub fn done(mut self) -> Vec { - let mut l = CODE_BITS as i32 - ilog(self.rng); - let mut msk = (CODE_TOP - 1) >> l; - let mut end = (self.low + msk) & !msk; - if (end | msk) >= self.low + self.rng { - l += 1; - msk >>= 1; - end = (self.low + msk) & !msk; - } - while l > 0 { - self.carry_out(end >> CODE_SHIFT); - end = (end << SYM_BITS) & (CODE_TOP - 1); - l -= SYM_BITS as i32; - } - if self.rem >= 0 || self.ext > 0 { - self.carry_out(0); - } - let mut window = self.end_window; - let mut used = self.nend_bits; - while used > 0 { - self.end.push((window & SYM_MAX) as u8); - window >>= SYM_BITS; - used -= SYM_BITS as i32; - } - assert!(self.out.len() + self.end.len() <= self.size, "range encoder overflow"); - let mut buf = self.out; - buf.resize(self.size - self.end.len(), 0); - for &b in self.end.iter().rev() { - buf.push(b); - } - buf - } - } -} - -#[cfg(test)] -mod tests { - use super::enc::RangeEncoder; - use super::*; - - struct Lcg(u32); - impl Lcg { - fn next(&mut self) -> u32 { - self.0 = self.0.wrapping_mul(1664525).wrapping_add(1013904223); - self.0 >> 8 - } - } - - #[test] - fn roundtrip_mixed_symbols() { - let mut rng = Lcg(1); - for trial in 0..200 { - let n = 1 + (rng.next() % 300) as usize; - let mut ops = Vec::new(); - for _ in 0..n { - match rng.next() % 5 { - 0 => { - let ft = 2 + rng.next() % 1000; - let v = rng.next() % ft; - ops.push((0u8, v, ft)); - } - 1 => { - let logp = 1 + rng.next() % 15; - ops.push((1, rng.next().is_multiple_of(7) as u32, logp)); - } - 2 => { - let bits = 1 + rng.next() % 24; - ops.push((2, rng.next() & ((1 << bits) - 1), bits)); - } - 3 => { - let ft = 2 + rng.next() % 100_000_000; - ops.push((3, rng.next() % ft, ft)); - } - _ => ops.push((4, rng.next() % 4, 0)), - } - } - let icdf: [u8; 4] = [200, 120, 30, 0]; - let mut e = RangeEncoder::new(8 * n + 16); - for &(k, v, p) in &ops { - match k { - 0 => e.encode(v, v + 1, p), - 1 => e.bit_logp(v != 0, p), - 2 => e.bits(v, p), - 3 => e.uint(v, p), - _ => e.icdf(v as usize, &icdf, 8), - } - } - let buf = e.done(); - let mut d = RangeDecoder::new(&buf); - for (i, &(k, v, p)) in ops.iter().enumerate() { - let got = match k { - 0 => { - let s = d.decode(p); - d.update(s, s + 1, p); - s - } - 1 => d.bit_logp(p) as u32, - 2 => d.bits(p), - 3 => d.uint(p), - _ => d.icdf(&icdf, 8) as u32, - }; - assert_eq!(got, v, "trial {trial} op {i} kind {k}"); - } - assert!(!d.error); - } - } - - #[test] - fn tell_starts_at_one_bit() { - let buf = [0u8; 8]; - let d = RangeDecoder::new(&buf); - assert_eq!(d.tell(), 1); - assert_eq!(d.tell_frac(), 8); - } - - #[test] - fn empty_and_garbage_never_panic() { - let mut d = RangeDecoder::new(&[]); - for i in 0..100 { - d.bits(1 + i % 20); - d.uint(3 + i * 77); - d.icdf(&[250, 100, 0], 8); - d.bit_logp(1 + i % 15); - } - let _ = d.tell_frac(); - } -} diff --git a/crates/audio/src/opus/decode/silk/lpc.rs b/crates/audio/src/opus/decode/silk/lpc.rs index 32a6d02340..9a8bb3ffbe 100644 --- a/crates/audio/src/opus/decode/silk/lpc.rs +++ b/crates/audio/src/opus/decode/silk/lpc.rs @@ -337,41 +337,3 @@ pub fn nlsf2a(nlsf: &[i32]) -> [i32; MAX_LPC_ORDER] { } a_q12 } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn flat_nlsf_gives_small_lpc() { - // Uniformly spaced NLSFs correspond to an (almost) flat spectrum. - let nlsf: Vec = (1..=16).map(|k| k * 32768 / 17).collect(); - let a = nlsf2a(&nlsf); - assert!(a.iter().all(|v| v.abs() < 600), "{a:?}"); - let nlsf: Vec = (1..=10).map(|k| k * 32768 / 11).collect(); - let a = nlsf2a(&nlsf); - assert!(a[..10].iter().all(|v| v.abs() < 600), "{a:?}"); - } - - #[test] - fn stabilize_enforces_spacing() { - let mut v = [100, 90, 80, 30000, 30001, 30002, 31000, 32000, 32700, 32760]; - nlsf_stabilize(&mut v, &NLSF_MIN_SPACING_NBMB); - assert!(v[0] >= NLSF_MIN_SPACING_NBMB[0]); - for i in 1..10 { - assert!(v[i] - v[i - 1] >= NLSF_MIN_SPACING_NBMB[i], "{v:?}"); - } - assert!(32768 - v[9] >= NLSF_MIN_SPACING_NBMB[10]); - } - - #[test] - fn inverse_approximations() { - for &b in &[65536, 100_000, 1 << 20, 81920, 1_686_110_208] { - let inv = inverse32_varq(b, 47) as f64; - let exact = 2f64.powi(47) / b as f64; - assert!((inv - exact).abs() / exact < 1e-3, "{b}"); - } - let q = div32_varq(65536, 131072, 16) as f64; - assert!((q - 32768.0).abs() < 2.0); - } -} diff --git a/crates/audio/src/opus/decode/silk/resampler.rs b/crates/audio/src/opus/decode/silk/resampler.rs index 7d3f803eff..0bd3efa809 100644 --- a/crates/audio/src/opus/decode/silk/resampler.rs +++ b/crates/audio/src/opus/decode/silk/resampler.rs @@ -184,49 +184,3 @@ impl Resampler { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn upsample_sine_and_delay() { - for &(fin, fout) in &[(16000u32, 48000u32), (8000, 48000), (12000, 48000), (16000, 24000), (16000, 8000), (12000, 16000)] { - let mut r = Resampler::new(fin, fout); - let f = 440.0; - let n = fin as usize / 10; - let x: Vec = (0..n).map(|i| ((2.0 * std::f64::consts::PI * f * i as f64 / fin as f64).sin() * 10000.0) as i16).collect(); - let mut y = Vec::new(); - for c in x.chunks(fin as usize / 50) { - r.process(c, &mut y); - } - assert_eq!(y.len(), n * fout as usize / fin as usize); - // Compare against the ideal delayed sine. - let delay_ms = match fin { - 8000 => 0.538, - 12000 => 0.692, - _ => 0.706, - }; - let mut err = 0f64; - let mut sig = 0f64; - for (j, &v) in y.iter().enumerate().skip(fout as usize / 100) { - let t = j as f64 / fout as f64 - delay_ms / 1000.0; - let ideal = (2.0 * std::f64::consts::PI * f * t).sin() * 10000.0; - err += (v as f64 - ideal).powi(2); - sig += ideal * ideal; - } - let snr = 10.0 * (sig / err).log10(); - assert!(snr > 35.0, "{fin}->{fout}: {snr} dB"); - } - } - - #[test] - fn dot8_matches_sequential_sum() { - for len in [1usize, 7, 8, 9, 35, 36, 71] { - let a: Vec = (0..len).map(|i| ((i * 37 % 19) as f32 - 9.0) * 1000.0).collect(); - let b: Vec = (0..len).map(|i| ((i * 11 % 7) as f32 - 3.0) / 7.0).collect(); - let seq: f64 = a.iter().zip(&b).map(|(&x, &y)| x as f64 * y as f64).sum(); - assert!((dot8(&a, &b) as f64 - seq).abs() < 1e-2, "len {len}"); - } - } -} diff --git a/crates/audio/src/peaks.rs b/crates/audio/src/peaks.rs index 16a6c14bbe..dacd509882 100644 --- a/crates/audio/src/peaks.rs +++ b/crates/audio/src/peaks.rs @@ -185,101 +185,4 @@ mod tests { assert_eq!(p.minmax(&x, a, b), brute(&x, a, b), "range {a}..{b}"); } } - - #[test] - fn degenerate_inputs() { - let p = Peaks::build(&[]); - assert_eq!(p.len_samples(), 0); - assert_eq!(p.minmax(&[], 0, 10), (0.0, 0.0)); - assert_eq!(p.spans(&[], 0.0, 1.0, 0.0, 4), vec![None; 4]); - let x = [0.5, -0.25]; - let p = Peaks::build(&x); - assert_eq!(p.minmax(&x, 0, 2), (-0.25, 0.5)); - assert_eq!(p.minmax(&x, 5, 3), (0.0, 0.0)); - assert_eq!(p.minmax(&x, 0, usize::MAX), (-0.25, 0.5)); - assert_eq!(p.minmax(&x[..1], 0, 2), (0.5, 0.5)); - for (start, step, overlap) in [ - (f64::NAN, 1.0, 0.0), - (0.0, 0.0, 0.0), - (0.0, -1.0, 0.0), - (0.0, f64::INFINITY, 0.0), - (f64::NEG_INFINITY, 1.0, 0.0), - (0.0, 1.0, -0.5), - (0.0, 1.0, f64::NAN), - ] { - assert_eq!(p.spans(&x, start, step, overlap, 3), vec![None; 3]); - } - assert_eq!(p.spans(&x, 0.0, 1.0, 0.0, 0).len(), 0); - assert_eq!(p.spans(&x, 0.0, 1.0, 0.0, usize::MAX).len(), MAX_COLUMNS); - let x = [f32::NAN, 1.0]; - let p = Peaks::build(&x); - assert_eq!(p.minmax(&x, 0, 2), (1.0, 1.0)); - assert_eq!(p.spans(&x, 0.0, 1.0, 0.0, 1), vec![Some((1.0, 1.0))]); - assert!(p.rms_spans(&x, 0.0, 1.0, 0.0, 1)[0].is_some_and(f32::is_finite)); - } - - #[test] - fn loud_finite_samples_give_a_finite_rms() { - let x = [1e20f32, -1e20, 3e38, 0.5]; - let p = Peaks::build(&x); - let rms = p.rms_spans(&x, 0.0, 4.0, 0.0, 1)[0].unwrap(); - let want = (x.iter().map(|&v| f64::from(v) * f64::from(v)).sum::() / 4.0).sqrt() as f32; - assert!(rms.is_finite() && (rms / want - 1.0).abs() < 1e-6, "{rms} vs {want}"); - } - - #[test] - fn rms_spans_match_the_samples() { - let x = signal(20_000); - let p = Peaks::build(&x); - let rms = |s: usize, e: usize| (x[s..e].iter().map(|&v| f64::from(v) * f64::from(v)).sum::() / (e - s) as f64).sqrt() as f32; - for (step, overlap) in [(1.5, 0.0), (37.0, 37.0), (1000.0, 0.0), (4096.0, 512.0)] { - let cols = ((19_999.0 - overlap) / step) as usize; - for (c, got) in p.rms_spans(&x, 0.0, step, overlap, cols).into_iter().enumerate() { - let (a, b) = (c as f64 * step, ((c + 1) as f64 * step + overlap).min(19_999.0)); - let (got, want) = (got.unwrap(), rms(a.floor() as usize, (b.ceil() as usize + 1).min(20_000))); - assert!((got - want).abs() <= want * 1e-4 + 1e-6, "span {c} at step {step}: {got} vs {want}"); - } - } - let sine: Vec = (0..48_000).map(|i| (i as f32 * 0.01).sin()).collect(); - let p = Peaks::build(&sine); - let r = p.rms_spans(&sine, 0.0, 47_000.0, 0.0, 1)[0].unwrap(); - assert!((r - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3, "{r}"); - assert_eq!(p.rms_spans(&sine, f64::NAN, 1.0, 0.0, 2), vec![None, None]); - assert_eq!(p.rms_spans(&sine, 50_000.0, 1.0, 0.0, 1), vec![None]); - } - - #[test] - fn spans_cover_their_samples_and_touch_their_neighbours() { - let x = signal(10_000); - let p = Peaks::build(&x); - for step in [0.3, 1.0, 7.5, 100.0, 333.3] { - let cols = (9_999.0 / step) as usize; - let spans = p.spans(&x, 0.0, step, 0.0, cols); - for (c, s) in spans.iter().enumerate() { - let (lo, hi) = s.unwrap_or_else(|| panic!("span {c} at step {step}")); - let (a, b) = ((c as f64 * step).ceil() as usize, ((c + 1) as f64 * step).floor() as usize); - if a <= b { - let truth = brute(&x, a, b + 1); - assert!(lo <= truth.0 && hi >= truth.1, "span {c} at step {step}"); - } - if let Some(Some((nlo, nhi))) = spans.get(c + 1) { - assert!(*nlo <= hi && *nhi >= lo, "spans {c} and {} at step {step} don't touch", c + 1); - } - } - let all = spans.iter().flatten().fold((f32::INFINITY, f32::NEG_INFINITY), |a, s| (a.0.min(s.0), a.1.max(s.1))); - assert_eq!(all, brute(&x, 0, ((cols as f64 * step).floor() as usize + 1).min(10_000)), "step {step}"); - } - } - - #[test] - fn spans_follow_the_line_between_samples() { - let x = [0.0, 1.0, -1.0, 0.5]; - let p = Peaks::build(&x); - assert_eq!(p.spans(&x, 0.0, 0.25, 0.0, 4), vec![Some((0.0, 0.25)), Some((0.25, 0.5)), Some((0.5, 0.75)), Some((0.75, 1.0))]); - assert_eq!(p.spans(&x, 0.5, 1.0, 0.0, 1), vec![Some((0.0, 1.0))]); - let spans = vec![None, Some((0.0, 0.0)), Some((0.0, 1.0)), Some((-1.0, 1.0)), Some((-1.0, 0.5)), Some((0.5, 0.5)), None]; - assert_eq!(p.spans(&x, -2.0, 1.0, 0.0, 7), spans); - assert_eq!(p.spans(&x, 0.0, 1.0, 1.0, 3), vec![Some((-1.0, 1.0)), Some((-1.0, 1.0)), Some((-1.0, 0.5))]); - assert_eq!(p.spans(&x, 0.0, 1.0, 0.5, 3), vec![Some((0.0, 1.0)), Some((-1.0, 1.0)), Some((-1.0, 0.5))]); - } } diff --git a/crates/audio/src/read/caf.rs b/crates/audio/src/read/caf.rs index d1c6f69c78..6e8ca1f728 100644 --- a/crates/audio/src/read/caf.rs +++ b/crates/audio/src/read/caf.rs @@ -85,13 +85,3 @@ fn varint(b: &[u8], at: usize) -> Option<(u64, usize)> { } None } - -#[cfg(test)] -mod tests { - #[test] - fn rejects_cookie_size_above_signed_range() { - let mut bytes = b"caff\0\x01\0\0kuki".to_vec(); - bytes.extend_from_slice(&(1u64 << 63).to_be_bytes()); - assert!(super::check(&bytes, 0).is_err()); - } -} diff --git a/crates/audio/src/read/mod.rs b/crates/audio/src/read/mod.rs index 5d78af9c1c..fad1841efd 100644 --- a/crates/audio/src/read/mod.rs +++ b/crates/audio/src/read/mod.rs @@ -558,75 +558,3 @@ fn not_built(src: &Src<'_>) -> AudioError { None => AudioError::Unsupported("not a recognized audio format".into()), } } - -#[cfg(all(test, not(feature = "symphonia")))] -mod native_only_tests { - use super::*; - - /// Without symphonia, a format with no native decoder is unsupported, not malformed. - #[test] - fn formats_left_to_symphonia_are_unsupported() { - let flac_header = [&b"fLaC"[..], &[0x80, 0, 0, 34], &[0; 34]].concat(); - assert!(matches!(decode(&flac_header, None), Err(AudioError::Unsupported(m)) if m.contains("FLAC"))); - assert!(matches!(probe(&flac_header, None), Err(AudioError::Unsupported(_)))); - // A track list says the same instead of listing nothing. - assert!(matches!(tracks(&flac_header, None), Err(AudioError::Unsupported(m)) if m.contains("FLAC"))); - // Bytes that name no format are not blamed on the build. - assert!(matches!(tracks(&[7u8; 64], None), Err(AudioError::Unsupported(m)) if m.contains("not a recognized"))); - } - - /// A source that cannot be read is an I/O error, not an unrecognized format. - #[test] - fn a_failed_header_read_is_an_io_error() { - struct Failing; - impl craft_media::ByteSource for Failing { - fn len(&self) -> u64 { - 1000 - } - fn read_at(&self, _: u64, _: &mut [u8]) -> std::io::Result<()> { - Err(std::io::Error::other("disk gone")) - } - } - assert!(matches!(tracks_of(Failing, None), Err(AudioError::Io(_)))); - assert!(matches!(Decoder::open(Failing, None, &DecodeOptions::default()), Err(AudioError::Io(_)))); - } - - /// A damaged file in a container the native path reads is malformed, not left to a decoder - /// this build lacks. - #[test] - fn a_damaged_mp4_is_malformed() { - // an `ftyp` box and nothing after it: no `moov` - let mp4 = [&16u32.to_be_bytes()[..], b"ftypisom", &[0, 0, 2, 0]].concat(); - assert!(matches!(decode(&mp4, None), Err(AudioError::Malformed(_)))); - assert!(matches!(tracks(&mp4, None), Err(AudioError::Malformed(_)))); - } - - /// A source that fails past its first 64 KiB fails inside the demuxer: still an I/O error. - #[test] - fn a_failed_read_inside_the_demuxer_is_an_io_error() { - use craft_media::matroska::{LacingMode, MkvWriter, MuxOptions, TrackKind, TrackSpec}; - struct FailsLate(Vec); - impl craft_media::ByteSource for FailsLate { - fn len(&self) -> u64 { - self.0.len() as u64 - } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { - if offset + buf.len() as u64 > 64 * 1024 { - return Err(std::io::Error::other("disk gone")); - } - self.0.read_at(offset, buf) - } - } - // a Matroska PCM file of about 400 KB, whose cues and later clusters lie past 64 KiB - let mut spec = TrackSpec::new(TrackKind::Audio, "A_PCM/FLOAT/IEEE"); - spec.audio = Some((48_000.0, 1, Some(32))); - let opts = MuxOptions { lacing: LacingMode::None, ..MuxOptions::default() }; - let mut w = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], opts).unwrap(); - for k in 0..100i64 { - w.write_frame(0, k * 20_000_000, true, &[0; 960 * 4], Some(20_000_000)).unwrap(); - } - let file = w.finish().unwrap().into_inner(); - assert!(matches!(tracks_of(FailsLate(file.clone()), None), Err(AudioError::Io(_)))); - assert!(matches!(Decoder::open(FailsLate(file), None, &DecodeOptions::default()), Err(AudioError::Io(_)))); - } -} diff --git a/crates/audio/src/read/native.rs b/crates/audio/src/read/native.rs index ede4628aaf..a42aec6d47 100644 --- a/crates/audio/src/read/native.rs +++ b/crates/audio/src/read/native.rs @@ -1420,32 +1420,6 @@ mod adts_tests { w.finish() } - /// ALAC in MP4 decodes natively (without symphonia this is the only path): every sample, - /// the short last packet included, and a seek lands on the exact frame. - #[test] - fn alac_in_mp4_decodes_and_seeks_natively() { - use craft_media::isobmff::{Brand, CodecConfig, FourCc, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; - // Escaped (uncompressed) stereo 16-bit packets of 4 frames, the last one of 2. - let frames: Vec<[i16; 2]> = (0..10).map(|i| [i * 100 - 300, -(i * 77)]).collect(); - let packet = |chunk: &[[i16; 2]]| alac_escaped_stereo(chunk, 4); - let cookie = crate::alac::SpecificConfig::new(48_000, 2, 16, 4).to_bytes(); - let entry = SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie }, 2, 48_000.0, 16); - let mut w = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); - let track = w.add_track(TrackConfig::new(entry, 48_000)).unwrap(); - for chunk in frames.chunks(4) { - w.write_sample(track, WriteSample { data: &packet(chunk), duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap(); - } - let file = w.finish().unwrap().into_inner(); - let (info, buf) = decode(&file, None).unwrap(); - assert_eq!((info.codec, info.sample_format, info.sample_rate, info.frames), (crate::CodecId::Alac, crate::SampleFormat::Int16, 48_000, 10)); - let ints: Vec<[i16; 2]> = (0..buf.frames()).map(|i| [0, 1].map(|c| (buf.channels[c][i] * 32768.0) as i16)).collect(); - assert_eq!(ints, frames); - let mut d = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap(); - d.seek(5).unwrap(); - let block = d.next_block().unwrap().unwrap(); - assert_eq!((block.channels[0][0] * 32768.0) as i16, frames[5][0]); - } - /// ALAC in Matroska seeks to the exact frame: packet starts come from the frame length, not /// from the millisecond timestamps (packet 1 starts at frame 4096, stored as 85 ms = 4080). #[test] diff --git a/crates/audio/src/read/symph.rs b/crates/audio/src/read/symph.rs index 189503804b..4bf9d622ae 100644 --- a/crates/audio/src/read/symph.rs +++ b/crates/audio/src/read/symph.rs @@ -4,24 +4,18 @@ use std::borrow::Cow; use std::io::{Cursor, Seek, SeekFrom}; use std::panic::{AssertUnwindSafe, catch_unwind}; -use symphonia::core::audio::Channels; use symphonia::core::codecs::audio::AudioDecoder; -use symphonia::core::codecs::audio::well_known::{ - CODEC_ID_AAC, CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS, - CODEC_ID_ALAC, CODEC_ID_FLAC, CODEC_ID_MP1, CODEC_ID_MP2, CODEC_ID_MP3, CODEC_ID_OPUS, CODEC_ID_PCM_ALAW, CODEC_ID_PCM_F32BE, CODEC_ID_PCM_F32LE, - CODEC_ID_PCM_F64BE, CODEC_ID_PCM_F64BE_PLANAR, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_MULAW, CODEC_ID_PCM_S32LE, CODEC_ID_VORBIS, -}; -use symphonia::core::codecs::audio::{AudioCodecId, AudioCodecParameters, AudioDecoderOptions, CODEC_ID_NULL_AUDIO}; +use symphonia::core::codecs::audio::AudioDecoderOptions; +use symphonia::core::codecs::audio::well_known::CODEC_ID_ALAC; use symphonia::core::errors::Error as SymError; -use symphonia::core::formats::probe::{Hint, ProbeOptions, ProbeableFormat, Score, Scoreable}; -use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo, Track}; -use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions, ScopedStream}; +use symphonia::core::formats::probe::Hint; +use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo}; +use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions}; use symphonia::core::meta::MetadataOptions; use symphonia::core::units::{TimeBase, Timestamp}; -use super::id3v2_len; use crate::pcm::{MAX_DECODE_SAMPLES, be_u32}; -use crate::{AudioBuffer, AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; +use crate::{AudioBuffer, AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result}; /// The most frames a packet may declare: decoders allocate a packet's frames up front, and ALAC /// takes its frame length from the file (encoders use 4096). @@ -36,45 +30,6 @@ const GAP_BLOCK_FRAMES: u64 = 1 << 16; /// otherwise claim gigabytes before a sample is decoded (64 MiB of `f32`). Ports soundcraft #1332. const MAX_PACKET_SAMPLES: u64 = 1 << 24; -/// How far [`first_marker`] looks for the first format marker: the same 1 MiB a default symphonia -/// probe scans. -const MAX_PREFIX_SCAN: usize = 1 << 20; - -/// How many MPEG/ADTS candidates [`first_marker`] may hand to the readers' expensive `Scoreable` -/// implementations. A crafted 1 MiB prefix of repeated sync markers otherwise asks for hundreds -/// of thousands of scores, each allowed up to symphonia's 16 KiB score depth. Once the budget is -/// spent, the scan stops at the next audio candidate: a container-like byte string later in an -/// unscored audio payload must not become authoritative. A container marker reached first is still -/// checked; an unchecked one the probe selects is refused after probing. -const MAX_AUDIO_SCORE_ATTEMPTS: usize = 256; - -/// A per-scan budget for `Scoreable::score` calls. Taking a slot consumes it even when the score -/// rejects the candidate, so a stream of false syncs cannot multiply the work. -struct ScoreBudget { - used: usize, -} - -impl ScoreBudget { - /// Start a scan with no expensive score attempts spent. - fn new() -> Self { - Self { used: 0 } - } - - /// Spend one score attempt, returning false once the per-scan budget is exhausted. - fn take(&mut self) -> bool { - if self.exhausted() { - return false; - } - self.used = self.used.saturating_add(1); - true - } - - /// Whether no attempt is left for this scan. - fn exhausted(&self) -> bool { - self.used >= MAX_AUDIO_SCORE_ATTEMPTS - } -} - /// Turn a symphonia error into the audio layer's error, keeping "unsupported" and "too large" /// distinct from a malformed file. fn map_err(e: SymError) -> AudioError { @@ -115,261 +70,10 @@ fn decoder_options() -> AudioDecoderOptions { AudioDecoderOptions::default().gapless(true) } -/// The first byte after any ID3v2 tags at the start of `b`. Symphonia's tag reader allocates -/// whatever a frame claims, so the tags are skipped, not read: they are not used here. -fn skip_id3v2(b: &[u8]) -> usize { - let mut at = 0usize; - loop { - match b.get(at..).and_then(id3v2_len) { - Some(n) if n > 0 => at = at.saturating_add(n), - _ => return at, - } - } -} - -/// The first format marker the probe can reach from `start`, within its 1 MiB scan limit. -#[derive(Clone, Copy)] -enum FirstMarker { - Flac(usize), - Caf(usize), - Mp4(usize), - Wav(usize), - /// MPEG audio, Ogg, Matroska or AIFF: formats with no separate container size check. - Audio, -} - -/// What the preflight container checks covered before the probe built a reader. -enum Precheck { - /// A zero-frame FLAC: returned without a reader, because Symphonia 0.6's reader needs a first - /// audio frame to resynchronize to. - Empty(AudioInfo), - /// The size checks ran for the container the probe reports under this short name. - Checked(&'static str), - /// As `Checked`, for a FLAC stream with this layout, which symphonia's reader does not parse. - Flac(&'static str, Option), - /// No container size check was needed. - Unchecked, -} - -/// Probe short names whose demuxer allocates from sizes in the file, so the matching container -/// check has to run before the stream is decoded. -const SIZE_CHECKED_PROBE_FORMATS: &[&str] = &["caf", "flac", "isomp4", "wave"]; - -/// The container markers to check for the family `detected` names. `None` is a raw audio stream -/// (MP3, Ogg, AIFF), whose payload may contain container-like bytes: the unrestricted scan below -/// finds a container only when one starts the stream, before any audio marker. -fn container_markers(detected: Option) -> Option<&'static [&'static [u8; 4]]> { - match detected { - // RF64 and BW64 are the >4 GiB RIFF forms. - Some(Container::Wav) => Some(&[b"RIFF", b"RF64", b"BW64"]), - Some(Container::Flac) => Some(&[b"fLaC"]), - Some(Container::Caf) => Some(&[b"caff"]), - // MP4/M4A put `ftyp` after the first atom's size field (an `.aac` name may hide one). - Some(Container::Mp4 | Container::QuickTime | Container::Adts) => Some(&[b"ftyp"]), - Some(Container::Aiff | Container::MpegAudio | Container::Ogg) => None, - // Unknown files may carry junk before the container; symphonia's probe scans for markers. - _ => Some(&[b"caff", b"ftyp", b"fLaC", b"RIFF"]), - } -} - -/// The probe short name a container marker stands for. -fn expected_probe_format(marker: &[u8; 4]) -> &'static str { - match marker { - b"caff" => "caf", - // The isomp4 reader reads the `ftyp` atom. - b"ftyp" => "isomp4", - b"fLaC" => "flac", - // RIFF, RF64 and BW64. - _ => "wave", - } -} - -/// Find the first marker of `markers` at or after `at`, within symphonia's probe depth. A RIFF -/// form other than WAVE is skipped, as the probe skips it and reads a WAVE behind it. -fn find_container_marker<'a>(bytes: &[u8], at: usize, markers: &'a [&'static [u8; 4]]) -> Option<(usize, &'a [u8; 4])> { - let end = bytes.len().min(at.saturating_add(MAX_PREFIX_SCAN)); - for pos in at..end.saturating_sub(3) { - let window = bytes.get(pos..pos + 4)?; - if let Some(marker) = markers.iter().find(|marker| window == marker.as_slice()) { - if matches!(*marker, b"RIFF" | b"RF64" | b"BW64") && bytes.get(pos + 8..pos + 12) != Some(&b"WAVE"[..]) { - continue; - } - return Some((pos, *marker)); - } - } - None -} - -/// The scan variant for a marker found by [`find_container_marker`], with the probe short name its -/// size check stands for. `ftyp` sits four bytes into its atom, so the MP4 check starts there. -fn marker_kind(at: usize, marker: &[u8; 4]) -> (FirstMarker, &'static str) { - match marker { - b"fLaC" => (FirstMarker::Flac(at), expected_probe_format(marker)), - b"caff" => (FirstMarker::Caf(at), expected_probe_format(marker)), - b"ftyp" => (FirstMarker::Mp4(at.saturating_sub(4)), expected_probe_format(marker)), - _ => (FirstMarker::Wav(at), expected_probe_format(marker)), - } -} - -/// The probe short name a container scan variant stands for. -fn marker_name(marker: FirstMarker) -> &'static str { - match marker { - FirstMarker::Flac(_) => "flac", - FirstMarker::Caf(_) => "caf", - FirstMarker::Mp4(_) => "isomp4", - FirstMarker::Wav(_) => "wave", - FirstMarker::Audio => "", - } -} - -/// Whether `rest` starts with one of `R`'s exact registered probe markers. -fn has_probe_marker>(rest: &[u8]) -> bool { - R::probe_data().iter().any(|data| data.spec.markers.iter().any(|marker| rest.starts_with(marker))) -} - -/// Score `R` at `at` exactly as symphonia's private probe does: `Supported` wins, EOF and every -/// other scoring error mean "not this format", while a real I/O error aborts the probe. -fn scores_supported(stream: &mut MediaSourceStream<'_>, at: usize, depth: u16) -> Result { - stream.seek(SeekFrom::Start(u64::try_from(at).unwrap_or(u64::MAX)))?; - match R::score(ScopedStream::new(stream, u64::from(depth))) { - Ok(Score::Supported(_)) => Ok(true), - Err(SymError::IoError(e)) if e.kind() != std::io::ErrorKind::UnexpectedEof => Err(AudioError::Malformed(e.to_string())), - _ => Ok(false), - } -} - -/// Whether `b[at..]` is an MPEG/ADTS candidate the probe would actually select: an exact -/// `probe_data()` marker and a `Supported` score from the same reader. A loose `0xFFEx` pair is -/// not enough: `0xFFE0` is neither a registered marker nor a valid frame, so it must not stop the -/// scan before a later FLAC/CAF/MP4 candidate. -fn audio_sync_at<'a>(b: &'a [u8], at: usize, stream: &mut Option>, budget: &mut ScoreBudget) -> Result { - let rest = b.get(at..).unwrap_or_default(); - let adts = has_probe_marker::>(rest); - let mpa = has_probe_marker::>(rest); - if !adts && !mpa { - return Ok(false); - } - if stream.is_none() { - *stream = Some(MediaSourceStream::new(Box::new(Cursor::new(b)), MediaSourceStreamOptions::default())); - } - let Some(mss) = stream.as_mut() else { return Ok(false) }; - let depth = ProbeOptions::default().max_score_depth; - if adts && budget.take() && scores_supported::>(mss, at, depth)? { - return Ok(true); - } - if mpa && budget.take() && scores_supported::>(mss, at, depth)? { - return Ok(true); - } - Ok(false) -} - -/// Find the first marker that can start a container or audio stream. Symphonia's `Probe::probe` -/// constructs the reader itself and exposes no pre-construction hook, while checking every magic -/// in the scan window would validate bytes the probe never reaches (for example a valid MP3's -/// audio payload). Stopping at the first marker avoids that: it is the candidate the probe selects -/// for FLAC, CAF, MP4, Ogg and Matroska, and for WAV/AIFF once their full form is verified below. -/// MPEG/ADTS candidates are checked with the readers' own `probe_data()`/`Scoreable` APIs, so a -/// false sync byte pair cannot stop the scan. If that scoring budget runs out, the scan stops at -/// the next audio candidate instead of trusting a container-like byte string later in the unscored -/// audio payload. A container marker reached before any such candidate is still preflighted; if -/// the probe selects a size-checked container the scan did not check, `open` refuses it. -/// -/// WAV candidates include RF64/BW64 so `check_info` can run, although symphonia 0.6 registers only -/// the RIFF marker. Native PCM RF64/BW64 is parsed by `wav::parse` before this path; a foreign -/// RF64/BW64 stream therefore remains unsupported by the probe rather than misdetected. -fn first_marker(b: &[u8], start: usize) -> Result> { - first_marker_with_budget(b, start, &mut ScoreBudget::new()) -} - -/// [`first_marker`] with an explicit score budget, so a test can prove a prefix crowded with -/// false sync markers performs only the bounded number of reader scores. -fn first_marker_with_budget(b: &[u8], start: usize, budget: &mut ScoreBudget) -> Result> { - let end = b.len().min(start.saturating_add(MAX_PREFIX_SCAN)); - let mut at = start; - let mut audio_probe = None; - while at.saturating_add(4) <= end { - let rest = b.get(at..).unwrap_or_default(); - if rest.get(..4) == Some(b"fLaC".as_slice()) { - return Ok(Some(FirstMarker::Flac(at))); - } - if rest.get(..4) == Some(b"caff".as_slice()) { - return Ok(Some(FirstMarker::Caf(at))); - } - if rest.get(..4) == Some(b"OggS".as_slice()) || rest.get(..4) == Some(b"\x1A\x45\xDF\xA3".as_slice()) || super::aiff::is_aiff(rest) { - return Ok(Some(FirstMarker::Audio)); - } - if super::wav::is_wav(rest) { - return Ok(Some(FirstMarker::Wav(at))); - } - if let (Some(&b0), Some(&b1)) = (b.get(at), b.get(at + 1)) - && b0 == 0xFF - && b1 & 0xE0 == 0xE0 - { - // A candidate after the cap cannot be scored. Stop rather than let a container-like - // byte string later in an unscored audio payload become preflight-authoritative; the - // probe will select the reader, and `open` refuses an unchecked size-checked one. - if budget.exhausted() { - return Ok(None); - } - if audio_sync_at(b, at, &mut audio_probe, budget)? { - return Ok(Some(FirstMarker::Audio)); - } - } - if rest.get(4..8) == Some(b"ftyp".as_slice()) { - return Ok(Some(FirstMarker::Mp4(at))); - } - at += 1; - } - Ok(None) -} - -/// Run the early size checks on the container the probe can select. `start` is the first byte -/// after leading ID3v2 tags. A zero-frame FLAC is returned as an empty stream because Symphonia -/// 0.6's reader requires a first audio frame to resynchronize to. -fn precheck(b: &[u8], start: usize, detected: Option) -> Result { - let any_marker = |b: &[u8], start: usize| -> Result> { - Ok(match first_marker(b, start)? { - // Stop at the first marker of any kind, so container magic incidental to an audio - // payload is not mistaken for the stream's container. - Some(FirstMarker::Audio) | None => None, - Some(marker) => Some((marker, marker_name(marker))), - }) - }; - let found = match container_markers(detected) { - // Follow the detection: check the first marker of the family it names, so a misleading - // marker cannot let a differently sized container reach the probe unchecked. A detection - // is only a hint, though: when the stream holds none of its markers (a FLAC behind a - // `.mp3` name), the probe can still select another container, which is checked here. - Some(markers) => match find_container_marker(b, start, markers) { - Some((at, marker)) => Some(marker_kind(at, marker)), - None => any_marker(b, start)?, - }, - None => any_marker(b, start)?, - }; - let Some((marker, expected)) = found else { return Ok(Precheck::Unchecked) }; - match marker { - FirstMarker::Flac(at) => { - super::flac::check_metadata(b, at)?; - if let Some(info) = super::flac::empty_stream_info(b, at) { - return Ok(Precheck::Empty(info)); - } - Ok(Precheck::Flac(expected, super::flac::layout(b, at))) - } - FirstMarker::Caf(at) => { - super::caf::check(b, at)?; - Ok(Precheck::Checked(expected)) - } - FirstMarker::Mp4(at) => { - super::mp4::check(b, at)?; - Ok(Precheck::Checked(expected)) - } - FirstMarker::Wav(at) => { - super::wav::check_info(b, at)?; - Ok(Precheck::Checked(expected)) - } - FirstMarker::Audio => Ok(Precheck::Unchecked), - } -} +mod map; +mod precheck; +use map::{audio_params, audio_tracks, codec_id_of, info_of}; +use precheck::{MAX_PREFIX_SCAN, Precheck, SIZE_CHECKED_PROBE_FORMATS, precheck, skip_id3v2}; /// `block` without the frames still to drop after a seek landed before its target; `None` when /// that is all of it. @@ -433,133 +137,6 @@ fn open(bytes: Cow<'_, [u8]>, detected: Option) -> Result { Ok(Opened::Reader(reader, preread)) } -/// The codec symphonia reports, as a [`CodecId`]. -fn codec_id_of(c: AudioCodecId) -> CodecId { - match c { - c if (CODEC_ID_PCM_S32LE..=CODEC_ID_PCM_F64BE_PLANAR).contains(&c) => CodecId::Pcm, - c if c == CODEC_ID_PCM_ALAW => CodecId::ALaw, - c if c == CODEC_ID_PCM_MULAW => CodecId::MuLaw, - c if [CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS] - .contains(&c) => - { - CodecId::Adpcm - } - c if c == CODEC_ID_FLAC => CodecId::Flac, - c if c == CODEC_ID_ALAC => CodecId::Alac, - c if c == CODEC_ID_AAC => CodecId::Aac, - c if c == CODEC_ID_MP1 => CodecId::Mp1, - c if c == CODEC_ID_MP2 => CodecId::Mp2, - c if c == CODEC_ID_MP3 => CodecId::Mp3, - c if c == CODEC_ID_OPUS => CodecId::Opus, - c if c == CODEC_ID_VORBIS => CodecId::Vorbis, - _ => CodecId::Unknown, - } -} - -/// The container a symphonia reader stands for, refined by the detection (which tells MP4 from -/// QuickTime and Matroska from WebM). -fn container_of(short_name: &str, detected: Option) -> Container { - match short_name { - "wave" => Container::Wav, - "aiff" => Container::Aiff, - "flac" => Container::Flac, - "caf" => Container::Caf, - "ogg" => Container::Ogg, - "isomp4" if detected == Some(Container::QuickTime) => Container::QuickTime, - "isomp4" => Container::Mp4, - "matroska" if detected == Some(Container::WebM) => Container::WebM, - "matroska" => Container::Matroska, - "mp1" | "mp2" | "mp3" => Container::MpegAudio, - "aac" | "adts" => Container::Adts, - _ => detected.unwrap_or(Container::MpegAudio), - } -} - -/// The speakers of symphonia's channel description; its first 18 position bits are the WAV mask -/// bits, and its decoded planes follow them. -fn layout_of(channels: Option<&Channels>) -> ChannelLayout { - match channels { - Some(Channels::Positioned(p)) => { - let bits = p.bits(); - match u32::try_from(bits) { - Ok(mask) if mask != 0 => ChannelLayout::from_mask(mask), - _ => ChannelLayout::unordered(bits.count_ones() as u16), - } - } - Some(c) => ChannelLayout::unordered(crate::layout::count(c.count())), - None => ChannelLayout::unordered(0), - } -} - -/// The stored sample format, using the codec and its declared bit depth. Lossy and unusual -/// codecs decode to `Compressed`. -fn sample_format_of(p: &AudioCodecParameters) -> SampleFormat { - let c = p.codec; - if c == CODEC_ID_PCM_F32LE || c == CODEC_ID_PCM_F32BE { - return SampleFormat::Float32; - } - if c == CODEC_ID_PCM_F64LE || c == CODEC_ID_PCM_F64BE { - return SampleFormat::Float64; - } - let lossy = [ - CODEC_ID_MP1, - CODEC_ID_MP2, - CODEC_ID_MP3, - CODEC_ID_AAC, - CODEC_ID_VORBIS, - CODEC_ID_OPUS, - CODEC_ID_ADPCM_MS, - CODEC_ID_ADPCM_IMA_WAV, - CODEC_ID_ADPCM_IMA_QT, - CODEC_ID_ADPCM_G722, - CODEC_ID_ADPCM_G726, - CODEC_ID_ADPCM_G726LE, - CODEC_ID_PCM_ALAW, - CODEC_ID_PCM_MULAW, - ]; - let lossless = !lossy.contains(&c); - match (lossless, p.bits_per_sample) { - (true, Some(1..=8)) => SampleFormat::Int8, - (true, Some(9..=16)) => SampleFormat::Int16, - (true, Some(17..=24)) => SampleFormat::Int24, - (true, Some(25..=32)) => SampleFormat::Int32, - _ => SampleFormat::Compressed, - } -} - -/// The audio parameters of `track`, if it carries any. -fn audio_params(track: &Track) -> Option<&AudioCodecParameters> { - track.codec_params.as_ref()?.audio() -} - -/// The audio tracks with a decodable codec. -fn audio_tracks(reader: &dyn FormatReader) -> impl Iterator { - reader.tracks().iter().filter(|t| audio_params(t).is_some_and(|p| p.codec != CODEC_ID_NULL_AUDIO)) -} - -/// The `n`-th audio track (the first when `None`), counting an Ogg file's `streams` in file order -/// when they are known. With no `n`, the first stream symphonia has a track for: it has none for -/// some of the codecs `tracks` lists. -fn pick_track<'a>(reader: &'a dyn FormatReader, streams: &[(u32, Option)], n: Option) -> Option<&'a Track> { - let with_serial = |serial: u32| audio_tracks(reader).find(|t| t.id == serial); - match n { - _ if streams.is_empty() => audio_tracks(reader).nth(n.unwrap_or(0)), - Some(n) => with_serial(streams.get(n)?.0), - None => streams.iter().find_map(|s| with_serial(s.0)), - } -} - -/// The `n`-th audio track (see [`pick_track`]), with the stream information the UI shows. -fn info_of(reader: &dyn FormatReader, detected: Option, ogg_streams: &[(u32, Option)], n: Option) -> Result<(u32, AudioInfo)> { - let container = container_of(reader.format_info().short_name, detected); - let track = pick_track(reader, ogg_streams, n).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?; - let p = audio_params(track).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?; - let sample_rate = p.sample_rate.filter(|&r| r > 0).ok_or_else(|| AudioError::Malformed("unknown sample rate".into()))?; - let layout = layout_of(p.channels.as_ref()); - let frames = track.num_frames.unwrap_or(0); - Ok((track.id, AudioInfo::new(container, codec_id_of(p.codec), sample_format_of(p), sample_rate, layout, frames))) -} - /// A demux error ends the decode; it is only an error when nothing was decoded yet. fn demux_failure(frames: u64, e: SymError) -> Result<()> { if frames == 0 { @@ -886,132 +463,3 @@ pub(crate) fn tracks(bytes: Cow<'_, [u8]>, detected: Option) -> Resul .collect()) }) } - -#[cfg(test)] -mod tests { - use super::*; - use symphonia::core::codecs::audio::well_known::{ - CODEC_ID_AAC, CODEC_ID_ADPCM_MS, CODEC_ID_ALAC, CODEC_ID_FLAC, CODEC_ID_MP3, CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_S16LE, - CODEC_ID_VORBIS, - }; - - /// Build codec parameters for a test, optionally declaring a bit depth. - fn params(codec: AudioCodecId, bits_per_sample: Option) -> AudioCodecParameters { - let mut params = AudioCodecParameters::new(); - params.for_codec(codec); - if let Some(bits) = bits_per_sample { - params.with_bits_per_sample(bits); - } - params - } - - /// symphonia's codec ids map to ours, PCM by its id range. - #[test] - fn codecs_map_to_codec_ids() { - assert_eq!(codec_id_of(CODEC_ID_FLAC), CodecId::Flac); - assert_eq!(codec_id_of(CODEC_ID_MP3), CodecId::Mp3); - assert_eq!(codec_id_of(CODEC_ID_ALAC), CodecId::Alac); - assert_eq!(codec_id_of(CODEC_ID_VORBIS), CodecId::Vorbis); - assert_eq!(codec_id_of(CODEC_ID_PCM_S16LE), CodecId::Pcm); - assert_eq!(codec_id_of(CODEC_ID_PCM_F64LE), CodecId::Pcm); - assert_eq!(codec_id_of(CODEC_ID_ADPCM_MS), CodecId::Adpcm); - assert_eq!(codec_id_of(CODEC_ID_PCM_ALAW), CodecId::ALaw); - } - - /// The reader names the container; the detection refines MP4 into QuickTime and Matroska into WebM. - #[test] - fn readers_map_to_containers() { - assert_eq!(container_of("isomp4", None), Container::Mp4); - assert_eq!(container_of("isomp4", Some(Container::QuickTime)), Container::QuickTime); - assert_eq!(container_of("matroska", Some(Container::WebM)), Container::WebM); - assert_eq!(container_of("mp3", None), Container::MpegAudio); - assert_eq!(container_of("wave", Some(Container::Wav)), Container::Wav); - } - - /// PCM and FLAC keep their declared bit depth; lossy codecs report `Compressed` regardless of their decoded - /// width. - #[test] - fn sample_formats_keep_their_depth_and_lossy_marker() { - assert_eq!(sample_format_of(¶ms(CODEC_ID_PCM_S16LE, Some(16))), SampleFormat::Int16); - assert_eq!(sample_format_of(¶ms(CODEC_ID_FLAC, Some(24))), SampleFormat::Int24); - assert_eq!(sample_format_of(¶ms(CODEC_ID_FLAC, Some(8))), SampleFormat::Int8); - assert_eq!(sample_format_of(¶ms(CODEC_ID_FLAC, Some(32))), SampleFormat::Int32); - assert_eq!(sample_format_of(¶ms(CODEC_ID_PCM_F32LE, Some(32))), SampleFormat::Float32); - assert_eq!(sample_format_of(¶ms(CODEC_ID_PCM_F64LE, Some(64))), SampleFormat::Float64); - // Lossy codecs report no fixed bit depth, whatever their decoded sample format is. - assert_eq!(sample_format_of(¶ms(CODEC_ID_AAC, Some(16))), SampleFormat::Compressed); - assert_eq!(sample_format_of(¶ms(CODEC_ID_ADPCM_MS, Some(4))), SampleFormat::Compressed); - assert_eq!(sample_format_of(¶ms(CODEC_ID_ALAC, None)), SampleFormat::Compressed); - } - - /// Decoder options keep gapless trimming enabled so the encoder delay and padding reported by the demuxer are - /// removed. - #[test] - fn gapless_decoding_stays_enabled() { - assert!(decoder_options().gapless); - } - - /// A complete MPEG frame header is a candidate; loose or unregistered sync pairs are rejected before scoring, - /// while a registered but truncated header is rejected by the reader's score after consuming a budget slot. - #[test] - fn only_the_readers_own_audio_markers_are_candidates() { - /// Whether the preflight would score `b` as an audio candidate at offset 0. - fn candidate(b: &[u8]) -> bool { - let mut stream = None; - let mut budget = ScoreBudget::new(); - matches!(audio_sync_at(b, 0, &mut stream, &mut budget), Ok(true)) - } - let mut mp3_frame = vec![0u8; 417]; - mp3_frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); // MPEG-1 Layer III, 128 kbps, 44.1 kHz - assert!(candidate(&[&mp3_frame[..], &mp3_frame].concat())); - for false_sync in [vec![0xFF, 0xE0, 0x00], vec![0xFF, 0xF0, 0x00], vec![0xFF, 0xFB, 0xF0, 0x00]] { - assert!(!candidate(&false_sync), "{false_sync:?} is not a probe candidate"); - } - } - - /// A prefix made of false MPEG sync markers must not ask the readers to score every byte - /// position: the per-scan budget caps the expensive work. A cheap container marker reached - /// before the next audio candidate is still found, but once the cap is spent an audio - /// candidate stops the scan so later payload magic cannot be preflight-authoritative. - #[test] - fn a_prefix_crowded_with_sync_markers_scores_only_the_budget() { - let mut crowded = vec![0u8; 1 << 16]; - for pair in crowded.as_chunks_mut::<2>().0 { - pair.copy_from_slice(&[0xFF, 0xE2]); - } - let mut budget = ScoreBudget::new(); - assert!(matches!(first_marker_with_budget(&crowded, 0, &mut budget), Ok(None))); - assert_eq!(budget.used, MAX_AUDIO_SCORE_ATTEMPTS, "no candidate after the cap is scored"); - - // At the cap boundary, with no later audio candidate, the cheap marker is still found. - let mut at_cap: Vec = (0..MAX_AUDIO_SCORE_ATTEMPTS).flat_map(|_| [0xFFu8, 0xE2]).collect(); - at_cap.extend_from_slice(b"fLaC"); - let mut budget = ScoreBudget::new(); - assert!( - matches!(first_marker_with_budget(&at_cap, 0, &mut budget), Ok(Some(FirstMarker::Flac(_)))), - "a container marker reached before the next audio candidate is still found" - ); - assert_eq!(budget.used, MAX_AUDIO_SCORE_ATTEMPTS); - - // One more false candidate between the cap and the magic makes the scan stop unchecked: - // the same magic could instead sit in a valid audio payload. - let mut after_candidate = at_cap[..2 * MAX_AUDIO_SCORE_ATTEMPTS].to_vec(); - after_candidate.extend_from_slice(&[0xFF, 0xE2]); - after_candidate.extend_from_slice(b"fLaC"); - let mut budget = ScoreBudget::new(); - assert!(matches!(first_marker_with_budget(&after_candidate, 0, &mut budget), Ok(None)), "an audio candidate after the cap stops the scan"); - assert_eq!(budget.used, MAX_AUDIO_SCORE_ATTEMPTS); - } - - /// ID3v2 sizes are read in their 7-bit syncsafe form; consecutive tags are skipped by their declared sizes, and - /// the v2.3 reserved footer bit does not extend a tag. - #[test] - fn leading_id3_tags_are_skipped_by_their_declared_size() { - let tag = [&b"ID3\x04\0\0\0\0\0\x05"[..], b"hello"].concat(); - assert_eq!(skip_id3v2(&[&tag[..], &tag[..]].concat()), 30); - assert_eq!(skip_id3v2(b"fLaC"), 0); - // The 10-byte footer flag exists only in v2.4; the same bit in v2.3 is reserved. - assert_eq!(id3v2_len(b"ID3\x03\0\x10\0\0\0\0"), Some(10)); - assert_eq!(id3v2_len(b"ID3\x04\0\x10\0\0\0\0"), Some(20)); - } -} diff --git a/crates/audio/src/read/symph/map.rs b/crates/audio/src/read/symph/map.rs new file mode 100644 index 0000000000..5cf6587260 --- /dev/null +++ b/crates/audio/src/read/symph/map.rs @@ -0,0 +1,143 @@ +//! Mapping from symphonia codec, layout and track types to the crate's own. + +use crate::{AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; +use symphonia::core::audio::Channels; +use symphonia::core::codecs::audio::well_known::{ + CODEC_ID_AAC, CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS, + CODEC_ID_ALAC, CODEC_ID_FLAC, CODEC_ID_MP1, CODEC_ID_MP2, CODEC_ID_MP3, CODEC_ID_OPUS, CODEC_ID_PCM_ALAW, CODEC_ID_PCM_F32BE, CODEC_ID_PCM_F32LE, + CODEC_ID_PCM_F64BE, CODEC_ID_PCM_F64BE_PLANAR, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_MULAW, CODEC_ID_PCM_S32LE, CODEC_ID_VORBIS, +}; +use symphonia::core::codecs::audio::{AudioCodecId, AudioCodecParameters, CODEC_ID_NULL_AUDIO}; +use symphonia::core::formats::{FormatReader, Track}; + +/// The codec symphonia reports, as a [`CodecId`]. +pub(super) fn codec_id_of(c: AudioCodecId) -> CodecId { + match c { + c if (CODEC_ID_PCM_S32LE..=CODEC_ID_PCM_F64BE_PLANAR).contains(&c) => CodecId::Pcm, + c if c == CODEC_ID_PCM_ALAW => CodecId::ALaw, + c if c == CODEC_ID_PCM_MULAW => CodecId::MuLaw, + c if [CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS] + .contains(&c) => + { + CodecId::Adpcm + } + c if c == CODEC_ID_FLAC => CodecId::Flac, + c if c == CODEC_ID_ALAC => CodecId::Alac, + c if c == CODEC_ID_AAC => CodecId::Aac, + c if c == CODEC_ID_MP1 => CodecId::Mp1, + c if c == CODEC_ID_MP2 => CodecId::Mp2, + c if c == CODEC_ID_MP3 => CodecId::Mp3, + c if c == CODEC_ID_OPUS => CodecId::Opus, + c if c == CODEC_ID_VORBIS => CodecId::Vorbis, + _ => CodecId::Unknown, + } +} + +/// The container a symphonia reader stands for, refined by the detection (which tells MP4 from +/// QuickTime and Matroska from WebM). +pub(super) fn container_of(short_name: &str, detected: Option) -> Container { + match short_name { + "wave" => Container::Wav, + "aiff" => Container::Aiff, + "flac" => Container::Flac, + "caf" => Container::Caf, + "ogg" => Container::Ogg, + "isomp4" if detected == Some(Container::QuickTime) => Container::QuickTime, + "isomp4" => Container::Mp4, + "matroska" if detected == Some(Container::WebM) => Container::WebM, + "matroska" => Container::Matroska, + "mp1" | "mp2" | "mp3" => Container::MpegAudio, + "aac" | "adts" => Container::Adts, + _ => detected.unwrap_or(Container::MpegAudio), + } +} + +/// The speakers of symphonia's channel description; its first 18 position bits are the WAV mask +/// bits, and its decoded planes follow them. +fn layout_of(channels: Option<&Channels>) -> ChannelLayout { + match channels { + Some(Channels::Positioned(p)) => { + let bits = p.bits(); + match u32::try_from(bits) { + Ok(mask) if mask != 0 => ChannelLayout::from_mask(mask), + _ => ChannelLayout::unordered(bits.count_ones() as u16), + } + } + Some(c) => ChannelLayout::unordered(crate::layout::count(c.count())), + None => ChannelLayout::unordered(0), + } +} + +/// The stored sample format, using the codec and its declared bit depth. Lossy and unusual +/// codecs decode to `Compressed`. +pub(super) fn sample_format_of(p: &AudioCodecParameters) -> SampleFormat { + let c = p.codec; + if c == CODEC_ID_PCM_F32LE || c == CODEC_ID_PCM_F32BE { + return SampleFormat::Float32; + } + if c == CODEC_ID_PCM_F64LE || c == CODEC_ID_PCM_F64BE { + return SampleFormat::Float64; + } + let lossy = [ + CODEC_ID_MP1, + CODEC_ID_MP2, + CODEC_ID_MP3, + CODEC_ID_AAC, + CODEC_ID_VORBIS, + CODEC_ID_OPUS, + CODEC_ID_ADPCM_MS, + CODEC_ID_ADPCM_IMA_WAV, + CODEC_ID_ADPCM_IMA_QT, + CODEC_ID_ADPCM_G722, + CODEC_ID_ADPCM_G726, + CODEC_ID_ADPCM_G726LE, + CODEC_ID_PCM_ALAW, + CODEC_ID_PCM_MULAW, + ]; + let lossless = !lossy.contains(&c); + match (lossless, p.bits_per_sample) { + (true, Some(1..=8)) => SampleFormat::Int8, + (true, Some(9..=16)) => SampleFormat::Int16, + (true, Some(17..=24)) => SampleFormat::Int24, + (true, Some(25..=32)) => SampleFormat::Int32, + _ => SampleFormat::Compressed, + } +} + +/// The audio parameters of `track`, if it carries any. +pub(super) fn audio_params(track: &Track) -> Option<&AudioCodecParameters> { + track.codec_params.as_ref()?.audio() +} + +/// The audio tracks with a decodable codec. +pub(super) fn audio_tracks(reader: &dyn FormatReader) -> impl Iterator { + reader.tracks().iter().filter(|t| audio_params(t).is_some_and(|p| p.codec != CODEC_ID_NULL_AUDIO)) +} + +/// The `n`-th audio track (the first when `None`), counting an Ogg file's `streams` in file order +/// when they are known. With no `n`, the first stream symphonia has a track for: it has none for +/// some of the codecs `tracks` lists. +fn pick_track<'a>(reader: &'a dyn FormatReader, streams: &[(u32, Option)], n: Option) -> Option<&'a Track> { + let with_serial = |serial: u32| audio_tracks(reader).find(|t| t.id == serial); + match n { + _ if streams.is_empty() => audio_tracks(reader).nth(n.unwrap_or(0)), + Some(n) => with_serial(streams.get(n)?.0), + None => streams.iter().find_map(|s| with_serial(s.0)), + } +} + +/// The `n`-th audio track (see [`pick_track`]), with the stream information the UI shows. +pub(super) fn info_of( + reader: &dyn FormatReader, + detected: Option, + ogg_streams: &[(u32, Option)], + n: Option, +) -> Result<(u32, AudioInfo)> { + let container = container_of(reader.format_info().short_name, detected); + let track = pick_track(reader, ogg_streams, n).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?; + let p = audio_params(track).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?; + let sample_rate = p.sample_rate.filter(|&r| r > 0).ok_or_else(|| AudioError::Malformed("unknown sample rate".into()))?; + let layout = layout_of(p.channels.as_ref()); + let frames = track.num_frames.unwrap_or(0); + Ok((track.id, AudioInfo::new(container, codec_id_of(p.codec), sample_format_of(p), sample_rate, layout, frames))) +} diff --git a/crates/audio/src/read/symph/precheck.rs b/crates/audio/src/read/symph/precheck.rs new file mode 100644 index 0000000000..6697f802c0 --- /dev/null +++ b/crates/audio/src/read/symph/precheck.rs @@ -0,0 +1,303 @@ +//! Container preflight: ID3v2 skipping, the budgeted marker scan and the size checks that run before probing. + +use super::super::id3v2_len; +use crate::{AudioError, AudioInfo, ChannelLayout, Container, Result}; +use std::io::{Cursor, Seek, SeekFrom}; +use symphonia::core::errors::Error as SymError; +use symphonia::core::formats::probe::{ProbeOptions, ProbeableFormat, Score, Scoreable}; +use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions, ScopedStream}; + +/// How far [`first_marker`] looks for the first format marker: the same 1 MiB a default symphonia +/// probe scans. +pub(super) const MAX_PREFIX_SCAN: usize = 1 << 20; + +/// How many MPEG/ADTS candidates [`first_marker`] may hand to the readers' expensive `Scoreable` +/// implementations. A crafted 1 MiB prefix of repeated sync markers otherwise asks for hundreds +/// of thousands of scores, each allowed up to symphonia's 16 KiB score depth. Once the budget is +/// spent, the scan stops at the next audio candidate: a container-like byte string later in an +/// unscored audio payload must not become authoritative. A container marker reached first is still +/// checked; an unchecked one the probe selects is refused after probing. +pub(super) const MAX_AUDIO_SCORE_ATTEMPTS: usize = 256; + +/// A per-scan budget for `Scoreable::score` calls. Taking a slot consumes it even when the score +/// rejects the candidate, so a stream of false syncs cannot multiply the work. +pub(super) struct ScoreBudget { + pub(super) used: usize, +} + +impl ScoreBudget { + /// Start a scan with no expensive score attempts spent. + pub(super) fn new() -> Self { + Self { used: 0 } + } + + /// Spend one score attempt, returning false once the per-scan budget is exhausted. + pub(super) fn take(&mut self) -> bool { + if self.exhausted() { + return false; + } + self.used = self.used.saturating_add(1); + true + } + + /// Whether no attempt is left for this scan. + pub(super) fn exhausted(&self) -> bool { + self.used >= MAX_AUDIO_SCORE_ATTEMPTS + } +} + +/// The first byte after any ID3v2 tags at the start of `b`. Symphonia's tag reader allocates +/// whatever a frame claims, so the tags are skipped, not read: they are not used here. +pub(super) fn skip_id3v2(b: &[u8]) -> usize { + let mut at = 0usize; + loop { + match b.get(at..).and_then(id3v2_len) { + Some(n) if n > 0 => at = at.saturating_add(n), + _ => return at, + } + } +} + +/// The first format marker the probe can reach from `start`, within its 1 MiB scan limit. +#[derive(Clone, Copy)] +pub(super) enum FirstMarker { + Flac(usize), + Caf(usize), + Mp4(usize), + Wav(usize), + /// MPEG audio, Ogg, Matroska or AIFF: formats with no separate container size check. + Audio, +} + +/// What the preflight container checks covered before the probe built a reader. +pub(super) enum Precheck { + /// A zero-frame FLAC: returned without a reader, because Symphonia 0.6's reader needs a first + /// audio frame to resynchronize to. + Empty(AudioInfo), + /// The size checks ran for the container the probe reports under this short name. + Checked(&'static str), + /// As `Checked`, for a FLAC stream with this layout, which symphonia's reader does not parse. + Flac(&'static str, Option), + /// No container size check was needed. + Unchecked, +} + +/// Probe short names whose demuxer allocates from sizes in the file, so the matching container +/// check has to run before the stream is decoded. +pub(super) const SIZE_CHECKED_PROBE_FORMATS: &[&str] = &["caf", "flac", "isomp4", "wave"]; + +/// The container markers to check for the family `detected` names. `None` is a raw audio stream +/// (MP3, Ogg, AIFF), whose payload may contain container-like bytes: the unrestricted scan below +/// finds a container only when one starts the stream, before any audio marker. +fn container_markers(detected: Option) -> Option<&'static [&'static [u8; 4]]> { + match detected { + // RF64 and BW64 are the >4 GiB RIFF forms. + Some(Container::Wav) => Some(&[b"RIFF", b"RF64", b"BW64"]), + Some(Container::Flac) => Some(&[b"fLaC"]), + Some(Container::Caf) => Some(&[b"caff"]), + // MP4/M4A put `ftyp` after the first atom's size field (an `.aac` name may hide one). + Some(Container::Mp4 | Container::QuickTime | Container::Adts) => Some(&[b"ftyp"]), + Some(Container::Aiff | Container::MpegAudio | Container::Ogg) => None, + // Unknown files may carry junk before the container; symphonia's probe scans for markers. + _ => Some(&[b"caff", b"ftyp", b"fLaC", b"RIFF"]), + } +} + +/// The probe short name a container marker stands for. +fn expected_probe_format(marker: &[u8; 4]) -> &'static str { + match marker { + b"caff" => "caf", + // The isomp4 reader reads the `ftyp` atom. + b"ftyp" => "isomp4", + b"fLaC" => "flac", + // RIFF, RF64 and BW64. + _ => "wave", + } +} + +/// Find the first marker of `markers` at or after `at`, within symphonia's probe depth. A RIFF +/// form other than WAVE is skipped, as the probe skips it and reads a WAVE behind it. +fn find_container_marker<'a>(bytes: &[u8], at: usize, markers: &'a [&'static [u8; 4]]) -> Option<(usize, &'a [u8; 4])> { + let end = bytes.len().min(at.saturating_add(MAX_PREFIX_SCAN)); + for pos in at..end.saturating_sub(3) { + let window = bytes.get(pos..pos + 4)?; + if let Some(marker) = markers.iter().find(|marker| window == marker.as_slice()) { + if matches!(*marker, b"RIFF" | b"RF64" | b"BW64") && bytes.get(pos + 8..pos + 12) != Some(&b"WAVE"[..]) { + continue; + } + return Some((pos, *marker)); + } + } + None +} + +/// The scan variant for a marker found by [`find_container_marker`], with the probe short name its +/// size check stands for. `ftyp` sits four bytes into its atom, so the MP4 check starts there. +fn marker_kind(at: usize, marker: &[u8; 4]) -> (FirstMarker, &'static str) { + match marker { + b"fLaC" => (FirstMarker::Flac(at), expected_probe_format(marker)), + b"caff" => (FirstMarker::Caf(at), expected_probe_format(marker)), + b"ftyp" => (FirstMarker::Mp4(at.saturating_sub(4)), expected_probe_format(marker)), + _ => (FirstMarker::Wav(at), expected_probe_format(marker)), + } +} + +/// The probe short name a container scan variant stands for. +fn marker_name(marker: FirstMarker) -> &'static str { + match marker { + FirstMarker::Flac(_) => "flac", + FirstMarker::Caf(_) => "caf", + FirstMarker::Mp4(_) => "isomp4", + FirstMarker::Wav(_) => "wave", + FirstMarker::Audio => "", + } +} + +/// Whether `rest` starts with one of `R`'s exact registered probe markers. +fn has_probe_marker>(rest: &[u8]) -> bool { + R::probe_data().iter().any(|data| data.spec.markers.iter().any(|marker| rest.starts_with(marker))) +} + +/// Score `R` at `at` exactly as symphonia's private probe does: `Supported` wins, EOF and every +/// other scoring error mean "not this format", while a real I/O error aborts the probe. +fn scores_supported(stream: &mut MediaSourceStream<'_>, at: usize, depth: u16) -> Result { + stream.seek(SeekFrom::Start(u64::try_from(at).unwrap_or(u64::MAX)))?; + match R::score(ScopedStream::new(stream, u64::from(depth))) { + Ok(Score::Supported(_)) => Ok(true), + Err(SymError::IoError(e)) if e.kind() != std::io::ErrorKind::UnexpectedEof => Err(AudioError::Malformed(e.to_string())), + _ => Ok(false), + } +} + +/// Whether `b[at..]` is an MPEG/ADTS candidate the probe would actually select: an exact +/// `probe_data()` marker and a `Supported` score from the same reader. A loose `0xFFEx` pair is +/// not enough: `0xFFE0` is neither a registered marker nor a valid frame, so it must not stop the +/// scan before a later FLAC/CAF/MP4 candidate. +pub(super) fn audio_sync_at<'a>(b: &'a [u8], at: usize, stream: &mut Option>, budget: &mut ScoreBudget) -> Result { + let rest = b.get(at..).unwrap_or_default(); + let adts = has_probe_marker::>(rest); + let mpa = has_probe_marker::>(rest); + if !adts && !mpa { + return Ok(false); + } + if stream.is_none() { + *stream = Some(MediaSourceStream::new(Box::new(Cursor::new(b)), MediaSourceStreamOptions::default())); + } + let Some(mss) = stream.as_mut() else { return Ok(false) }; + let depth = ProbeOptions::default().max_score_depth; + if adts && budget.take() && scores_supported::>(mss, at, depth)? { + return Ok(true); + } + if mpa && budget.take() && scores_supported::>(mss, at, depth)? { + return Ok(true); + } + Ok(false) +} + +/// Find the first marker that can start a container or audio stream. Symphonia's `Probe::probe` +/// constructs the reader itself and exposes no pre-construction hook, while checking every magic +/// in the scan window would validate bytes the probe never reaches (for example a valid MP3's +/// audio payload). Stopping at the first marker avoids that: it is the candidate the probe selects +/// for FLAC, CAF, MP4, Ogg and Matroska, and for WAV/AIFF once their full form is verified below. +/// MPEG/ADTS candidates are checked with the readers' own `probe_data()`/`Scoreable` APIs, so a +/// false sync byte pair cannot stop the scan. If that scoring budget runs out, the scan stops at +/// the next audio candidate instead of trusting a container-like byte string later in the unscored +/// audio payload. A container marker reached before any such candidate is still preflighted; if +/// the probe selects a size-checked container the scan did not check, `open` refuses it. +/// +/// WAV candidates include RF64/BW64 so `check_info` can run, although symphonia 0.6 registers only +/// the RIFF marker. Native PCM RF64/BW64 is parsed by `wav::parse` before this path; a foreign +/// RF64/BW64 stream therefore remains unsupported by the probe rather than misdetected. +fn first_marker(b: &[u8], start: usize) -> Result> { + first_marker_with_budget(b, start, &mut ScoreBudget::new()) +} + +/// [`first_marker`] with an explicit score budget, so a test can prove a prefix crowded with +/// false sync markers performs only the bounded number of reader scores. +pub(super) fn first_marker_with_budget(b: &[u8], start: usize, budget: &mut ScoreBudget) -> Result> { + let end = b.len().min(start.saturating_add(MAX_PREFIX_SCAN)); + let mut at = start; + let mut audio_probe = None; + while at.saturating_add(4) <= end { + let rest = b.get(at..).unwrap_or_default(); + if rest.get(..4) == Some(b"fLaC".as_slice()) { + return Ok(Some(FirstMarker::Flac(at))); + } + if rest.get(..4) == Some(b"caff".as_slice()) { + return Ok(Some(FirstMarker::Caf(at))); + } + if rest.get(..4) == Some(b"OggS".as_slice()) || rest.get(..4) == Some(b"\x1A\x45\xDF\xA3".as_slice()) || super::super::aiff::is_aiff(rest) { + return Ok(Some(FirstMarker::Audio)); + } + if super::super::wav::is_wav(rest) { + return Ok(Some(FirstMarker::Wav(at))); + } + if let (Some(&b0), Some(&b1)) = (b.get(at), b.get(at + 1)) + && b0 == 0xFF + && b1 & 0xE0 == 0xE0 + { + // A candidate after the cap cannot be scored. Stop rather than let a container-like + // byte string later in an unscored audio payload become preflight-authoritative; the + // probe will select the reader, and `open` refuses an unchecked size-checked one. + if budget.exhausted() { + return Ok(None); + } + if audio_sync_at(b, at, &mut audio_probe, budget)? { + return Ok(Some(FirstMarker::Audio)); + } + } + if rest.get(4..8) == Some(b"ftyp".as_slice()) { + return Ok(Some(FirstMarker::Mp4(at))); + } + at += 1; + } + Ok(None) +} + +/// Run the early size checks on the container the probe can select. `start` is the first byte +/// after leading ID3v2 tags. A zero-frame FLAC is returned as an empty stream because Symphonia +/// 0.6's reader requires a first audio frame to resynchronize to. +pub(super) fn precheck(b: &[u8], start: usize, detected: Option) -> Result { + let any_marker = |b: &[u8], start: usize| -> Result> { + Ok(match first_marker(b, start)? { + // Stop at the first marker of any kind, so container magic incidental to an audio + // payload is not mistaken for the stream's container. + Some(FirstMarker::Audio) | None => None, + Some(marker) => Some((marker, marker_name(marker))), + }) + }; + let found = match container_markers(detected) { + // Follow the detection: check the first marker of the family it names, so a misleading + // marker cannot let a differently sized container reach the probe unchecked. A detection + // is only a hint, though: when the stream holds none of its markers (a FLAC behind a + // `.mp3` name), the probe can still select another container, which is checked here. + Some(markers) => match find_container_marker(b, start, markers) { + Some((at, marker)) => Some(marker_kind(at, marker)), + None => any_marker(b, start)?, + }, + None => any_marker(b, start)?, + }; + let Some((marker, expected)) = found else { return Ok(Precheck::Unchecked) }; + match marker { + FirstMarker::Flac(at) => { + super::super::flac::check_metadata(b, at)?; + if let Some(info) = super::super::flac::empty_stream_info(b, at) { + return Ok(Precheck::Empty(info)); + } + Ok(Precheck::Flac(expected, super::super::flac::layout(b, at))) + } + FirstMarker::Caf(at) => { + super::super::caf::check(b, at)?; + Ok(Precheck::Checked(expected)) + } + FirstMarker::Mp4(at) => { + super::super::mp4::check(b, at)?; + Ok(Precheck::Checked(expected)) + } + FirstMarker::Wav(at) => { + super::super::wav::check_info(b, at)?; + Ok(Precheck::Checked(expected)) + } + FirstMarker::Audio => Ok(Precheck::Unchecked), + } +} diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index c1552d7e29..2cc5202780 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -252,12 +252,25 @@ struct DataChunk { declared: u64, } +/// Ids of the chunks that commonly follow a `data` chunk: metadata a writer appends after the +/// samples, sometimes without correcting the RIFF size. +const TRAILING_IDS: [&[u8; 4]; 12] = [b"LIST", b"fact", b"id3 ", b"ID3 ", b"cue ", b"JUNK", b"PEAK", b"bext", b"smpl", b"iXML", b"inst", b"PAD "]; + /// Bytes of audio a `data` chunk holds: leniently, whatever is present when the size is wrong or /// the recording was never finalised. +/// +/// A size of 0 is an empty chunk when only whole chunks follow it and either the RIFF size is the +/// file's or the first of them has an id that follows audio (#2123: a `LIST` chunk appended after +/// the RIFF size was written). Otherwise it is a recording that was never finalised, and what +/// follows is audio: the bytes of PCM can spell any id, but rarely whole chunks to the end. fn data_chunk_len(src: &Src<'_>, c: DataChunk) -> u64 { + if c.size32 != 0 || c.is_rf64 { + return c.declared.min(c.remaining); + } let finished = u64::from(src.le_u32(4).unwrap_or(0)) + 8 == src.size(); - let empty = c.size32 == 0 && !c.is_rf64 && finished && only_chunks_follow(src, c.body); - if c.size32 == 0 && !c.is_rf64 && !empty { c.remaining } else { c.declared.min(c.remaining) } + let metadata_follows = src.tag(c.body).is_some_and(|id| TRAILING_IDS.contains(&&id)); + let empty = (finished || metadata_follows) && only_chunks_follow(src, c.body); + if empty { 0 } else { c.remaining } } /// The sample layout of a `fmt` chunk, `None` for a format we do not read natively. diff --git a/crates/audio/src/track.rs b/crates/audio/src/track.rs index d39e55abfb..cc1d9d7079 100644 --- a/crates/audio/src/track.rs +++ b/crates/audio/src/track.rs @@ -932,8 +932,6 @@ pub(crate) fn opus_layout(head: &opus::OpusHead) -> ChannelLayout { #[cfg(test)] mod tests { use super::*; - use crate::PcmFormat; - /// An MP3 frame of silence: MPEG-1 Layer III, 128 kbit/s, 44.1 kHz, stereo, 417 bytes. #[cfg(feature = "mp3-decode")] fn mp3_frame() -> Vec { @@ -997,22 +995,6 @@ mod tests { assert_eq!(dec.conceal(None).unwrap().frames(), 1152, "after a seek"); } - #[test] - fn pcm_tracks_decode_in_wav_order() { - let params = CodecParams::new(CodecId::Pcm).with_sample_rate(48_000).with_channels(2).with_pcm(PcmFormat::int(16, true, false)); - let mut dec = TrackDecoder::new(¶ms, &[]).unwrap(); - assert_eq!((dec.codec(), dec.sample_rate(), dec.layout()), (CodecId::Pcm, 48_000, ChannelLayout::STEREO)); - let block = dec.decode(&[0x00, 0x40, 0x00, 0xC0]).unwrap(); - assert_eq!(block.channels, vec![vec![0.5], vec![-0.5]]); - assert_eq!(dec.conceal(None).unwrap().frames(), 1); - // a reset forgets the last packet's length - dec.reset(); - assert_eq!(dec.conceal(None).unwrap().frames(), 0); - // silence past the decode limit is an error, not shorter silence - dec.last_frames = usize::try_from(crate::pcm::MAX_DECODE_SAMPLES / 2 + 1).unwrap(); - assert!(matches!(dec.conceal(None), Err(AudioError::TooLarge(_)))); - } - #[cfg(feature = "opus-decode")] #[test] fn opus_conceals_a_damaged_packet_at_its_own_length() { @@ -1105,81 +1087,6 @@ mod tests { assert_eq!(dec.conceal(None).unwrap().frames(), 2048); } - /// A signalled output rate that is not twice the core's is not upsampled to: the core plays. - #[cfg(feature = "aac-decode")] - #[test] - fn an_sbr_rate_other_than_twice_the_core_plays_the_core() { - // AOT 5, 24 kHz, mono, extension 44.1 kHz, core AOT 2 - let asc = { - use craft_media::bitstream::BitWriter; - let mut bw = BitWriter::new(); - for (value, bits) in [(5, 5), (6, 4), (1, 4), (4, 4), (2, 5), (0, 3)] { - bw.write_bits(value, bits); - } - bw.finish() - }; - let dec = TrackDecoder::new(&aac_params().with_extradata(asc), &[]).unwrap(); - assert_eq!((dec.codec(), dec.sample_rate(), dec.frames_per_packet()), (CodecId::Aac, 24_000, Some(1024))); - } - - #[cfg(feature = "aac-decode")] - #[test] - fn adts_frames_of_another_format_or_several_blocks_conceal_at_their_length() { - let frame = adts_frame(2); - let mut dec = TrackDecoder::new(&aac_params(), &[&frame]).unwrap(); - // sampling frequency index 4 where the stream has 3 - let mut other = frame.clone(); - other[2] = (other[2] & 0xC3) | (4 << 2); - assert!(matches!(dec.decode(&other), Err(AudioError::Malformed(_)))); - assert_eq!(dec.conceal(Some(&other)).unwrap().frames(), 1024); - let mut blocks = frame.clone(); - blocks[6] |= 2; // three raw data blocks - assert!(matches!(dec.decode(&blocks), Err(AudioError::Unsupported(_)))); - assert_eq!(dec.conceal(Some(&blocks)).unwrap().frames(), 3072); - // the profile and the channel configuration are part of the format too - let mut main = frame.clone(); - main[2] &= 0x3F; // profile 0: Main - assert!(matches!(dec.decode(&main), Err(AudioError::Malformed(_)))); - let mut mono = frame.clone(); - mono[3] = (mono[3] & 0x3F) | (1 << 6); - assert!(matches!(dec.decode(&mono), Err(AudioError::Malformed(_)))); - } - - /// With extradata, a header's differing fields are not a format change (ADTS in MP4 with a - /// program config element in its AudioSpecificConfig, or channel configuration 0 in its headers). - #[cfg(feature = "aac-decode")] - #[test] - fn extradata_decides_the_format_of_adts_packets() { - let frame = adts_frame(0); - let mut stereo = adts_frame(2); - let params = aac_params().with_extradata(aac::AudioSpecificConfig::lc(3, 2).to_bytes().unwrap()); - let mut dec = TrackDecoder::new(¶ms, &[]).unwrap(); - assert_eq!(dec.decode(&stereo).unwrap().channels.len(), 2); - stereo[3] &= 0x3F; // channel configuration 0 in the header - stereo[2] &= 0xFE; - assert_eq!(dec.decode(&stereo).unwrap().channels.len(), 2); - assert!(dec.decode(&frame).is_err(), "elements the configuration does not have"); - } - - /// One damaged header at the start of a stream does not decide its format. - #[cfg(feature = "aac-decode")] - #[test] - fn the_adts_format_is_the_one_most_of_the_lookahead_shares() { - let good = adts_frame(2); - let mut damaged = good.clone(); - damaged[2] = (damaged[2] & 0xC3) | (4 << 2); // sampling frequency index 4 where the rest have 3 - let lookahead: [&[u8]; 4] = [&damaged, &good, &good, &good]; - let mut dec = TrackDecoder::new(&aac_params(), &lookahead).unwrap(); - assert_eq!(dec.sample_rate(), 48_000); - assert!(dec.decode(&damaged).is_err()); - assert_eq!(dec.decode(&good).unwrap().frames(), 1024); - // on a tie, the earlier one - let tied: [&[u8]; 2] = [&good, &damaged]; - assert_eq!(TrackDecoder::new(&aac_params(), &tied).unwrap().sample_rate(), 48_000); - #[cfg(feature = "decode-native")] - assert_eq!((adts_frame_count(&good), adts_frame_count(&good.repeat(2)), adts_frame_count(&[0; 8])), (1, 2, 0)); - } - /// `au` as a stereo ADTS frame at 48 kHz (channel configuration `channel_config`). #[cfg(feature = "aac-decode")] fn adts_of(au: &[u8], channel_config: u8) -> Vec { @@ -1214,31 +1121,6 @@ mod tests { aac::ProgramConfig { front: vec![(true, 0)], ..Default::default() } } - /// HE-AAC whose SBR data first appears in a later frame of a lookahead packet is found. - #[cfg(feature = "aac-decode")] - #[test] - fn sbr_in_a_later_adts_frame_of_a_packet_is_found() { - use craft_media::bitstream::BitWriter; - let unit = |sbr: bool| { - let mut bw = BitWriter::new(); - bw.write_bits(0, 7); // ID_SCE, tag 0 - bw.write_bits(0, 22); - if sbr { - bw.write_bits(6, 3); // ID_FIL - bw.write_bits(1, 4); - bw.write_bits(13, 4); // EXT_SBR_DATA - bw.write_bits(0, 4); - } - bw.write_bits(7, 3); - bw.finish() - }; - let frame = |au: &[u8]| [&aac::AdtsHeader::write(2, 7, 1, au.len(), 0x7FF).unwrap()[..], au].concat(); - let packet = [frame(&unit(false)), frame(&unit(true))].concat(); - let params = aac_params().with_extradata(vec![0x13, 0x88]); - let dec = TrackDecoder::new(¶ms, &[&packet]).unwrap(); - assert_eq!((dec.codec(), dec.sample_rate()), (CodecId::HeAac, 44_100)); - } - /// A packet whose later frame fails leaves the decoder as a failed single frame does. #[cfg(feature = "aac-decode")] #[test] @@ -1255,17 +1137,6 @@ mod tests { assert_eq!(dec.decode(&plain).unwrap().channels.len(), 3); } - /// Frames of one packet with different channel counts are an error, not a short packet. - #[cfg(feature = "aac-decode")] - #[test] - fn a_channel_count_change_inside_a_packet_is_an_error() { - let first = adts_frame(0); - let mut dec = TrackDecoder::new(&aac_params(), &[&first]).unwrap(); - let change = adts_of(&au_of(Some(&stereo_pce()), &[(1, 0)]), 0); - assert!(matches!(dec.decode(&[first.clone(), change.clone()].concat()), Err(AudioError::Malformed(_)))); - assert_eq!(dec.conceal(Some(&[first, change].concat())).unwrap().frames(), 2048); - } - /// Whole frames before a damaged or truncated end of a packet still decode. #[cfg(feature = "aac-decode")] #[test] @@ -1304,26 +1175,6 @@ mod tests { assert!(matches!(TrackDecoder::new(&aac_params(), &[&bare]), Err(AudioError::Malformed(_)))); } - #[cfg(feature = "ac3-decode")] - #[test] - fn e_ac3_packets_are_as_long_as_all_their_syncframes() { - use crate::ac3::tests::single_block_eac3; - let params = CodecParams::new(CodecId::Eac3); - // One block per packet: 256 frames, known before any packet is decoded. - let one = single_block_eac3(true); - let dec = TrackDecoder::new(¶ms, &[&one]).unwrap(); - assert_eq!((dec.codec(), dec.frames_per_packet()), (CodecId::Eac3, Some(256))); - // Six one-block syncframes to a packet (as MP4 groups them): 1536. - let six = [one.clone(), (0..5).flat_map(|_| single_block_eac3(false)).collect()].concat(); - let mut dec = TrackDecoder::new(¶ms, &[&six]).unwrap(); - assert_eq!(dec.frames_per_packet(), Some(1536)); - assert_eq!(dec.decode(&six).unwrap().channels[0].len(), 1536); - // A damaged packet conceals at the length of all its syncframes. - dec.reset(); - assert_eq!(dec.conceal(Some(&six)).unwrap().channels[0].len(), 1536); - assert_eq!(dec.conceal(Some(&one)).unwrap().channels[0].len(), 256); - } - #[cfg(feature = "ac3-decode")] #[test] fn a_packet_decoded_in_part_keeps_the_length_lost_packets_are_concealed_at() { @@ -1340,62 +1191,6 @@ mod tests { assert_eq!(dec.frames_per_packet(), Some(1536), "a damaged packet does not make the packets' lengths differ"); } - #[cfg(feature = "ac3-decode")] - #[test] - fn e_ac3_packets_of_different_lengths_or_short_syncframes_are_not_indexed() { - use crate::ac3::tests::single_block_eac3; - let params = CodecParams::new(CodecId::Eac3); - let one = single_block_eac3(true); - let two = [single_block_eac3(true), single_block_eac3(false)].concat(); - // Packets of 256 and 512 frames: a packet's index does not give its position. - let dec = TrackDecoder::new(¶ms, &[&one, &one, &two]).unwrap(); - assert_eq!(dec.frames_per_packet(), None); - // Known only once decoded: from then on too. - let mut dec = TrackDecoder::new(¶ms, &[&one]).unwrap(); - assert_eq!(dec.frames_per_packet(), Some(256)); - dec.decode(&two).unwrap(); - assert_eq!(dec.frames_per_packet(), None); - // One-block syncframes may reuse exponents from any syncframe before them. - assert_eq!(TrackDecoder::new(¶ms, &[&one]).unwrap().preroll(), usize::MAX); - } - - #[test] - fn codecs_without_a_packet_decoder_are_unsupported() { - for codec in [CodecId::Vorbis, CodecId::H264] { - assert!(matches!(TrackDecoder::new(&CodecParams::new(codec), &[]), Err(AudioError::Unsupported(_))), "{codec:?}"); - } - // A codec whose feature is off names the feature. - #[cfg(not(feature = "aac-decode"))] - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Aac), &[]), Err(AudioError::Unsupported(m)) if m.contains("aac-decode"))); - #[cfg(not(feature = "alac-decode"))] - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac), &[]), Err(AudioError::Unsupported(m)) if m.contains("alac-decode"))); - #[cfg(not(feature = "flac-decode"))] - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Flac), &[]), Err(AudioError::Unsupported(m)) if m.contains("flac-decode"))); - #[cfg(not(feature = "opus-decode"))] - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Opus), &[]), Err(AudioError::Unsupported(m)) if m.contains("opus-decode"))); - #[cfg(not(feature = "mp3-decode"))] - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Mp3), &[]), Err(AudioError::Unsupported(m)) if m.contains("mp3-decode"))); - // PCM needs its sample format. - assert!(TrackDecoder::new(&CodecParams::new(CodecId::Pcm).with_channels(2).with_sample_rate(48_000), &[]).is_err()); - } - - #[cfg(feature = "alac-decode")] - #[test] - fn alac_needs_a_sample_rate() { - let cookie = alac::SpecificConfig::new(0, 2, 16, 4096).to_bytes(); - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac).with_extradata(cookie.clone()), &[]), Err(AudioError::Malformed(_)))); - let dec = TrackDecoder::new(&CodecParams::new(CodecId::Alac).with_extradata(cookie).with_sample_rate(32_000), &[]).unwrap(); - assert_eq!(dec.sample_rate(), 32_000); - } - - #[cfg(feature = "alac-decode")] - #[test] - fn alac_needs_its_cookie() { - assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac), &[]), Err(AudioError::Malformed(_)))); - let bad = CodecParams::new(CodecId::Alac).with_extradata(vec![0; 10]); - assert!(matches!(TrackDecoder::new(&bad, &[]), Err(AudioError::Malformed(_)))); - } - /// ALAC 5.1 comes out in WAV order at full scale, and a lost packet is as long as the last. #[cfg(all(feature = "alac-decode", feature = "alac-encode"))] #[test] diff --git a/crates/audio/src/write/flac/crc.rs b/crates/audio/src/write/flac/crc.rs index 0cc4869b53..86095b0f0f 100644 --- a/crates/audio/src/write/flac/crc.rs +++ b/crates/audio/src/write/flac/crc.rs @@ -43,15 +43,3 @@ pub fn crc8(data: &[u8]) -> u8 { pub fn crc16(data: &[u8]) -> u16 { data.iter().fold(0u16, |c, &b| (c << 8) ^ T16[usize::from((c >> 8) as u8 ^ b)]) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn check_values() { - // the standard check value of each polynomial over "123456789" - assert_eq!(crc8(b"123456789"), 0xF4); - assert_eq!(crc16(b"123456789"), 0xFEE8); - } -} diff --git a/crates/audio/src/write/flac/encoder.rs b/crates/audio/src/write/flac/encoder.rs index a7a453d20c..fb0e057ccf 100644 --- a/crates/audio/src/write/flac/encoder.rs +++ b/crates/audio/src/write/flac/encoder.rs @@ -270,20 +270,3 @@ impl Encoder { data } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn streaminfo_holds_a_36_bit_total_and_leaves_a_larger_one_unknown() { - let enc = Encoder::new(EncoderConfig::new(48_000, 1, 16)).unwrap(); - let total = |t| { - let si = enc.streaminfo_with(0, 0, t, [0; 16]); - (u64::from(si[13] & 0x0F) << 32) | u64::from(u32::from_be_bytes([si[14], si[15], si[16], si[17]])) - }; - assert_eq!(total((1 << 36) - 1), (1 << 36) - 1); - assert_eq!(total((1 << 35) + 5), (1 << 35) + 5); - assert_eq!(total(1 << 36), 0); - } -} diff --git a/crates/audio/src/write/flac/frame.rs b/crates/audio/src/write/flac/frame.rs index 06a1bf5f65..3c3cdd2b3e 100644 --- a/crates/audio/src/write/flac/frame.rs +++ b/crates/audio/src/write/flac/frame.rs @@ -196,51 +196,3 @@ pub fn write(spec: &FrameSpec) -> Vec { out.extend_from_slice(&crc.to_be_bytes()); out } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn coded_numbers() { - let code = |v| { - let mut o = Vec::new(); - coded_number(v, &mut o); - o - }; - assert_eq!(code(0), [0]); - assert_eq!(code(0x7F), [0x7F]); - assert_eq!(code(0x80), [0xC2, 0x80]); - assert_eq!(code(0x7FF), [0xDF, 0xBF]); - assert_eq!(code(0x800), [0xE0, 0xA0, 0x80]); - assert_eq!(code(0xFFFF), [0xEF, 0xBF, 0xBF]); - assert_eq!(code(0x1_0000), [0xF0, 0x90, 0x80, 0x80]); - assert_eq!(code(0x7FFF_FFFF), [0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF]); - assert_eq!(code(0xF_FFFF_FFFF), [0xFE, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF]); - } - - #[test] - fn sample_sizes_are_named_in_the_header_except_32_bits() { - assert_eq!([8, 12, 16, 20, 24, 32].map(sample_size_code), [1, 2, 4, 5, 6, 0]); - } - - #[test] - fn sample_rates_in_the_table_have_their_codes() { - let table = [88_200, 176_400, 192_000, 8_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 96_000]; - for (rate, code) in table.into_iter().zip(1..) { - assert_eq!(sample_rate_code(rate), (code, None), "{rate}"); - } - } - - #[test] - fn sample_rates_outside_the_table_are_named_in_the_header() { - assert_eq!(sample_rate_code(48_000), (10, None)); - assert_eq!(sample_rate_code(64_000), (12, Some((64, 8)))); - assert_eq!(sample_rate_code(11_025), (13, Some((11_025, 16)))); - assert_eq!(sample_rate_code(37_800), (13, Some((37_800, 16)))); - assert_eq!(sample_rate_code(352_800), (14, Some((35_280, 16)))); - assert_eq!(sample_rate_code(655_350), (14, Some((65_535, 16)))); - // neither whole kHz, at most 65535 Hz, nor whole tens of Hz - assert_eq!(sample_rate_code(100_001), (0, None)); - } -} diff --git a/crates/audio/src/write/flac/golden_tests.rs b/crates/audio/src/write/flac/golden_tests.rs deleted file mode 100644 index ec5ef5620e..0000000000 --- a/crates/audio/src/write/flac/golden_tests.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! Golden hashes of the encoder output for a fixed set of synthetic signals. -//! -//! Encoder speed-ups must not change a single output byte, so this pins the encoded frames and the -//! final STREAMINFO (which holds the MD5 of the input) of 64 deterministic cases: noise, sines, silence, -//! full-scale squares, wasted bits and a music-like mix, at 8/12/16/24/32 bits, 1 to 4 channels, -//! several block sizes (with a short final frame), and levels 0 to 8. -//! -//! The hashes were captured from FilmCraft's encoder (68919ed8), which this one came from, before the per-order -//! predictor kernels and merged partition sums were added. Six cases differ from FilmCraft's table -//! on purpose and were captured here, identical before and after those changes: the five `wasted` -//! cases (this encoder codes wasted bits) and `click-32b` (32-bit stereo is coded as independent -//! channels). Signals use integer arithmetic only. The -//! encoder itself uses `f64` (window, autocorrelation), so a platform whose libm rounds `cos` -//! differently could in principle differ; the hashes were made on x86-64 Linux. -//! -//! An intentional change of the output (for example a different LPC order choice) regenerates the -//! table with `cargo test -p craft-audio --features flac-encode golden -- --ignored --nocapture print`. - -use super::encoder::{Encoder, EncoderConfig}; - -struct Rng(u64); -impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } -} - -/// FNV-1a, 64 bit. -fn fnv(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)) -} - -/// A sine-like wave from an integer resonator: `y[n] = 2cos(w) y[n-1] - y[n-2]` in Q14, amplitude `amp`. -fn resonator(n: usize, coef_q14: i64, amp: i64) -> Vec { - let (mut y1, mut y2) = (amp, amp * 9 / 10); - (0..n) - .map(|_| { - let y = ((coef_q14 * y1) >> 14) - y2; - y2 = y1; - y1 = y.clamp(-amp, amp); - y1 - }) - .collect() -} - -/// One channel of `kind` at `bps` bits, values always inside the sample range. -fn signal(kind: &str, n: usize, bps: u8, seed: u64) -> Vec { - let max = (1i64 << (bps - 1)) - 1; - let mut r = Rng(seed | 1); - let sine = resonator(n, 32_000 - (seed as i64 % 7) * 900, max / 2); - let sine2 = resonator(n, 27_000, max / 4); - (0..n) - .map(|i| { - let noise = |r: &mut Rng, amp: i64| (r.next() >> 11) as i64 % (2 * amp + 1) - amp; - let v = match kind { - "noise" => noise(&mut r, max), - "sine" => sine[i], - "music" => sine[i] + sine2[i] + noise(&mut r, max / 64), - "square" => { - if (i / 37) % 2 == 0 { - max - } else { - -max - 1 - } - } - // low 3 bits always zero (wasted bits) on a quiet sine - "wasted" => (sine[i] / 8) * 8, - "click" => { - if i == n / 2 { - max - } else { - 0 - } - } - // a silent stretch between two noisy ones - "gap" => { - if (n / 3..2 * n / 3).contains(&i) { - 0 - } else { - noise(&mut r, max / 3) - } - } - _ => 0, - }; - v.clamp(-max - 1, max) as i32 - }) - .collect() -} - -struct Case { - kind: &'static str, - bps: u8, - channels: u8, - block: u16, - level: u8, - samples: usize, - chunk: usize, -} - -impl Case { - fn name(&self) -> String { - format!("{}-{}b-{}ch-bs{}-L{}-n{}-c{}", self.kind, self.bps, self.channels, self.block, self.level, self.samples, self.chunk) - } - - /// Hash of every frame and the final STREAMINFO (the file header carries the crate version). - fn hash(&self) -> u64 { - let planar: Vec> = - (0..self.channels).map(|c| signal(self.kind, self.samples, self.bps, 0x9E37_79B9 + u64::from(c) * 7919)).collect(); - let mut cfg = EncoderConfig::new(44_100, self.channels, self.bps); - cfg.block_size = self.block; - cfg.level = self.level; - let mut enc = Encoder::new(cfg).expect("valid config"); - let mut out = Vec::new(); - let mut at = 0; - while at < self.samples { - let end = (at + self.chunk).min(self.samples); - let parts: Vec<&[i32]> = planar.iter().map(|c| &c[at..end]).collect(); - out.extend(enc.encode(&parts).expect("samples in range")); - at = end; - } - out.extend(enc.finish()); - out.extend_from_slice(&enc.streaminfo()); - fnv(&out) - } -} - -fn cases() -> Vec { - const KINDS: [&str; 8] = ["noise", "sine", "music", "square", "wasted", "click", "gap", "silence"]; - const BPS: [u8; 5] = [8, 12, 16, 24, 32]; - const BLOCKS: [u16; 5] = [16, 576, 1000, 4096, 4608]; - let mut v = Vec::new(); - // every kind at every bit depth; channels, block size and level rotate through their ranges - for (k, kind) in KINDS.iter().enumerate() { - for (b, &bps) in BPS.iter().enumerate() { - let block = BLOCKS[(k + 2 * b) % BLOCKS.len()]; - let samples = 2 * usize::from(block) + 37 + (k * 101 + b * 13) % 700; - v.push(Case { - kind, - bps, - channels: 1 + ((k + b) % 4) as u8, - block, - level: ((k * 5 + b * 3) % 9) as u8, - samples, - chunk: 1 + (k * 977 + b * 311) % 5000, - }); - } - } - // all levels on stereo music at 16 and 24 bits, and the 4096 blocks real files use - for level in 0..=8 { - for bps in [16u8, 24] { - v.push(Case { kind: "music", bps, channels: 2, block: 4096, level, samples: 9000, chunk: 4096 }); - } - } - // 4 channels, short blocks and a block that is not a power of two - for level in [0u8, 5, 8] { - v.push(Case { kind: "noise", bps: 16, channels: 4, block: 1000, level, samples: 2500, chunk: 777 }); - v.push(Case { kind: "gap", bps: 16, channels: 2, block: 576, level, samples: 2000, chunk: 2000 }); - } - v -} - -/// (case name, hash), captured on FilmCraft 68919ed8. -const GOLDEN: &[(&str, u64)] = &[ - ("noise-8b-1ch-bs16-L0-n69-c1", 0x69cba522cd83247a), - ("noise-12b-2ch-bs1000-L3-n2050-c312", 0xbd8aa93b40b5b078), - ("noise-16b-3ch-bs4608-L6-n9279-c623", 0xe1969205fcfb7d74), - ("noise-24b-4ch-bs576-L0-n1228-c934", 0xd444404f16d70169), - ("noise-32b-1ch-bs4096-L3-n8281-c1245", 0x45ca92f380216922), - ("sine-8b-2ch-bs576-L5-n1290-c978", 0x135ff72f3b74e284), - ("sine-12b-3ch-bs4096-L8-n8343-c1289", 0x95c4d0720e59d826), - ("sine-16b-4ch-bs16-L2-n196-c1600", 0x84bf0b50ef111b77), - ("sine-24b-1ch-bs1000-L5-n2177-c1911", 0xf4cb2b792c100e1c), - ("sine-32b-2ch-bs4608-L8-n9406-c2222", 0x45aaf5d6091ecc85), - ("music-8b-3ch-bs1000-L1-n2239-c1955", 0x3540af737b613e03), - ("music-12b-4ch-bs4608-L4-n9468-c2266", 0x07d8c76385536b70), - ("music-16b-1ch-bs576-L7-n1417-c2577", 0x1b5300d81d3a8eac), - ("music-24b-2ch-bs4096-L1-n8470-c2888", 0x570f7821161e7932), - ("music-32b-3ch-bs16-L4-n323-c3199", 0xb720fd6b9fb8d7c9), - ("square-8b-4ch-bs4096-L6-n8532-c2932", 0xf1e702077432c346), - ("square-12b-1ch-bs16-L0-n385-c3243", 0x2820a440a7465bb2), - ("square-16b-2ch-bs1000-L3-n2366-c3554", 0x827ee17d45c447bc), - ("square-24b-3ch-bs4608-L6-n9595-c3865", 0x88b6af280896f131), - ("square-32b-4ch-bs576-L0-n1544-c4176", 0x8a72918d0834a2f1), - ("wasted-8b-1ch-bs4608-L2-n9657-c3909", 0xa7516cdcf761110e), - ("wasted-12b-2ch-bs576-L5-n1606-c4220", 0xf1894eef730d7546), - ("wasted-16b-3ch-bs4096-L8-n8659-c4531", 0x39d34c6ea3569b7c), - ("wasted-24b-4ch-bs16-L2-n512-c4842", 0xfa3786f5b0f1004d), - ("wasted-32b-1ch-bs1000-L5-n2493-c153", 0x00934303beb10016), - ("click-8b-2ch-bs16-L7-n574-c4886", 0x54b956cd16590b80), - ("click-12b-3ch-bs1000-L1-n2555-c197", 0x5b5c00ba683e16fb), - ("click-16b-4ch-bs4608-L4-n9784-c508", 0x906ae4960be0eb16), - ("click-24b-1ch-bs576-L7-n1733-c819", 0x815a9e001b296ae1), - ("click-32b-2ch-bs4096-L1-n8786-c1130", 0x9d4424021be06705), - ("gap-8b-3ch-bs576-L3-n1795-c863", 0xa372ac31d477b4de), - ("gap-12b-4ch-bs4096-L6-n8848-c1174", 0x0f98e2cbcff69b73), - ("gap-16b-1ch-bs16-L0-n701-c1485", 0xf0de17bb815bc8eb), - ("gap-24b-2ch-bs1000-L3-n2682-c1796", 0x09a7b31c70740cc1), - ("gap-32b-3ch-bs4608-L6-n9911-c2107", 0x8ba6d94ee8c85b0c), - ("silence-8b-4ch-bs1000-L8-n2044-c1840", 0x845724c286fa7300), - ("silence-12b-1ch-bs4608-L2-n9273-c2151", 0xe09802e7a78bf137), - ("silence-16b-2ch-bs576-L5-n1222-c2462", 0x9bfd29a65f5d4a8c), - ("silence-24b-3ch-bs4096-L8-n8275-c2773", 0xfcf34cb0553f5b39), - ("silence-32b-4ch-bs16-L2-n128-c3084", 0xc4c8f1f5d73208e0), - ("music-16b-2ch-bs4096-L0-n9000-c4096", 0x7ee21e0646af3021), - ("music-24b-2ch-bs4096-L0-n9000-c4096", 0x384bb9626dd0eeb3), - ("music-16b-2ch-bs4096-L1-n9000-c4096", 0x7ee21e0646af3021), - ("music-24b-2ch-bs4096-L1-n9000-c4096", 0x384bb9626dd0eeb3), - ("music-16b-2ch-bs4096-L2-n9000-c4096", 0x7ee21e0646af3021), - ("music-24b-2ch-bs4096-L2-n9000-c4096", 0x384bb9626dd0eeb3), - ("music-16b-2ch-bs4096-L3-n9000-c4096", 0xf948f408d6ea5f90), - ("music-24b-2ch-bs4096-L3-n9000-c4096", 0xc448a8514df4434d), - ("music-16b-2ch-bs4096-L4-n9000-c4096", 0xd6524def929fdb8e), - ("music-24b-2ch-bs4096-L4-n9000-c4096", 0xf8f9ddf3036880be), - ("music-16b-2ch-bs4096-L5-n9000-c4096", 0xd6524def929fdb8e), - ("music-24b-2ch-bs4096-L5-n9000-c4096", 0xf8f9ddf3036880be), - ("music-16b-2ch-bs4096-L6-n9000-c4096", 0xd6524def929fdb8e), - ("music-24b-2ch-bs4096-L6-n9000-c4096", 0xf8f9ddf3036880be), - ("music-16b-2ch-bs4096-L7-n9000-c4096", 0x5be70a6777d3303e), - ("music-24b-2ch-bs4096-L7-n9000-c4096", 0x70773b947683c189), - ("music-16b-2ch-bs4096-L8-n9000-c4096", 0x5be70a6777d3303e), - ("music-24b-2ch-bs4096-L8-n9000-c4096", 0x70773b947683c189), - ("noise-16b-4ch-bs1000-L0-n2500-c777", 0x5d0bbda30208b8e9), - ("gap-16b-2ch-bs576-L0-n2000-c2000", 0x294b47f7663f3861), - ("noise-16b-4ch-bs1000-L5-n2500-c777", 0x5d0bbda30208b8e9), - ("gap-16b-2ch-bs576-L5-n2000-c2000", 0xb8a5a6d18a43f0da), - ("noise-16b-4ch-bs1000-L8-n2500-c777", 0x5d0bbda30208b8e9), - ("gap-16b-2ch-bs576-L8-n2000-c2000", 0xb8a5a6d18a43f0da), -]; - -#[test] -fn encoder_output_matches_golden_hashes() { - let all = cases(); - assert_eq!(all.len(), GOLDEN.len(), "golden table out of date: regenerate it"); - for (case, &(name, want)) in all.iter().zip(GOLDEN) { - assert_eq!(case.name(), name, "case list changed"); - assert_eq!(case.hash(), want, "output changed for {name}"); - } -} - -#[test] -#[ignore = "prints the golden table"] -fn print() { - for c in cases() { - println!(" (\"{}\", {:#018x}),", c.name(), c.hash()); - } -} diff --git a/crates/audio/src/write/flac/mod.rs b/crates/audio/src/write/flac/mod.rs index 6f562e6e27..78234442fc 100644 --- a/crates/audio/src/write/flac/mod.rs +++ b/crates/audio/src/write/flac/mod.rs @@ -10,8 +10,6 @@ mod predict; #[cfg(test)] use craft_media_testkit as common; #[cfg(test)] -mod golden_tests; -#[cfg(test)] mod oracle_tests; use super::pcm::{Quantizer, validate_buffer, validate_layout}; diff --git a/crates/audio/src/write/flac/oracle_tests.rs b/crates/audio/src/write/flac/oracle_tests.rs index aaf2322e11..a28cc48b0c 100644 --- a/crates/audio/src/write/flac/oracle_tests.rs +++ b/crates/audio/src/write/flac/oracle_tests.rs @@ -131,66 +131,6 @@ fn every_signal_round_trips_exactly() { } } -#[test] -fn channel_layouts_rates_and_sizes() { - let cases: [(&str, u8, u8, u32, usize); 12] = [ - ("mono-8bit", 1, 8, 8_000, 3_001), - ("mono-24-44k1", 1, 24, 44_100, 9_999), - ("stereo-20bit", 2, 20, 96_000, 10_000), - ("5.1-24", 6, 24, 48_000, 12_345), - ("mono-32", 1, 32, 48_000, 7_777), - ("5.1-32", 6, 32, 96_000, 12_345), - ("odd-rate", 2, 16, 37_800, 5_000), - ("rate-khz", 2, 16, 64_000, 5_000), - ("rate-tens", 2, 24, 352_800, 5_000), - ("rate-max", 1, 16, 655_350, 5_000), - ("rate-from-streaminfo", 1, 16, 100_001, 5_000), - ("tiny", 2, 16, 48_000, 1), - ]; - for (name, ch, bps, rate, n) in cases { - let planar: Vec> = (0..ch).map(|c| signal(if c == 3 { "silence" } else { "music" }, n, bps, u64::from(c) + 7)).collect(); - if round_trip(name, &planar, EncoderConfig::new(rate, ch, bps), 1000).is_none() { - return; - } - } -} - -#[test] -fn levels_and_block_sizes_trade_time_for_size() { - let planar = vec![signal("music", 48_000, 16, 11), signal("sweep", 48_000, 16, 12)]; - let mut sizes = Vec::new(); - for level in 0..=8 { - let cfg = EncoderConfig { level, ..EncoderConfig::new(48_000, 2, 16) }; - let Some(size) = round_trip(&format!("level{level}"), &planar, cfg, 48_000) else { return }; - sizes.push(size); - } - // linear prediction beats the fastest level by a wide margin, and all beat PCM - assert!(sizes[8] <= sizes[5] && sizes[5] < sizes[0] * 4 / 5, "{sizes:?}"); - assert!(sizes.iter().all(|&s| s < 48_000 * 4), "{sizes:?}"); - for bs in [16u16, 192, 1152, 4608, 65_535] { - let cfg = EncoderConfig { block_size: bs, ..EncoderConfig::new(48_000, 2, 16) }; - round_trip(&format!("block{bs}"), &planar, cfg, 777); - } -} - -#[test] -fn bad_input_is_an_error_not_a_panic() { - assert!(Encoder::new(EncoderConfig::new(48_000, 0, 16)).is_err()); - assert!(Encoder::new(EncoderConfig::new(48_000, 9, 16)).is_err()); - assert!(Encoder::new(EncoderConfig::new(48_000, 2, 33)).is_err()); - assert!(Encoder::new(EncoderConfig::new(48_000, 2, 7)).is_err()); - assert!(Encoder::new(EncoderConfig::new(0, 2, 16)).is_err()); - assert!(Encoder::new(EncoderConfig { block_size: 8, ..EncoderConfig::new(48_000, 2, 16) }).is_err()); - let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 16)).unwrap(); - assert_eq!(enc.encode(&[&[0, 1]]), Err(Error::Channels { expected: 2, got: 1 })); - assert_eq!(enc.encode(&[&[0, 1], &[0]]), Err(Error::UnequalChannels)); - assert_eq!(enc.encode(&[&[40_000], &[0]]), Err(Error::SampleRange(40_000))); - assert_eq!(enc.encode(&[&[-32_769], &[0]]), Err(Error::SampleRange(-32_769))); - // nothing encoded: no frames, and a header that still says "unknown" - assert!(enc.finish().is_empty()); - assert_eq!(&enc.header(&[])[..4], b"fLaC"); -} - /// 32-bit stereo at the extremes of i32: left minus right would need 33 bits, so the encoder must /// not code a side channel (it overflowed `i32` and wrote garbage); every level decodes exactly. #[test] @@ -209,286 +149,6 @@ fn full_scale_32_bit_stereo_round_trips() { assert!(enc.encode(&[&[i32::MIN, i32::MAX], &[0, -1]]).is_ok()); } -/// A layout decoders would not assume for the channel count is recorded as a channel mask comment, -/// which ffmpeg reads: they read 6 channels with side surrounds, and 7 as 6.1 with sides. -#[test] -fn layouts_decoders_would_not_assume_are_recorded() { - use crate::{AudioBuffer, ChannelLayout, EncodeFormat, EncodeOptions}; - let Some(ffprobe) = common::ffprobe() else { return }; - let cases = [ - ("layout-stereo", 2, None, "stereo"), - ("layout-7-default", 7, None, "6.1(back)"), - ("layout-6.1-side", 7, Some(ChannelLayout::SURROUND_6_1), "6.1"), - ("layout-5.1-side", 6, Some(ChannelLayout::SURROUND_5_1_SIDE), "5.1(side)"), - ("layout-5.1-back", 6, Some(ChannelLayout::SURROUND_5_1), "5.1"), - ("layout-6-default", 6, None, "5.1"), - ]; - for (name, channels, layout, expected) in cases { - let buf = AudioBuffer::new(48_000, channels, 100); - let mut opts = EncodeOptions::new(EncodeFormat::Flac); - opts.layout = layout; - let file = crate::encode(&buf, &opts).unwrap(); - let path = common::fixture_subdir("flac").join(format!("{name}.flac")); - std::fs::write(&path, &file).unwrap(); - let out = - Command::new(&ffprobe).args(["-v", "error", "-show_entries", "stream=channel_layout", "-of", "csv=p=0"]).arg(&path).output().unwrap(); - assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), expected, "{name}"); - } -} - -/// FLAC in Ogg reads its layout as a FLAC file does: from the mask comment, or else the one -/// decoders assume for the count. -#[cfg(feature = "symphonia")] -#[test] -fn ogg_flac_reads_the_mask_comment() { - use crate::ChannelLayout; - let Some(ff) = ffmpeg() else { return }; - let cases: [(&str, &str, &[&str], u16, u32); 5] = [ - ("ogg-mask", "aevalsrc=0|0|0|0:c=4c:d=0.1:s=48000", &["-metadata", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"], 4, 0x107), - ("ogg-5.1", "aevalsrc=0|0|0|0|0|0:c=5.1:d=0.1:s=48000", &[], 6, 0x60F), - ("ogg-stereo", "aevalsrc=0|0:c=stereo:d=0.1:s=48000", &["-metadata", "TITLE=x"], 2, 0x3), - ("ogg-6.1", "aevalsrc=0|0|0|0|0|0|0:c=6.1:d=0.1:s=48000", &[], 7, 0x70F), - ("ogg-zero-mask", "aevalsrc=0|0|0|0|0|0:c=5.1:d=0.1:s=48000", &["-metadata", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0"], 6, 0), - ]; - for (name, source, extra, channels, mask) in cases { - let path = common::fixture_subdir("flac").join(format!("{name}.oga")); - let status = Command::new(&ff) - .args(["-v", "error", "-y", "-f", "lavfi", "-i", source, "-c:a", "flac", "-f", "ogg"]) - .args(extra) - .arg(&path) - .status() - .unwrap(); - assert!(status.success(), "{name}"); - let bytes = std::fs::read(&path).unwrap(); - let expected = ChannelLayout::from_mask_and_channels(mask, channels); - assert_eq!(crate::probe(&bytes, None).unwrap().layout, expected, "probe {name}"); - assert_eq!(crate::decode(&bytes, None).unwrap().0.layout, expected, "decode {name}"); - } -} - -/// `file`, an Ogg file of two streams, with its streams' serial numbers replaced by `serials`, in -/// the order the streams start. -#[cfg(feature = "symphonia")] -fn set_ogg_serials(mut file: Vec, serials: [u32; 2]) -> Vec { - let mut seen = Vec::new(); - let mut at = 0; - while at < file.len() { - assert_eq!(&file[at..at + 4], b"OggS"); - let segments = usize::from(file[at + 26]); - let body: usize = file[at + 27..at + 27 + segments].iter().map(|&n| usize::from(n)).sum(); - let end = at + 27 + segments + body; - let old: [u8; 4] = file[at + 14..at + 18].try_into().unwrap(); - let stream = seen.iter().position(|s| *s == old).unwrap_or_else(|| { - seen.push(old); - seen.len() - 1 - }); - file[at + 14..at + 18].copy_from_slice(&serials[stream].to_le_bytes()); - // The page's checksum covers its serial number, and is computed with its own field zero. - file[at + 22..at + 26].fill(0); - let crc = craft_media::ogg::crc32(&file[at..end]); - file[at + 22..at + 26].copy_from_slice(&crc.to_le_bytes()); - at = end; - } - assert_eq!(seen.len(), 2); - file -} - -/// Two streams in an Ogg file written by ffmpeg, with serial numbers in file order or in `reversed` -/// order. ffmpeg picks them at random, and symphonia orders tracks by serial, so the reversed order -/// is the one that tells the two orders apart. `None` after `skip` when this ffmpeg cannot write the -/// file. -#[cfg(feature = "symphonia")] -fn two_ogg_streams(ff: &Path, name: &str, args: &[&str], reversed: bool) -> Option> { - let path = common::fixture_subdir("flac").join(format!("{name}.ogg")); - let status = Command::new(ff) - .args(["-v", "error", "-y", "-f", "lavfi", "-i", "aevalsrc=0|0|0|0:c=4c:d=0.1:s=48000"]) - .args(["-f", "lavfi", "-i", "aevalsrc=0|0|0|0:c=4c:d=0.1:s=44100"]) - .args(["-map", "0", "-map", "1"]) - .args(args) - .args(["-f", "ogg"]) - .arg(&path) - .status() - .unwrap(); - if !status.success() { - return common::skip(&format!("this ffmpeg cannot write {name}")); - } - let serials = if reversed { [2, 1] } else { [1, 2] }; - let bytes = set_ogg_serials(std::fs::read(&path).unwrap(), serials); - let file = craft_media::ogg::open(bytes.as_slice()).unwrap(); - assert_eq!(file.streams.iter().map(|s| s.serial).collect::>(), serials, "{name}"); - assert!(file.warnings.is_empty(), "{name}: {:?}", file.warnings); - Some(bytes) -} - -/// A track index means the same stream in `tracks`, `probe` and `decode`: the file's order. Each -/// track has its own mask comment, or else the layout decoders assume for the count. -#[cfg(feature = "symphonia")] -#[test] -fn ogg_flac_tracks_are_in_file_order_with_their_own_mask_comments() { - use crate::{ChannelLayout, DecodeOptions}; - let Some(ff) = ffmpeg() else { return }; - let args = ["-c:a", "flac", "-metadata:s:a:0", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"]; - for reversed in [false, true] { - let Some(bytes) = two_ogg_streams(&ff, "ogg-one-mask", &args, reversed) else { return }; - let rates: Vec<_> = crate::tracks(&bytes, None).unwrap().iter().map(|t| t.sample_rate).collect(); - assert_eq!(rates, [Some(48_000), Some(44_100)]); - for (track, rate, layout) in [(0, 48_000, ChannelLayout::from_mask(0x107)), (1, 44_100, ChannelLayout::default_for(4))] { - let opts = DecodeOptions::default().with_track(track); - let info = crate::probe_with(&bytes, None, &opts).unwrap(); - assert_eq!((info.sample_rate, info.layout), (rate, layout), "probe track {track}"); - let info = crate::decode_with(&bytes, None, &opts).unwrap().0; - assert_eq!((info.sample_rate, info.layout), (rate, layout), "decode track {track}"); - } - assert_eq!(crate::decode(&bytes, None).unwrap().0.sample_rate, 48_000, "the first track"); - } -} - -/// A FLAC stream before a stream symphonia cannot decode is still the first track. -#[cfg(feature = "symphonia")] -#[test] -fn ogg_flac_before_opus_is_the_first_track() { - use crate::CodecId; - let Some(ff) = ffmpeg() else { return }; - let args = ["-c:a:0", "flac", "-c:a:1", "libopus", "-ac:a:1", "2"]; - for reversed in [false, true] { - let Some(bytes) = two_ogg_streams(&ff, "ogg-flac-opus", &args, reversed) else { return }; - assert_eq!(crate::tracks(&bytes, None).unwrap()[0].codec, CodecId::Flac); - assert_eq!(crate::decode(&bytes, None).unwrap().0.codec, CodecId::Flac); - } -} - -/// The first page of a Speex stream, which symphonia has no reader for. -#[cfg(feature = "symphonia")] -fn speex_ogg_page(serial: u32) -> Vec { - let mut packet = b"Speex ".to_vec(); - packet.resize(80, 0); - let mut page = b"OggS\0\x02".to_vec(); // the start of a stream - page.extend_from_slice(&[0; 8]); // granule position - page.extend_from_slice(&serial.to_le_bytes()); - page.extend_from_slice(&[0; 8]); // page number and checksum - page.extend_from_slice(&[1, packet.len() as u8]); - page.extend_from_slice(&packet); - let crc = craft_media::ogg::crc32(&page); - page[22..26].copy_from_slice(&crc.to_le_bytes()); - page -} - -/// A stream symphonia has no track for does not stop the default decode from reading the next one, -/// and it keeps its index. -#[cfg(feature = "symphonia")] -#[test] -fn ogg_flac_after_a_stream_with_no_reader_is_the_default_track() { - use crate::{CodecId, DecodeOptions}; - let Some(ff) = ffmpeg() else { return }; - let args = ["-c:a", "flac"]; - for reversed in [false, true] { - let Some(flac) = two_ogg_streams(&ff, "ogg-speex-flac", &args, reversed) else { return }; - for speex_serial in [0, 9] { - let file = [speex_ogg_page(speex_serial), flac.clone()].concat(); - let codecs: Vec<_> = crate::tracks(&file, None).unwrap().iter().map(|t| t.codec).collect(); - assert_eq!(codecs, [CodecId::Speex, CodecId::Flac, CodecId::Flac]); - let info = crate::decode(&file, None).unwrap().0; - assert_eq!((info.codec, info.sample_rate), (CodecId::Flac, 48_000), "reversed {reversed}, speex {speex_serial}"); - assert!(crate::decode_with(&file, None, &DecodeOptions::default().with_track(0)).is_err()); - let second = crate::decode_with(&file, None, &DecodeOptions::default().with_track(2)).unwrap().0; - assert_eq!(second.sample_rate, 44_100, "reversed {reversed}, speex {speex_serial}"); - } - } -} - -/// Bytes before the first page do not lose the file's track order or mask comments. -#[cfg(feature = "symphonia")] -#[test] -fn ogg_flac_after_leading_bytes_keeps_its_track_order() { - use crate::{ChannelLayout, DecodeOptions}; - let Some(ff) = ffmpeg() else { return }; - let args = ["-c:a", "flac", "-metadata:s:a:0", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"]; - let Some(bytes) = two_ogg_streams(&ff, "ogg-leading-bytes", &args, true) else { return }; - let file = [vec![0; 64], bytes].concat(); - let info = crate::decode_with(&file, None, &DecodeOptions::default().with_track(0)).unwrap().0; - assert_eq!((info.sample_rate, info.layout), (48_000, ChannelLayout::from_mask(0x107))); -} - -#[test] -fn the_mask_comment_is_written_only_when_decoders_would_assume_otherwise() { - use super::mask_comment; - let comment = |m: &str| Some(format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={m}")); - for channels in [1, 2, 3, 4, 8] { - assert_eq!(mask_comment(channels, None), None, "{channels}"); - } - assert_eq!(mask_comment(5, None), comment("0x0037")); - assert_eq!(mask_comment(5, Some(0x607)), None); - assert_eq!(mask_comment(6, None), comment("0x003F")); - assert_eq!(mask_comment(6, Some(0x60F)), None); - assert_eq!(mask_comment(7, None), comment("0x013F")); - assert_eq!(mask_comment(7, Some(0x70F)), None); - // no speaker assignment - assert_eq!(mask_comment(2, Some(0)), comment("0x0000")); -} - -/// Left and right at opposite full scale: the side channel needs its extra bit at every depth. -#[test] -fn opposite_polarity_stereo_round_trips() { - for bps in [16u8, 24] { - let left = signal("square", 9_000, bps, 1); - let right: Vec = left.iter().map(|&v| !v).collect(); - let planar = vec![left, right]; - if round_trip(&format!("opposite-{bps}"), &planar, EncoderConfig::new(48_000, 2, bps), 4096).is_none() { - return; - } - } -} - -#[test] -fn streaminfo_states_the_block_and_frame_sizes() { - // silence in the middle: the smallest frame is neither the first nor the last - let channel = |seed| [signal("noise", 4096, 16, seed), signal("silence", 4096, 16, seed), signal("noise", 1000, 16, seed)].concat(); - let planar = [channel(21), channel(22)]; - let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 16)).unwrap(); - let parts: Vec<&[i32]> = planar.iter().map(Vec::as_slice).collect(); - let mut sizes: Vec = enc.encode_frames(&parts).unwrap().iter().map(Vec::len).collect(); - sizes.push(enc.finish().len()); - let si = enc.streaminfo(); - let u24 = |b: &[u8]| usize::from(b[0]) << 16 | usize::from(b[1]) << 8 | usize::from(b[2]); - assert_eq!(&si[..4], &[0x10, 0x00, 0x10, 0x00]); - assert_eq!(u24(&si[4..7]), sizes.iter().copied().min().unwrap()); - assert_eq!(u24(&si[7..10]), sizes.iter().copied().max().unwrap()); -} - -/// Frame numbers count up from 0; a decoder that seeks depends on them, though one that reads from -/// the start does not. -#[test] -fn frames_are_numbered_in_order() { - let planar = [signal("music", 4096 * 10, 16, 31)]; - let mut enc = Encoder::new(EncoderConfig::new(48_000, 1, 16)).unwrap(); - let frames = enc.encode_frames(&[&planar[0]]).unwrap(); - let numbers: Vec = frames.iter().map(|f| f[4]).collect(); - assert_eq!(numbers, (0..10).collect::>()); -} - -/// Two equal channels cost little more than one: the side channel is all zeros. -#[test] -fn stereo_decorrelation_removes_a_duplicated_channel() { - let x = signal("music", 20_000, 16, 41); - let mono = encode(std::slice::from_ref(&x), EncoderConfig::new(48_000, 1, 16), 4096).unwrap(); - let stereo = encode(&[x.clone(), x], EncoderConfig::new(48_000, 2, 16), 4096).unwrap(); - assert!(stereo.len() < mono.len() * 11 / 10, "stereo {} mono {}", stereo.len(), mono.len()); -} - -#[test] -fn the_frame_limit_stops_a_write_before_it_reaches_the_sink() { - use super::Writer; - use crate::{AudioError, BitDepth}; - let mut w = Writer::new(std::io::Cursor::new(Vec::new()), 1, 48_000, BitDepth::Int16, false, None).unwrap(); - let header = w.out.get_ref().len(); - w.frames = (1 << 36) - 2; - assert!(matches!(w.write(&[[0.0f32; 4096]], 4096), Err(AudioError::TooLarge(_)))); - assert_eq!(w.out.get_ref().len(), header); - // refused, not failed: what fits can still be written - assert!(w.write(&[[0.0f32; 1]], 1).is_ok()); - assert!(matches!(w.write(&[[0.0f32; 1]], 1), Err(AudioError::TooLarge(_)))); -} - /// Samples with unused low bits, on every kind of subframe and stereo mode: the decoder must put /// the bits back before it undoes the stereo decorrelation. #[test] @@ -507,31 +167,3 @@ fn wasted_bits_round_trip() { let lowest: Vec = (0..9_000).map(|i| if i % 3 == 0 { -(1 << 23) } else { 0 }).collect(); round_trip("wasted-to-one-bit", &[lowest], EncoderConfig::new(48_000, 1, 24), 4096); } - -/// A click at full scale needs a residual near the limit; a block is not stored verbatim for it. -#[test] -fn a_full_scale_click_at_32_bits_is_still_predicted() { - let planar = [signal("click", 4_096, 32, 61)]; - let Some(size) = round_trip("click-32", &planar, EncoderConfig::new(48_000, 1, 32), 4096) else { return }; - assert!(size < 4_096 * 4 / 2, "{size}"); -} - -/// Signals that reach the format's limits, which a decoder refuses when they are passed: a Rice -/// parameter of 31 is the escape code, and an LPC shift above 15 reads as negative. -#[test] -fn rice_parameter_and_lpc_shift_stay_in_range() { - let mut r = Rng(71); - let bursts: Vec = - (0..9_000).map(|i| if i % 1024 < 128 { if i % 2 == 0 { i32::MAX } else { -i32::MAX } } else { (r.next() * 100.0) as i32 }).collect(); - if round_trip("limit-rice", &[bursts], EncoderConfig::new(48_000, 1, 32), 4096).is_none() { - return; - } - let mut y = 0.0; - let correlated: Vec = (0..9_000) - .map(|_| { - y = 0.24 * y + r.next() * 8000.0; - y as i32 - }) - .collect(); - round_trip("limit-shift", &[correlated], EncoderConfig::new(48_000, 1, 16), 4096); -} diff --git a/crates/audio/src/write/flac/predict.rs b/crates/audio/src/write/flac/predict.rs index 6ab7e123e7..21fab24d94 100644 --- a/crates/audio/src/write/flac/predict.rs +++ b/crates/audio/src/write/flac/predict.rs @@ -356,59 +356,6 @@ pub fn choose(x: &[i32], bps: u8, effort: Effort, win: &[f64]) -> (Subframe, u64 mod tests { use super::*; - #[test] - fn folding() { - assert_eq!([0, -1, 1, -2, 2].map(fold), [0, 1, 2, 3, 4]); - } - - #[test] - fn predictable_signals_beat_verbatim() { - // a ramp is exactly predicted by the order-2 fixed predictor - let ramp: Vec = (0..4096).map(|i| i * 3 - 6000).collect(); - let (sub, bits) = choose(&ramp, 16, Effort::level(5), &window(ramp.len())); - assert!(matches!(sub, Subframe::Fixed { order: 2, .. } | Subframe::Lpc { .. }), "{sub:?}"); - assert!(bits < 4096 * 2, "{bits}"); - // a sine is well predicted by LPC - let sine: Vec = (0..4096).map(|i| ((i as f64 * 0.05).sin() * 20000.0) as i32).collect(); - let (_, bits) = choose(&sine, 16, Effort::level(5), &window(sine.len())); - assert!(bits < 4096 * 6, "{bits}"); - assert_eq!(choose(&[7; 100], 16, Effort::level(5), &window(100)), (Subframe::Constant(7), 24)); - } - - #[test] - fn residuals_may_reach_the_limit_of_a_32_bit_integer() { - assert!(fixed_fold(&[i32::MAX, -i32::MAX], 0).is_some()); - assert!(fixed_fold(&[0, i32::MAX], 1).is_some()); - // the most negative value is out of range (§9.2.7.3) - assert!(fixed_fold(&[i32::MIN], 0).is_none()); - assert!(fixed_fold(&[0, 1 << 30, -(1 << 30)], 1).is_none()); - assert!(lpc_fold(&[0, i32::MAX], &[1], 0).is_some()); - } - - #[test] - fn linear_predictions_stay_in_the_range_of_a_32_bit_integer() { - let x = [1 << 30, 1 << 30]; - assert!(lpc_fold(&x, &[1], 0).is_some()); - // predicts 2^31, and the residual would be small - assert!(lpc_fold(&x, &[2], 0).is_none()); - assert!(lpc_fold(&x, &[4], 1).is_none()); - assert!(lpc_fold(&x, &[3], 1).is_some()); - } - - #[test] - fn wasted_bits_are_not_coded() { - let x = tones(4096); - let padded: Vec = x.iter().map(|&s| s << 8).collect(); - let effort = Effort::level(5); - let (sub, bits) = choose(&x, 16, effort, &window(x.len())); - // the same coding, plus the 8 bits that say how many are wasted - assert_eq!(choose(&padded, 24, effort, &window(padded.len())), (Subframe::Wasted { bits: 8, coded: Box::new(sub) }, bits + 8)); - // at most what leaves one bit per sample, and nothing for silence, a constant keeps its bits - let lowest = [0, -(1 << 23)]; - assert!(matches!(choose(&lowest, 24, effort, &window(lowest.len())).0, Subframe::Wasted { bits: 23, .. })); - assert_eq!(choose(&[256; 10], 24, effort, &window([256; 10].len())).0, Subframe::Constant(256)); - } - /// Two tones and a little noise, from a fixed seed. fn tones(n: usize) -> Vec { let mut seed = 1u32; @@ -430,48 +377,4 @@ mod tests { let (_, fixed) = choose(&x, 16, Effort { max_lpc_order: 0, ..effort }, &window(x.len())); assert!(lpc < fixed * 4 / 5, "lpc {lpc} fixed {fixed}"); } - - #[test] - fn rice_partitions_follow_a_change_in_loudness() { - // quiet, then loud: one Rice parameter cannot suit both - let x: Vec = tones(4096).iter().enumerate().map(|(i, &s)| if i < 2048 { s / 256 } else { s }).collect(); - let effort = Effort::level(5); - let (_, partitioned) = choose(&x, 16, effort, &window(x.len())); - let (_, whole) = choose(&x, 16, Effort { max_partition_order: 0, ..effort }, &window(x.len())); - assert!(partitioned < whole * 19 / 20, "partitioned {partitioned} whole {whole}"); - } - - #[test] - fn lpc_residual_inverts() { - let x: Vec = (0..500).map(|i| ((i as f64 * 0.1).sin() * 1000.0) as i32).collect(); - let coefs = lpc_orders(&x, 4, &window(x.len())).pop().unwrap(); - let (q, shift) = quantise(&coefs, 15).unwrap(); - let r: Vec = - lpc_fold(&x, &q, shift).unwrap().iter().map(|&u| if u & 1 == 0 { i64::from(u >> 1) } else { -i64::from(u >> 1) - 1 }).collect(); - // rebuild the signal from the warm-up and the residual, as a decoder would - let mut y: Vec = x[..q.len()].to_vec(); - for (i, &res) in r.iter().enumerate() { - let p: i64 = q.iter().zip(y[i..i + q.len()].iter().rev()).map(|(&c, &s)| i64::from(c) * i64::from(s)).sum(); - y.push((res + (p >> shift)) as i32); - } - assert_eq!(y, x); - } - - #[test] - fn noise_and_extremes_do_not_panic() { - let mut seed = 1u32; - let noise: Vec = (0..4096) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 8) as i32 - (1 << 23) - }) - .collect(); - let (_, bits) = choose(&noise, 24, Effort::level(8), &window(noise.len())); - assert!(bits <= 8 + 4096 * 24); - let square: Vec = (0..4096).map(|i| if i % 2 == 0 { (1 << 23) - 1 } else { -(1 << 23) }).collect(); - choose(&square, 24, Effort::level(8), &window(square.len())); - choose(&[], 16, Effort::level(5), &window(0)); - choose(&[1], 16, Effort::level(5), &window(1)); - choose(&[1, 2], 16, Effort::level(8), &window(2)); - } } diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index a2043d2797..bbb42601ec 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -454,46 +454,3 @@ pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result< } wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) } - -// With only one of `pcm-encode` and `flac-encode`, the other's formats are refused, not silently -// written as something else. -#[cfg(all(test, any(feature = "pcm-encode", feature = "flac-encode"), not(all(feature = "pcm-encode", feature = "flac-encode"))))] -mod tests { - use super::*; - - #[test] - fn unbuilt_format_is_unsupported() { - let (format, name) = if cfg!(feature = "pcm-encode") { (EncodeFormat::Flac, "flac") } else { (EncodeFormat::Wav, "wav") }; - let opts = EncodeOptions::new(format); - let buf = AudioBuffer::new(48_000, 1, 16); - assert!(matches!(encode(&buf, &opts), Err(AudioError::Unsupported(_)))); - let enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 1); - assert!(matches!(enc, Err(AudioError::Unsupported(_)))); - assert_eq!(encode_format_for(name), None); - assert!(!format.is_built() && EncodeFormat::ALL.iter().any(|f| f.is_built())); - // Also with a layout it could not use. - let opts = opts.with_layout(ChannelLayout::STEREO); - assert!(matches!(encode(&buf, &opts), Err(AudioError::Unsupported(_)))); - let enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 1); - assert!(matches!(enc, Err(AudioError::Unsupported(_)))); - } - - /// Streaming in any block sizes writes the bytes `encode` writes. - #[cfg(feature = "flac-encode")] - #[test] - fn streamed_flac_matches_encode() { - let channels: Vec> = (0..2).map(|c| (0..20_000).map(|i| ((i * (c + 3)) as f32 * 0.01).sin() * 0.5).collect()).collect(); - let buf = AudioBuffer { sample_rate: 48_000, channels }; - let opts = EncodeOptions::new(EncodeFormat::Flac); - let whole = encode(&buf, &opts).unwrap(); - let mut enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 2).unwrap(); - let mut at = 0; - for n in [1000, 4096, 1, 9000, 5903] { - let block: Vec<&[f32]> = buf.channels.iter().map(|c| &c[at..at + n]).collect(); - enc.write(&block, n).unwrap(); - at += n; - } - assert_eq!(at, buf.frames()); - assert_eq!(enc.finish().unwrap().into_inner(), whole); - } -} diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index 72749df044..9e08b4a44e 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -1,24 +1,5 @@ use craft_audio::{EncodeFormat, encode_format_for}; -#[test] -fn only_formats_the_encoder_writes_are_named() { - assert_eq!(encode_format_for("wav"), Some(EncodeFormat::Wav)); - assert_eq!(encode_format_for("WAV"), Some(EncodeFormat::Wav)); - assert_eq!(encode_format_for(".aif"), Some(EncodeFormat::Aiff)); - assert_eq!(encode_format_for("aiff"), Some(EncodeFormat::Aiff)); - assert_eq!(encode_format_for("wave"), Some(EncodeFormat::Wav)); - assert_eq!(encode_format_for("BWF"), Some(EncodeFormat::Wav)); - assert_eq!(encode_format_for(".aifc"), Some(EncodeFormat::Aiff)); - assert_eq!(encode_format_for("flac"), Some(EncodeFormat::Flac)); - assert!(craft_audio::ENCODE_EXTENSIONS.contains(&"flac")); - for name in craft_audio::ENCODE_EXTENSIONS { - assert!(encode_format_for(name).is_some(), "{name}"); - } - for other in ["opus", "aac", "mp4", "xyz", ""] { - assert_eq!(encode_format_for(other), None, "{other}"); - } -} - #[test] fn ogg_names_follow_the_feature() { let built = cfg!(feature = "vorbis-encode"); diff --git a/crates/audio/tests/audio/float_headroom.rs b/crates/audio/tests/audio/float_headroom.rs index e0c62204e1..974015e509 100644 --- a/crates/audio/tests/audio/float_headroom.rs +++ b/crates/audio/tests/audio/float_headroom.rs @@ -63,39 +63,3 @@ fn assert_float_headroom(streaming: bool) { fn whole_file_float32_preserves_finite_headroom() { assert_float_headroom(false); } - -#[test] -fn streaming_float32_preserves_finite_headroom() { - assert_float_headroom(true); -} - -#[test] -fn float32_keeps_non_finite_sample_handling() { - let audio = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN, f32::NEG_INFINITY, f32::INFINITY]] }; - let expected = [0.0_f32, -1.0, 1.0]; - for format in [EncodeFormat::Wav, EncodeFormat::Aiff] { - for streaming in [false, true] { - let options = EncodeOptions::new(format).with_bit_depth(BitDepth::Float32).with_dither(false); - let bytes = encoded(&audio, &options, streaming); - // Inspect stored samples too: the decoder itself replaces non-finite values. - let pcm: Vec = expected.iter().flat_map(|v| if format == EncodeFormat::Wav { v.to_le_bytes() } else { v.to_be_bytes() }).collect(); - assert!(bytes.ends_with(&pcm), "{format:?}, streaming={streaming}"); - assert_eq!(decode(&bytes, None).unwrap().1.channels[0], expected); - } - } -} - -#[test] -fn integer_pcm_still_clips_at_full_scale() { - let audio = AudioBuffer { sample_rate: 48_000, channels: vec![vec![-2.0, -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25, 2.0]] }; - for (depth, max) in [(BitDepth::Int16, 32767.0 / 32768.0), (BitDepth::Int24, 8_388_607.0 / 8_388_608.0), (BitDepth::Int32, 1.0)] { - for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] { - for streaming in [false, true] { - let options = EncodeOptions::new(format).with_bit_depth(depth).with_dither(false); - let bytes = encoded(&audio, &options, streaming); - let (_, decoded) = decode(&bytes, None).unwrap(); - assert_eq!(decoded.channels[0], [-1.0, -1.0, -1.0, -0.5, 0.0, 0.5, max, max, max], "{format:?} {depth:?}, streaming={streaming}"); - } - } - } -} diff --git a/crates/audio/tests/audio/malformed.rs b/crates/audio/tests/audio/malformed.rs index 9d48d8068c..f954e28324 100644 --- a/crates/audio/tests/audio/malformed.rs +++ b/crates/audio/tests/audio/malformed.rs @@ -1,8 +1,6 @@ //! Hostile inputs must produce `Err` (or a best-effort `Ok`), never a panic. -use craft_audio::{ - AudioBuffer, AudioError, BitDepth, CodecId, Container, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, -}; +use craft_audio::{AudioBuffer, AudioError, BitDepth, CodecId, Container, EncodeFormat, EncodeOptions, decode, detect_container, encode, probe}; use proptest::prelude::*; fn small(format: EncodeFormat, depth: BitDepth, channels: usize) -> Vec { @@ -15,104 +13,6 @@ fn small(format: EncodeFormat, depth: BitDepth, channels: usize) -> Vec { encode(&b, &EncodeOptions::new(format).with_bit_depth(depth).with_dither(false)).unwrap() } -/// An ID3v2.4 header whose syncsafe size field declares `size` bytes of tag body. -fn id3_header(size: usize) -> [u8; 10] { - let size = size as u32; - [b'I', b'D', b'3', 4, 0, 0, ((size >> 21) & 0x7F) as u8, ((size >> 14) & 0x7F) as u8, ((size >> 7) & 0x7F) as u8, (size & 0x7F) as u8] -} - -/// Wrap `body` in an ID3v2.4 tag. -fn id3_tag(body: &[u8]) -> Vec { - [&id3_header(body.len())[..], body].concat() -} - -/// Little helper for building RIFF files by hand. -fn riff(chunks: &[(&[u8; 4], Vec)]) -> Vec { - let mut body = b"WAVE".to_vec(); - for (id, data) in chunks { - body.extend_from_slice(*id); - body.extend_from_slice(&(data.len() as u32).to_le_bytes()); - body.extend_from_slice(data); - if data.len() % 2 == 1 { - body.push(0); - } - } - let mut out = b"RIFF".to_vec(); - out.extend_from_slice(&(body.len() as u32).to_le_bytes()); - out.extend_from_slice(&body); - out -} - -fn fmt(tag: u16, channels: u16, sr: u32, bits: u16) -> Vec { - let align = channels * bits.div_ceil(8); - let mut f = Vec::new(); - f.extend_from_slice(&tag.to_le_bytes()); - f.extend_from_slice(&channels.to_le_bytes()); - f.extend_from_slice(&sr.to_le_bytes()); - f.extend_from_slice(&(sr * u32::from(align)).to_le_bytes()); - f.extend_from_slice(&align.to_le_bytes()); - f.extend_from_slice(&bits.to_le_bytes()); - f -} - -#[test] -fn every_truncation_is_handled() { - let files = [ - small(EncodeFormat::Wav, BitDepth::Int16, 2), - small(EncodeFormat::Wav, BitDepth::Float32, 6), - small(EncodeFormat::Aiff, BitDepth::Int24, 1), - small(EncodeFormat::Aiff, BitDepth::Float32, 2), - small(EncodeFormat::Flac, BitDepth::Int16, 2), - small(EncodeFormat::Flac, BitDepth::Int24, 1), - ]; - for file in &files { - for n in 0..file.len() { - let cut = &file[..n]; - let _ = probe(cut, None); - if let Ok((info, buf)) = decode(cut, None) { - assert_eq!(buf.num_channels(), info.channels); - assert_eq!(buf.frames() as u64, info.frames); - } - } - } -} - -#[test] -fn truncated_data_chunk_yields_partial_audio() { - let file = small(EncodeFormat::Wav, BitDepth::Int16, 2); - let (info, buf) = decode(&file[..file.len() - 400], None).unwrap(); - assert_eq!(info.frames, 200); - assert_eq!(buf.frames(), 200); -} - -#[test] -fn every_single_byte_corruption_is_handled() { - for file in - [small(EncodeFormat::Wav, BitDepth::Int24, 2), small(EncodeFormat::Aiff, BitDepth::Int16, 2), small(EncodeFormat::Flac, BitDepth::Int16, 1)] - { - for i in 0..file.len().min(200) { - for v in [0x00, 0xFF, 0x7F, 0x80] { - let mut f = file.clone(); - f[i] = v; - let _ = probe(&f, None); - let _ = decode(&f, None); - } - } - } -} - -#[test] -fn zero_channels_is_malformed() { - let wav = riff(&[(b"fmt ", fmt(1, 0, 44_100, 16)), (b"data", vec![0; 16])]); - assert!(matches!(decode(&wav, None), Err(AudioError::Malformed(_)))); - assert!(probe(&wav, None).is_err()); - let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1); - let comm = aiff.windows(4).position(|w| w == b"COMM").unwrap(); - aiff[comm + 8] = 0; - aiff[comm + 9] = 0; - assert!(matches!(decode(&aiff, None), Err(AudioError::Malformed(_)))); -} - #[test] fn aiff_negative_channel_count_is_malformed() { let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1); @@ -121,61 +21,6 @@ fn aiff_negative_channel_count_is_malformed() { aiff[comm + 9] = 0; assert!(probe(&aiff, None).is_err()); } - -#[test] -fn zero_sample_rate_is_malformed() { - let wav = riff(&[(b"fmt ", fmt(1, 2, 0, 16)), (b"data", vec![0; 16])]); - assert!(decode(&wav, None).is_err()); - let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1); - let comm = aiff.windows(4).position(|w| w == b"COMM").unwrap(); - for b in &mut aiff[comm + 16..comm + 26] { - *b = 0; - } - assert!(decode(&aiff, None).is_err()); - // Infinite exponent. - aiff[comm + 16] = 0x7F; - aiff[comm + 17] = 0xFF; - assert!(decode(&aiff, None).is_err()); -} - -#[test] -fn absurd_chunk_sizes() { - // fmt chunk claims 4 GiB. - let mut wav = riff(&[(b"fmt ", fmt(1, 2, 44_100, 16)), (b"data", vec![0; 16])]); - wav[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); - assert!(decode(&wav, None).is_err()); - // data chunk claims 4 GiB: lenient read of what's there. - let mut wav = riff(&[(b"fmt ", fmt(1, 2, 44_100, 16)), (b"data", vec![0; 16])]); - let d = wav.windows(4).position(|w| w == b"data").unwrap(); - wav[d + 4..d + 8].copy_from_slice(&u32::MAX.to_le_bytes()); - let (info, buf) = decode(&wav, None).unwrap(); - assert_eq!((info.frames, buf.frames()), (4, 4)); - // An unknown chunk with an absurd size before fmt. - let mut wav = riff(&[(b"junk", vec![0; 4]), (b"fmt ", fmt(1, 2, 44_100, 16)), (b"data", vec![0; 16])]); - wav[16..20].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); - assert!(decode(&wav, None).is_err()); - // RF64 with a ds64 claiming an exabyte of data. - let mut ds64 = Vec::new(); - ds64.extend_from_slice(&u64::MAX.to_le_bytes()); - ds64.extend_from_slice(&u64::MAX.to_le_bytes()); - ds64.extend_from_slice(&u64::MAX.to_le_bytes()); - ds64.extend_from_slice(&0u32.to_le_bytes()); - let mut rf = riff(&[(b"ds64", ds64), (b"fmt ", fmt(1, 1, 8_000, 8)), (b"data", vec![0x80; 10])]); - rf[..4].copy_from_slice(b"RF64"); - let d = rf.windows(4).rposition(|w| w == b"data").unwrap(); - rf[d + 4..d + 8].copy_from_slice(&u32::MAX.to_le_bytes()); - let (info, buf) = decode(&rf, None).unwrap(); - assert_eq!((info.frames, buf.frames()), (10, 10)); - // AIFF COMM claims more frames than present; SSND offset beyond the end. - let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1); - let comm = aiff.windows(4).position(|w| w == b"COMM").unwrap(); - aiff[comm + 10..comm + 14].copy_from_slice(&u32::MAX.to_be_bytes()); - assert_eq!(decode(&aiff, None).unwrap().1.frames(), 300); - let ssnd = aiff.windows(4).position(|w| w == b"SSND").unwrap(); - aiff[ssnd + 8..ssnd + 12].copy_from_slice(&u32::MAX.to_be_bytes()); - assert_eq!(decode(&aiff, None).unwrap().1.frames(), 0); -} - fn caf(chunks: &[(&[u8; 4], i64, Vec)]) -> Vec { let mut out = b"caff\0\x01\0\0".to_vec(); for (kind, size, body) in chunks { @@ -199,27 +44,6 @@ fn packet_table(packets: i64, frames: i64, entries: &[u8]) -> Vec { [&packets.to_be_bytes()[..], &frames.to_be_bytes(), &[0; 8], entries].concat() } -#[test] -fn caf_sizes_beyond_the_file_are_errors_not_aborts() { - let aac = || caf_desc(b"aac ", 0, 1024, 2, 0); - let huge = 1i64 << 50; - let cookie = caf(&[aac(), (b"kuki", huge, vec![0; 8])]); - let files = [ - cookie.clone(), - [vec![0; 100], cookie].concat(), - caf(&[aac(), (b"data", -1, [&[0; 4][..], b"kuki", &huge.to_be_bytes()].concat())]), - caf(&[aac(), (b"pakt", 24, packet_table(huge, 1024, &[])), (b"data", -1, vec![0; 16])]), - caf(&[aac(), (b"pakt", 32, packet_table(1, 1024, &[0x82, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0])), (b"data", -1, vec![0; 64])]), - caf(&[aac(), (b"pakt", 25, packet_table(1, 1024, &[0x80]))]), - ]; - for f in files { - assert!(matches!(probe(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); - } - let constant = caf(&[caf_desc(b"lpcm", 2, 1, 1, 16), (b"pakt", 25, packet_table(1, 1, &[1])), (b"data", -1, vec![0; 16])]); - assert!(matches!(decode(&constant, None), Err(AudioError::Malformed(m)) if m.contains("lists packets"))); -} - /// An EBML element: `id`, then `size` as an 8-byte vint (so any size up to 2^56 − 2 fits, and /// `u64::MAX` writes the reserved "unknown size"), then `body`. fn ebml(id: &[u8], size: u64, body: &[u8]) -> Vec { @@ -283,20 +107,6 @@ fn matroska_sizes_beyond_the_file_are_errors_not_aborts() { assert!(decode(&cluster, hint).map_or(0, |(_, b)| b.frames()) < 1_000, "{hint:?}"); } } - -#[test] -fn well_formed_caf_still_reads() { - let pcm: Vec = (0..480i16).flat_map(|i| (i * 50).to_be_bytes()).collect(); - let chan = [((100u32 << 16) | 1).to_be_bytes(), [0; 4], [0; 4]].concat(); - let data = [vec![0; 4], pcm].concat(); - let lpcm = caf(&[caf_desc(b"lpcm", 2, 1, 1, 16), (b"chan", 12, chan), (b"free", 8, vec![0; 8]), (b"data", data.len() as i64, data)]); - let (info, buf) = decode(&lpcm, None).unwrap(); - assert_eq!((info.container, buf.frames()), (Container::Caf, 480)); - let table = packet_table(3, 3072, &[10, 0x81, 0x48, 5]); - let aac = caf(&[caf_desc(b"aac ", 0, 1024, 2, 0), (b"pakt", table.len() as i64, table), (b"data", 219, vec![0; 219])]); - assert_eq!(probe(&aac, None).unwrap().frames, 3072); -} - fn atom(kind: &[u8; 4], body: &[u8]) -> Vec { [&(8 + body.len() as u32).to_be_bytes()[..], kind, body].concat() } @@ -328,102 +138,6 @@ fn mp4(frames: u32, entry: &[u8], swap: impl Fn(&[u8; 4], Vec) -> Vec) - [ftyp, moov(offset), atom(b"mdat", &pcm)].concat() } -#[test] -fn mp4_sizes_beyond_the_file_are_errors_not_aborts() { - let pcm = sample_entry(b"sowt", 0, &[], &[]); - let (_, buf) = decode(&mp4(480, &pcm, |_, a| a), None).unwrap(); - assert_eq!(buf.frames(), 480); - let huge = |kind: &[u8; 4], a: Vec| [&1u32.to_be_bytes()[..], kind, &(1u64 << 60).to_be_bytes(), &a[8..]].concat(); - // The first field after version and flags: stts's entry count, stsz's sample size. - let first_field_max = |mut a: Vec| { - a[12..16].copy_from_slice(&u32::MAX.to_be_bytes()); - a - }; - let sizes: Vec = (0..480u32).flat_map(|i| if i == 479 { u32::MAX } else { 2 }.to_be_bytes()).collect(); - let per_sample = atom(b"stsz", &[&[0; 8][..], &480u32.to_be_bytes(), &sizes].concat()); - // A header that starts inside its container is read whole, past the container's end. - let mdia = atom(b"mdia", &1u32.to_be_bytes()); - let straddling = [&b"hdlr"[..], &(1u64 << 60).to_be_bytes(), &[0; 24]].concat(); - let files = [ - mp4(480, &pcm, |k, a| if k == b"hdlr" { huge(k, a) } else { a }), - mp4(480, &pcm, |k, a| if k == b"stts" { first_field_max(a) } else { a }), - mp4(480, &pcm, |k, a| if k == b"stsz" { first_field_max(a) } else { a }), - mp4(480, &pcm, |k, a| if k == b"stsz" { per_sample.clone() } else { a }), - [atom(b"ftyp", b"M4A \0\0\0\0M4A isom"), atom(b"moov", &atom(b"trak", &mdia)), straddling].concat(), - ]; - for f in files { - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); - } -} - -#[test] -fn atoms_running_past_their_parent_are_walked_once() { - // Each moov holds a trak that runs to the end of the file; symphonia stops after the first. - let unit = atom(b"moov", &[&u32::MAX.to_be_bytes()[..], b"trak"].concat()); - let f = [atom(b"ftyp", b"M4A \0\0\0\0M4A isom"), unit.repeat(1 << 18)].concat(); - assert!(decode(&f, None).is_err()); -} - -#[test] -fn packets_longer_than_any_codec_uses_are_refused() { - let be = |v: &[u32]| v.iter().flat_map(|x| x.to_be_bytes()).collect::>(); - let v2 = |frames: u32| [&be(&[72])[..], &48_000f64.to_be_bytes(), &be(&[1, 0x7f00_0000, 16, 4, 2, frames])].concat(); - let lpcm = |frames: u32| sample_entry(b"lpcm", 2, &v2(frames), &[]); - let config = |frames: u32| [&be(&[0, frames])[..], &[0, 16, 40, 10, 14, 1, 0, 255], &be(&[0, 0, 48_000])].concat(); - let alac = |frames: u32| sample_entry(b"alac", 0, &[], &atom(b"alac", &config(frames))); - let (_, buf) = decode(&mp4(480, &lpcm(1), |_, a| a), None).unwrap(); - assert_eq!(buf.frames(), 480); - // PCM is read by craft-media's own demuxer, which reads version-2 sound description fields only - // in QuickTime files (ISO BMFF has no such version): the bogus frame count of this MP4 is never - // read, and nothing is allocated from it. symphonia read it, so SoundCraft refused the file. - let (_, buf) = decode(&mp4(480, &lpcm(1 << 21), |_, a| a), None).unwrap(); - assert_eq!(buf.frames(), 480); - // ALAC: a cookie declaring such packets is refused by the native decoder and then by the - // symphonia path's guard. - assert!(matches!(decode(&mp4(480, &alac(1 << 21), |_, a| a), None), Err(AudioError::Malformed(m)) if m.contains("declares packets"))); -} - -/// FLAC metadata blocks with field lengths exceeding their block boundary are refused as malformed. -#[test] -fn flac_metadata_fields_beyond_their_block_are_refused() { - let with_block = |kind: u8, body: &[u8]| { - let f = small(EncodeFormat::Flac, BitDepth::Int16, 1); - // between STREAMINFO and the encoder's VORBIS_COMMENT, which stays the last block - let head = (u32::from(kind) << 24 | body.len() as u32).to_be_bytes(); - [&f[..42], &head, body, &f[42..]].concat() - }; - let picture = |data: u32| [&[0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0][..], &[0; 16], &data.to_be_bytes(), &[1, 2, 3]].concat(); - assert_eq!(decode(&with_block(6, &picture(3)), None).unwrap().1.frames(), 300); - let comment = [&0u32.to_le_bytes()[..], &1u32.to_le_bytes(), &u32::MAX.to_le_bytes()].concat(); - let vendor_overflow = [&0x7fff_fff0u32.to_le_bytes()[..], &0u32.to_le_bytes()].concat(); - for f in [with_block(6, &picture(0x7fff_fff0)), with_block(4, &comment), with_block(4, &vendor_overflow)] { - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than its block"))); - } -} - -#[test] -fn an_id3_tag_before_the_audio_is_skipped_unread() { - let frame = [&b"TIT2"[..], &0x7fff_ffffu32.to_be_bytes(), &[0, 0, 3, b'h', b'i', 0]].concat(); - let tag = [&b"ID3\x03\0\0\0\0\0"[..], &[frame.len() as u8], &frame].concat(); - let flac = small(EncodeFormat::Flac, BitDepth::Int16, 1); - assert_eq!(decode(&[tag, flac].concat(), None).unwrap().1.frames(), 300); -} - -/// Container magic inside an MP3 frame payload must not change detection or make probing reject the stream. -#[test] -fn a_valid_mp3_with_incidental_container_magic_still_probes() { - let mut frame = vec![0u8; 417]; - frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); // MPEG-1 Layer III, 128 kbps, 44.1 kHz, stereo - let mut f: Vec = (0..8).flat_map(|_| frame.clone()).collect(); - let at = 417 * 2 + 10; // Inside frame 2's payload, leaving every frame header intact. - f[at..at + 8].copy_from_slice(b"caff\0\x01\0\0"); - f[at + 8..at + 12].copy_from_slice(b"kuki"); - f[at + 12..at + 20].copy_from_slice(&(1u64 << 50).to_be_bytes()); - assert_eq!(detect_container(&f, None), Some(Container::MpegAudio)); - let info = probe(&f, None).expect("valid MP3 with incidental container magic"); - assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Mp3, 44_100, 2)); -} - /// MP3 frames are read natively (as MP1 and MP2 are), so a container marker in junk before the /// first frame does not hide the frames: the stream plays, and the bytes before it never reach /// symphonia, whose CAF, FLAC and MP4 probes would claim the stream at the marker. A file that @@ -450,88 +164,6 @@ fn a_container_marker_before_the_first_audio_frame_does_not_hide_the_frames() { let info = probe(&f, Some("mp3")).expect("junk before a valid MP3"); assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Mp3, 44_100, 2)); } - -/// More false `0xFFEx` pairs than the preflight's scoring budget must not make a later container -/// magic inside the valid audio payload authoritative. Past the cap the scan is unchecked and the -/// probe selects the MPEG reader at the first real frame. -#[test] -fn an_exhausted_audio_score_budget_does_not_reject_the_mp3_behind_it() { - let mut frame = vec![0u8; 417]; - frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); - let mut audio: Vec = (0..8).flat_map(|_| frame.clone()).collect(); - let at = 417 * 2 + 10; // Inside frame 2's payload, leaving every frame header intact. - audio[at..at + 8].copy_from_slice(b"caff\0\x01\0\0"); - audio[at + 8..at + 12].copy_from_slice(b"kuki"); - audio[at + 12..at + 20].copy_from_slice(&(1u64 << 50).to_be_bytes()); - let false_syncs: Vec = (0..256).flat_map(|_| [0xFFu8, 0xE2]).collect(); - let f = [false_syncs, audio].concat(); - assert_eq!(detect_container(&f, Some("mp3")), Some(Container::MpegAudio)); - let info = probe(&f, Some("mp3")).expect("valid MP3 after an exhausted audio score budget"); - assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Mp3, 44_100, 2)); - let (decoded, buf) = decode(&f, Some("mp3")).expect("decode the same MP3"); - assert_eq!((decoded.codec, decoded.sample_rate, decoded.channels), (CodecId::Mp3, 44_100, 2)); - assert_eq!(decoded.frames, buf.frames() as u64); -} - -/// Past the score budget the preflight does not run, so if the probe then selects a container -/// whose reader allocates from sizes in the file, the post-probe refusal still applies. -#[test] -fn a_container_selected_without_its_size_check_is_refused() { - let flac = small(EncodeFormat::Flac, BitDepth::Int16, 1); - // Exactly the cap of false candidates, then one more that the reader rejects (invalid - // bit-rate), so the preflight stops unchecked before reaching the FLAC marker behind it. - let mut false_syncs: Vec = (0..256).flat_map(|_| [0xFFu8, 0xE2]).collect(); - false_syncs.extend_from_slice(&[0xFF, 0xFB, 0xF0, 0x00]); - let f = [false_syncs, flac].concat(); - assert_eq!(detect_container(&f, None), Some(Container::MpegAudio)); - assert!(matches!(probe(&f, None), Err(AudioError::Malformed(m)) if m.contains("was not size-checked"))); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("was not size-checked"))); -} - -/// A zero-frame FLAC after arbitrary bytes or ID3 tags is still detected and reported as an empty stream, not a -/// decode failure. -#[test] -fn zero_frame_flac_after_a_prefix_is_still_empty() { - let flac = - encode(&AudioBuffer::new(48_000, 1, 0), &EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int16).with_dither(false)).unwrap(); - let tag = id3_tag(b"tag"); - for (f, detected) in [ - ([vec![0x7A; 64], flac.clone()].concat(), None), - ([tag.clone(), vec![0x7A; 16], flac.clone()].concat(), Some(Container::MpegAudio)), - ([tag.clone(), tag, flac.clone()].concat(), Some(Container::MpegAudio)), - ] { - assert_eq!(detect_container(&f, None), detected); - let info = probe(&f, None).expect("empty FLAC after a prefix"); - assert_eq!((info.container, info.sample_rate, info.channels, info.frames), (Container::Flac, 48_000, 1, 0)); - assert_eq!(decode(&f, None).unwrap().1.frames(), 0); - } -} - -/// Build one MPEG-4 AAC-LC ADTS frame at 48 kHz stereo around `payload`, with the 13-bit length covering the 7-byte -/// header. -fn adts_frame(payload: &[u8]) -> Vec { - // MPEG-4 AAC-LC, 48 kHz, stereo; the 13-bit frame length includes this 7-byte header. - let len = 7 + payload.len(); - let mut h = [0xFF, 0xF1, 0x4C, 0x00, 0x00, 0x1F, 0xFC]; - h[3] = 0x80 | ((len >> 11) & 0x03) as u8; // stereo channel config low bits - h[4] = ((len >> 3) & 0xFF) as u8; - h[5] = (((len & 0x07) as u8) << 5) | 0x1F; - [&h[..], payload].concat() -} - -/// False MPEG sync prefixes must not stop a following zero-frame FLAC from probing as empty. -#[test] -fn zero_frame_flac_after_a_false_mpeg_sync_is_still_empty() { - let flac = - encode(&AudioBuffer::new(48_000, 1, 0), &EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int16).with_dither(false)).unwrap(); - for junk in [vec![0xFF, 0xE0, 0x00], vec![0xFF, 0xF0, 0x00], vec![0xFF, 0xFB, 0xF0, 0x00]] { - let f = [junk, flac.clone()].concat(); - let info = probe(&f, None).expect("empty FLAC after a false sync"); - assert_eq!((info.container, info.sample_rate, info.channels, info.frames), (Container::Flac, 48_000, 1, 0)); - assert_eq!(decode(&f, None).unwrap().1.frames(), 0); - } -} - /// A false MPEG sync prefix must not let malformed CAF or MP4 size fields bypass the container preflight. #[test] fn a_false_sync_does_not_bypass_container_checks() { @@ -558,218 +190,9 @@ fn a_false_sync_does_not_bypass_container_checks() { assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); } -/// Container magic inside a valid ADTS payload must not override AAC detection or make probing fail. -#[test] -fn a_valid_adts_stream_with_incidental_container_magic_still_probes() { - let payload = [0u8; 400]; - let mut frames: Vec> = (0..8).map(|_| adts_frame(&payload)).collect(); - let at = 100; // Inside frame 2's payload, leaving every frame header intact. - frames[2][7 + at..7 + at + 12].copy_from_slice(b"caff\0\x01\0\0kuki"); - let f: Vec = frames.concat(); - assert_eq!(detect_container(&f, None), Some(Container::Adts)); - let info = probe(&f, None).expect("valid ADTS with incidental container magic"); - assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Aac, 48_000, 2)); -} - -/// A later valid CAF must not excuse an earlier malformed container that the preflight or probe rejects. -#[test] -fn an_earlier_malformed_container_is_not_excused_by_a_later_valid_one() { - let malformed = caf(&[caf_desc(b"aac ", 0, 1024, 2, 0), (b"kuki", 1i64 << 50, vec![0; 8])]); - let pcm: Vec = (0..32i16).flat_map(|i| (i * 50).to_be_bytes()).collect(); - let data = [vec![0; 4], pcm].concat(); - let valid = caf(&[caf_desc(b"lpcm", 2, 1, 1, 16), (b"data", data.len() as i64, data)]); - let f = [vec![0u8; 32], malformed, valid].concat(); - assert!(matches!(probe(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); -} - -/// Truncated ID3 bodies, declared tag sizes beyond the file, and a complete tag with no audio after it are malformed -/// for both probe and decode. -#[test] -fn truncated_or_oversized_id3_tags_are_malformed() { - let cases = vec![[&id3_header(100)[..], b"xx"].concat(), id3_header(0x0FFF_FFFF).to_vec(), id3_tag(b"tag")]; - for f in cases { - assert!(matches!(probe(&f, None), Err(AudioError::Malformed(_)))); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(_)))); - } -} - -#[test] -fn wav_info_entries_beyond_the_file_are_refused() { - let alaw = |len: u32| { - let info = [&b"INFO"[..], b"INAM", &len.to_le_bytes(), b"hi"].concat(); - riff(&[(b"fmt ", [fmt(6, 1, 8_000, 8), vec![0, 0]].concat()), (b"LIST", info), (b"data", vec![0xD5; 800])]) - }; - assert_eq!(decode(&alaw(2), None).unwrap().1.frames(), 800); - let mut f = alaw(0x7fff_fff0); - f[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); - let list = f.windows(4).position(|w| w == b"LIST").unwrap(); - f[list + 4..list + 8].copy_from_slice(&0x7fff_fffcu32.to_le_bytes()); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); -} - -#[test] -fn a_wave_behind_another_riff_form_is_checked() { - let info = [&b"INFO"[..], b"INAM", &0x7fff_fff0u32.to_le_bytes(), b"hi"].concat(); - let mut wav = riff(&[(b"fmt ", [fmt(6, 1, 8_000, 8), vec![0, 0]].concat()), (b"LIST", info), (b"data", vec![0xD5; 800])]); - wav[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); - let list = wav.windows(4).position(|w| w == b"LIST").unwrap(); - wav[list + 4..list + 8].copy_from_slice(&0x7fff_fffcu32.to_le_bytes()); - // The probe skips the AVI form and reads the WAVE behind it. - let f = [&b"RIFF"[..], &4u32.to_le_bytes(), b"AVI ", &wav].concat(); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); -} - -#[test] -fn wav_info_entries_are_found_where_symphonia_reads_them() { - let list = [&b"LIST"[..], &0x7fff_fffcu32.to_le_bytes(), b"INFO", b"INAM", &0x7fff_fff0u32.to_le_bytes(), b"hi"].concat(); - let alaw = |extra: u16| (b"fmt ", [fmt(6, 1, 8_000, 8), extra.to_le_bytes().to_vec()].concat()); - // A-law's extra bytes are read past its chunk; an odd list is padded twice. - let files = - [riff(&[alaw(12), (b"JUNK", [&[0; 4][..], &list].concat())]), [riff(&[alaw(0), (b"LIST", b"adtl\0".to_vec())]), vec![0], list].concat()]; - for mut f in files { - f[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file"))); - } -} - -#[test] -fn many_tiny_chunks_terminate() { - let mut chunks: Vec<(&[u8; 4], Vec)> = vec![(b"fmt ", fmt(1, 1, 8_000, 16))]; - for _ in 0..200_000 { - chunks.push((b"pad ", Vec::new())); - } - let wav = riff(&chunks); - assert!(decode(&wav, None).is_err()); // no data chunk within the scan limit -} - -#[test] -fn hand_built_wav_variants() { - // 8-bit unsigned. - let wav = riff(&[(b"fmt ", fmt(1, 1, 8_000, 8)), (b"data", vec![0x80, 0xFF, 0x00])]); - let (info, buf) = decode(&wav, None).unwrap(); - assert_eq!(info.sample_format, SampleFormat::Int8); - assert_eq!(buf.channels[0], vec![0.0, 127.0 / 128.0, -1.0]); - // 64-bit float, with NaN replaced by silence. - let mut data = Vec::new(); - for v in [0.25f64, -0.5, f64::NAN] { - data.extend_from_slice(&v.to_le_bytes()); - } - let wav = riff(&[(b"fmt ", fmt(3, 1, 8_000, 64)), (b"data", data)]); - let (info, buf) = decode(&wav, None).unwrap(); - assert_eq!(info.sample_format, SampleFormat::Float64); - assert_eq!(buf.channels[0], vec![0.25, -0.5, 0.0]); - // Unsupported PCM width. - let wav = riff(&[(b"fmt ", fmt(3, 1, 8_000, 16)), (b"data", vec![0; 4])]); - assert!(matches!(decode(&wav, None), Err(AudioError::Unsupported(_)))); - // No data chunk / no fmt chunk. - assert!(decode(&riff(&[(b"fmt ", fmt(1, 1, 8_000, 16))]), None).is_err()); - assert!(decode(&riff(&[(b"data", vec![0; 4])]), None).is_err()); - // Short fmt chunk. - assert!(decode(&riff(&[(b"fmt ", vec![1, 0, 1]), (b"data", vec![0; 4])]), None).is_err()); - // Unknown codec tag goes to symphonia and fails cleanly. - let wav = riff(&[(b"fmt ", fmt(0x1234, 1, 8_000, 16)), (b"data", vec![0; 4])]); - assert!(decode(&wav, None).is_err()); -} - -#[test] -fn aiff_sowt_little_endian() { - let be = small(EncodeFormat::Aiff, BitDepth::Int16, 2); - let (_, expect) = decode(&be, None).unwrap(); - // Rebuild as AIFC/sowt by hand. - let comm = be.windows(4).position(|w| w == b"COMM").unwrap(); - let ssnd = be.windows(4).position(|w| w == b"SSND").unwrap(); - let mut comm_body = be[comm + 8..comm + 26].to_vec(); - comm_body.extend_from_slice(b"sowt"); - comm_body.extend_from_slice(&[0, 0]); // empty pstring, padded - let mut ssnd_body = be[ssnd + 8..].to_vec(); - for pair in ssnd_body[8..].as_chunks_mut::<2>().0 { - pair.swap(0, 1); - } - let mut body = b"AIFC".to_vec(); - for (id, data) in [(b"COMM", &comm_body), (b"SSND", &ssnd_body)] { - body.extend_from_slice(id); - body.extend_from_slice(&(data.len() as u32).to_be_bytes()); - body.extend_from_slice(data); - } - let mut f = b"FORM".to_vec(); - f.extend_from_slice(&(body.len() as u32).to_be_bytes()); - f.extend_from_slice(&body); - let (info, got) = decode(&f, None).unwrap(); - assert_eq!(info.sample_format, SampleFormat::Int16); - assert_eq!(got, expect); -} - -#[test] -fn detect_container_by_magic_and_hint() { - assert_eq!(detect_container(&small(EncodeFormat::Wav, BitDepth::Int16, 1), Some("mp3")), Some(Container::Wav)); - assert_eq!(detect_container(&small(EncodeFormat::Aiff, BitDepth::Int16, 1), None), Some(Container::Aiff)); - assert_eq!(detect_container(&small(EncodeFormat::Flac, BitDepth::Int16, 1), None), Some(Container::Flac)); - assert_eq!(detect_container(b"OggS\0\x02rest", None), Some(Container::Ogg)); - assert_eq!(detect_container(b"caff\0\x01\0\0", None), Some(Container::Caf)); - assert_eq!(detect_container(b"ID3\x04\0\0\0\0\0\x00", None), Some(Container::MpegAudio)); - let mut id3_flac = b"ID3\x04\0\0\0\0\0\x02xx".to_vec(); - id3_flac.extend_from_slice(b"fLaC"); - assert_eq!(detect_container(&id3_flac, None), Some(Container::Flac)); - assert_eq!(detect_container(&[0xFF, 0xFB, 0x90, 0x00], None), Some(Container::MpegAudio)); - assert_eq!(detect_container(&[0xFF, 0xF1, 0x50, 0x80], None), Some(Container::Adts)); - assert_eq!(detect_container(&[0x0B, 0x77, 0x00, 0x00], None), Some(Container::Ac3)); - let mut m4a = b"\0\0\0\x20ftypM4A ".to_vec(); - m4a.extend_from_slice(b"....stsd\0\0\0\0\0\0\0\x01\0\0\0\x24alac"); - assert_eq!(detect_container(&m4a, None), Some(Container::Mp4)); - assert_eq!(detect_container(b"\0\0\0\x20ftypM4A ", None), Some(Container::Mp4)); - assert_eq!(detect_container(b"\0\0\0\x14ftypqt ", None), Some(Container::QuickTime)); - assert_eq!(detect_container(b"", Some(".WAV")), Some(Container::Wav)); - assert_eq!(detect_container(b"zz", Some("aif")), Some(Container::Aiff)); - assert_eq!(detect_container(b"zz", Some("m4a")), Some(Container::Mp4)); - assert_eq!(detect_container(b"zz", Some("M4B")), Some(Container::Mp4)); - assert_eq!(detect_container(b"zz", Some("webm")), Some(Container::WebM)); - assert_eq!(detect_container(b"zz", Some("flac")), Some(Container::Flac)); - assert_eq!(detect_container(b"zz", Some("xyz")), None); - assert_eq!(detect_container(b"zz", None), None); - assert_eq!(detect_container(b"", None), None); -} - -#[test] -fn garbage_in_compressed_containers_errors() { - let garbage: Vec = (0..4096u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); - for hint in [None, Some("mp3"), Some("ogg"), Some("flac"), Some("m4a"), Some("caf"), Some("aac"), Some("mkv"), Some("wav"), Some("aiff")] { - assert!(decode(&garbage, hint).is_err(), "{hint:?}"); - assert!(probe(&garbage, hint).is_err(), "{hint:?}"); - } - for magic in [&b"fLaC"[..], b"OggS", b"caff", b"ID3\x03\0\0\0\0\0\0", &[0xFF, 0xFB, 0x90, 0x00], b"\0\0\0\x20ftypM4A "] { - let mut f = magic.to_vec(); - f.extend_from_slice(&garbage); - let _ = probe(&f, None); - assert!(decode(&f, None).map(|(_, b)| b.frames()).unwrap_or(0) < 1_000_000); - } - assert!(decode(&[], None).is_err()); -} - -/// A marker that passes its container check must not let the probe select a different container -/// without its own checks: the reader is refused when the probed format disagrees. -#[test] -fn a_probed_container_that_disagrees_with_the_checked_marker_is_refused() { - // The junk byte hides both magics, so the hint picks the marker: the FLAC is checked, but the - // probe reads the WAVE before it. - let bytes = [vec![0], small(EncodeFormat::Wav, BitDepth::Int24, 2), small(EncodeFormat::Flac, BitDepth::Int24, 2)].concat(); - match decode(&bytes, Some("flac")) { - Err(AudioError::Malformed(message)) => assert!(message.contains("probed container"), "unexpected message: {message}"), - Err(other) => panic!("unexpected error kind: {other:?}"), - Ok(_) => panic!("the mismatched container must be refused"), - } -} - proptest! { #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] - #[test] - fn random_bytes_never_panic(bytes in proptest::collection::vec(any::(), 0..2048), hint in 0usize..6) { - let hint = [None, Some("wav"), Some("aiff"), Some("flac"), Some("mp3"), Some("ogg")][hint]; - let _ = detect_container(&bytes, hint); - let _ = probe(&bytes, hint); - let _ = decode(&bytes, hint); - } #[test] fn random_bodies_behind_valid_headers_never_panic(body in proptest::collection::vec(any::(), 0..1024), which in 0usize..4) { @@ -784,97 +207,6 @@ proptest! { let _ = decode(&f, None); } - #[test] - fn random_audio_roundtrips_through_flac(samples in proptest::collection::vec(-1.2f32..1.2, 1..3000), channels in 1usize..4) { - let buf = AudioBuffer::from_interleaved(48_000, channels as u16, &samples); - prop_assume!(buf.frames() > 0); - let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int24).with_dither(false); - let (_, flac) = decode(&encode(&buf, &opts).unwrap(), None).unwrap(); - let (_, wav) = decode(&encode(&buf, &opts.clone().with_format(EncodeFormat::Wav)).unwrap(), None).unwrap(); - prop_assert_eq!(flac, wav); - } -} - -/// An extensible `fmt ` chunk: cbSize, valid bits, mask, then the 16-byte subtype GUID. -fn extensible_fmt(cb_size: u16, valid_bits: u16, guid: &[u8]) -> Vec { - let mut f = fmt(0xFFFE, 1, 44_100, 16); - f.extend_from_slice(&cb_size.to_le_bytes()); - f.extend_from_slice(&valid_bits.to_le_bytes()); - f.extend_from_slice(&4u32.to_le_bytes()); - f.extend_from_slice(guid); - f -} - -const PCM_GUID: [u8; 16] = [1, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xAA, 0, 0x38, 0x9B, 0x71]; - -#[test] -fn extensible_fmt_is_checked_in_full() { - let data = vec![0u8; 8]; - let good = riff(&[(b"fmt ", extensible_fmt(22, 16, &PCM_GUID)), (b"data", data.clone())]); - assert_eq!(probe(&good, None).unwrap().sample_format, SampleFormat::Int16); - // Subtype GUID cut short after the format code. - let cut = riff(&[(b"fmt ", extensible_fmt(22, 16, &PCM_GUID[..4])), (b"data", data.clone())]); - assert!(matches!(probe(&cut, None), Err(AudioError::Malformed(_)))); - assert!(matches!(decode(&cut, None), Err(AudioError::Malformed(_)))); - // cbSize too small for the extension. - let small_cb = riff(&[(b"fmt ", extensible_fmt(0, 16, &PCM_GUID)), (b"data", data.clone())]); - assert!(matches!(probe(&small_cb, None), Err(AudioError::Malformed(_)))); - // More valid bits than the 16-bit container holds. - let wide = riff(&[(b"fmt ", extensible_fmt(22, 24, &PCM_GUID)), (b"data", data.clone())]); - assert!(matches!(probe(&wide, None), Err(AudioError::Malformed(_)))); - // PCM-like prefix but a foreign GUID tail is not read as native PCM. - let mut foreign = PCM_GUID; - foreign[15] ^= 0xFF; - let foreign = riff(&[(b"fmt ", extensible_fmt(22, 16, &foreign)), (b"data", data)]); - assert!(!matches!(probe(&foreign, None), Ok(i) if i.sample_format == SampleFormat::Int16)); - // The Ambisonic PCM subtype is PCM. - let ambi = [1, 0, 0, 0, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0, 0, 0]; - let ambi = riff(&[(b"fmt ", extensible_fmt(22, 16, &ambi)), (b"data", vec![0u8; 8])]); - assert_eq!(probe(&ambi, None).unwrap().sample_format, SampleFormat::Int16); -} - -#[test] -fn aiff_frames_without_sound_data_are_malformed() { - // COMM declares 300 frames, and the file ends before any SSND chunk - let full = small(EncodeFormat::Aiff, BitDepth::Int16, 1); - let ssnd = full.windows(4).position(|w| w == b"SSND").unwrap(); - let mut f = full[..ssnd].to_vec(); - let size = (f.len() - 8) as u32; - f[4..8].copy_from_slice(&size.to_be_bytes()); - assert!(matches!(probe(&f, None), Err(AudioError::Malformed(_)))); - // with no frames declared, no SSND is needed (AIFF 1.3) - let comm = f.windows(4).position(|w| w == b"COMM").unwrap(); - f[comm + 10..comm + 14].fill(0); - assert_eq!(probe(&f, None).unwrap().frames, 0); -} - -#[test] -fn an_empty_flac_has_one_track() { - use craft_audio::{DecodeOptions, decode_with}; - // STREAMINFO: 4096-frame blocks, 44.1 kHz, 2 channels, 16 bits, no samples - let mut f = b"fLaC".to_vec(); - f.extend_from_slice(&[0x80, 0, 0, 34]); - f.extend_from_slice(&[0x10, 0x00, 0x10, 0x00, 0, 0, 0, 0, 0, 0]); - f.extend_from_slice(&((44_100u64 << 44) | (1 << 41) | (15 << 36)).to_be_bytes()); - f.extend_from_slice(&[0; 16]); - assert_eq!(decode_with(&f, None, &DecodeOptions::default().with_track(0)).unwrap().1.frames(), 0); - let e = decode_with(&f, None, &DecodeOptions::default().with_track(1)).unwrap_err(); - assert!(matches!(e, AudioError::Unsupported(_)), "{e}"); -} - -/// A damaged MP4 or Matroska file is malformed when symphonia cannot read it either, as it is -/// without symphonia. -#[test] -fn damaged_mp4_and_matroska_are_malformed() { - // an `ftyp` box and nothing after it: no `moov` - let mp4 = [&16u32.to_be_bytes()[..], b"ftypisom", &[0, 0, 2, 0]].concat(); - // an EBML header naming Matroska and nothing after it: no Segment - let mkv = [&[0x1A, 0x45, 0xDF, 0xA3, 0x8B, 0x42, 0x82, 0x88][..], b"matroska"].concat(); - for f in [mp4, mkv] { - assert!(matches!(decode(&f, None), Err(AudioError::Malformed(_))), "{:?}", decode(&f, None)); - assert!(matches!(probe(&f, None), Err(AudioError::Malformed(_)))); - assert!(matches!(craft_audio::tracks(&f, None), Err(AudioError::Malformed(_)))); - } } /// FLAC in MP4 is decoded by symphonia (PCM, AAC, ALAC, Opus, AC-3, MPEG audio are native), so diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 35f1b15684..2e58cd6332 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -1,7 +1,4 @@ -use craft_audio::{ - AudioBuffer, BitDepth, BwfInfo, ChannelLayout, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, - wav_float_header, -}; +use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe}; fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer { let mut b = AudioBuffer::new(sr, channels as u16, frames); @@ -20,7 +17,6 @@ fn tolerance(depth: BitDepth, dither: bool) -> f32 { BitDepth::Int24 => 1.0 / 8_388_608.0, BitDepth::Int32 => 1e-7, BitDepth::Float32 => 0.0, - _ => unreachable!("a bit depth this test does not know"), }; lsb * if dither { 1.6 } else { 0.6 } + 1e-7 } @@ -39,7 +35,6 @@ fn expected_sf(d: BitDepth) -> SampleFormat { BitDepth::Int24 => SampleFormat::Int24, BitDepth::Int32 => SampleFormat::Int32, BitDepth::Float32 => SampleFormat::Float32, - _ => unreachable!("a bit depth this test does not know"), } } @@ -69,346 +64,3 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } } - -#[test] -fn flac_roundtrip_is_lossless_vs_wav() { - for depth in [BitDepth::Int16, BitDepth::Int24, BitDepth::Int32] { - for channels in [1, 2, 3, 4, 5, 6, 7, 8] { - // Spans several blocks plus a short final block. - let src = sine(44_100, channels, 4096 * 2 + 17); - let wav = encode(&src, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(depth).with_dither(false)).unwrap(); - let flac = encode(&src, &EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(depth).with_dither(false)).unwrap(); - assert_eq!(detect_container(&flac, None), Some(craft_audio::Container::Flac)); - let info = probe(&flac, None).unwrap(); - assert_eq!((info.container, info.codec), (craft_audio::Container::Flac, craft_audio::CodecId::Flac)); - assert_eq!((info.sample_rate, info.channels as usize, info.frames), (44_100, channels, src.frames() as u64)); - assert_eq!(info.sample_format, expected_sf(depth)); - let (_, from_wav) = decode(&wav, None).unwrap(); - let (finfo, from_flac) = decode(&flac, None).unwrap(); - assert_eq!(finfo.frames, src.frames() as u64); - assert_eq!(from_flac, from_wav, "{depth:?} {channels}ch"); - if depth != BitDepth::Int32 { - assert!(flac.len() < wav.len(), "{depth:?} {channels}ch: flac {} >= wav {}", flac.len(), wav.len()); - } - } - } -} - -#[test] -fn flac_handles_silence_noise_full_scale_and_odd_rates() { - let frames = 10_000; - let mut b = AudioBuffer::new(37_123, 3, frames); - let mut seed = 1u32; - for i in 0..frames { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - b.channels[1][i] = (seed as f32 / u32::MAX as f32) * 2.0 - 1.0; // white noise - b.channels[2][i] = if i % 2 == 0 { 1.5 } else { -1.5 }; // clipped full-scale square - } - for depth in [BitDepth::Int16, BitDepth::Int24, BitDepth::Int32] { - for dither in [false, true] { - let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(depth).with_dither(dither); - let flac = encode(&b, &opts).unwrap(); - let (info, out) = decode(&flac, None).unwrap(); - assert_eq!(info.sample_rate, 37_123); - let wav = encode(&b, &opts.clone().with_format(EncodeFormat::Wav)).unwrap(); - let (_, expect) = decode(&wav, None).unwrap(); - assert_eq!(out, expect, "{depth:?} dither={dither}"); - } - } -} - -/// 16-bit audio exported at a larger depth costs no more: the padding is not coded. -#[test] -fn flac_does_not_store_padding() { - let mut src = sine(48_000, 2, 20_000); - for s in src.channels.iter_mut().flatten() { - *s = (*s * 32768.0).round() / 32768.0; - } - let size = |depth| { - let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(depth).with_dither(false); - let flac = encode(&src, &opts).unwrap(); - let (_, wav) = decode(&encode(&src, &opts.clone().with_format(EncodeFormat::Wav)).unwrap(), None).unwrap(); - assert_eq!(decode(&flac, None).unwrap().1, wav, "{depth:?}"); - flac.len() - }; - let base = size(BitDepth::Int16); - assert!(size(BitDepth::Int24) < base * 11 / 10); - assert!(size(BitDepth::Int32) < base * 11 / 10); -} - -#[test] -fn flac_rejects_unsupported_layouts() { - let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Float32).with_dither(false); - assert!(encode(&sine(48_000, 2, 10), &opts).is_err()); - let opts = opts.clone().with_bit_depth(BitDepth::Int16); - assert!(encode(&sine(48_000, 9, 10), &opts).is_err()); - assert!(encode(&sine(655_351, 1, 10), &opts).is_err()); - assert!(encode(&sine(655_350, 1, 10), &opts).is_ok()); - // Tiny buffers still encode and decode. - let one = sine(48_000, 2, 1); - let (_, out) = decode(&encode(&one, &opts).unwrap(), None).unwrap(); - assert_eq!(out.frames(), 1); -} - -#[test] -fn bwf_roundtrip() { - let bwf = BwfInfo::default() - .with_description("Scene 12 take 3") - .with_originator("SoundCraft") - .with_originator_reference("SC-0001") - .with_origination("2026-10-06", "12:34:56") - .with_time_reference(0x1_2345_6789); // > 32 bits - let src = sine(96_000, 2, 1000); - // RF64 is a WAV layout: other formats ignore it. - let aiff = encode(&src, &EncodeOptions::new(EncodeFormat::Aiff).with_force_rf64(true)).unwrap(); - assert_eq!(&aiff[..4], b"FORM"); - let flac = encode(&src, &EncodeOptions::new(EncodeFormat::Flac).with_force_rf64(true)).unwrap(); - assert_eq!(&flac[..4], b"fLaC"); - for depth in DEPTHS { - let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(depth).with_dither(false).with_bwf(bwf.clone()); - let bytes = encode(&src, &opts).unwrap(); - let info = probe(&bytes, None).unwrap(); - assert_eq!(info.bwf.as_ref(), Some(&bwf)); - let (dinfo, _) = decode(&bytes, None).unwrap(); - assert_eq!(dinfo.bwf, Some(bwf.clone())); - // RF64 layout reads back identically. - let rf64 = encode(&src, &opts.clone().with_force_rf64(true)).unwrap(); - assert_eq!(&rf64[..4], b"RF64"); - let (rinfo, rbuf) = decode(&rf64, None).unwrap(); - assert_eq!(rinfo.bwf, Some(bwf.clone())); - assert_eq!(rinfo.frames, 1000); - assert_eq!(rbuf, decode(&bytes, None).unwrap().1); - } - // Overlong strings are truncated to the field width, not an error. - let long = BwfInfo::default().with_description("x".repeat(400)); - let bytes = encode(&src, &EncodeOptions::default().with_bwf(long)).unwrap(); - assert_eq!(probe(&bytes, None).unwrap().bwf.unwrap().description.len(), 256); -} - -#[test] -fn wav_header_layout() { - let b = encode(&sine(44_100, 2, 10), &EncodeOptions::default().with_bit_depth(BitDepth::Int16)).unwrap(); - // Plain PCM for 16-bit stereo; extensible otherwise. - let fmt = b.windows(4).position(|w| w == b"fmt ").unwrap(); - assert_eq!(u16::from_le_bytes([b[fmt + 8], b[fmt + 9]]), 1); - let b = encode(&sine(44_100, 2, 10), &EncodeOptions::default()).unwrap(); - let fmt = b.windows(4).position(|w| w == b"fmt ").unwrap(); - assert_eq!(u16::from_le_bytes([b[fmt + 8], b[fmt + 9]]), 0xFFFE); - let riff = u32::from_le_bytes([b[4], b[5], b[6], b[7]]) as usize; - assert_eq!(riff + 8, b.len()); - // Odd data length (24-bit mono, odd frames) gets a pad byte. - let b = encode(&sine(44_100, 1, 3), &EncodeOptions::default()).unwrap(); - assert_eq!(b.len() % 2, 0); - assert_eq!(decode(&b, None).unwrap().1.frames(), 3); -} - -#[test] -fn aiff_float_is_aifc() { - let b = encode(&sine(44_100, 2, 10), &EncodeOptions::new(EncodeFormat::Aiff).with_bit_depth(BitDepth::Float32)).unwrap(); - assert_eq!(&b[8..12], b"AIFC"); - assert!(b.windows(4).any(|w| w == b"fl32")); - let b = encode(&sine(44_100, 2, 10), &EncodeOptions::new(EncodeFormat::Aiff)).unwrap(); - assert_eq!(&b[8..12], b"AIFF"); - let form = u32::from_be_bytes([b[4], b[5], b[6], b[7]]) as usize; - assert_eq!(form + 8, b.len()); -} - -#[test] -fn unusual_sample_rates_roundtrip() { - for sr in [1, 8_000, 11_025, 22_050, 44_100, 88_200, 176_400, 192_000, 352_800, 384_000, 768_000] { - for format in [EncodeFormat::Wav, EncodeFormat::Aiff] { - let bytes = encode(&sine(sr, 1, 8), &EncodeOptions::new(format)).unwrap(); - assert_eq!(probe(&bytes, None).unwrap().sample_rate, sr, "{format:?}"); - } - } -} - -#[test] -fn encode_rejects_bad_buffers_and_formats() { - assert!(encode(&AudioBuffer::default(), &EncodeOptions::default()).is_err()); - assert!(encode(&AudioBuffer::new(0, 2, 10), &EncodeOptions::default()).is_err()); - // Formats `encode` cannot write are not `EncodeFormat` variants, so asking for one does not compile. - // Non-finite samples are sanitized; only integer output clips finite samples. - let mut b = AudioBuffer::new(48_000, 1, 4); - b.channels[0] = vec![f32::NAN, f32::INFINITY, -5.0, 0.5]; - for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] { - for depth in DEPTHS { - if format == EncodeFormat::Flac && depth == BitDepth::Float32 { - continue; - } - let bytes = encode(&b, &EncodeOptions::new(format).with_bit_depth(depth)).unwrap(); - let (_, out) = decode(&bytes, None).unwrap(); - assert_eq!(out.channels[0][0], 0.0); - assert!(out.channels[0][1] > 0.99 && out.channels[0][1] <= 1.0); - assert_eq!(out.channels[0][2], if depth == BitDepth::Float32 { -5.0 } else { -1.0 }); - } - } - // Ragged buffers encode the common length. - let ragged = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.1; 10], vec![0.2; 7]] }; - let (_, out) = decode(&encode(&ragged, &EncodeOptions::default()).unwrap(), None).unwrap(); - assert_eq!(out.frames(), 7); -} - -#[test] -fn audio_buffer_helpers() { - let b = AudioBuffer::from_interleaved(48_000, 2, &[0.1, -0.2, 0.3, -0.4, 0.5]); - assert_eq!(b.frames(), 2); - assert_eq!(b.num_channels(), 2); - assert_eq!(b.interleaved(), vec![0.1, -0.2, 0.3, -0.4]); - assert!((b.peak() - 0.4).abs() < 1e-7); - assert!((b.duration_secs() - 2.0 / 48_000.0).abs() < 1e-12); - assert_eq!(AudioBuffer::from_interleaved(1, 0, &[1.0]).num_channels(), 0); - assert_eq!(AudioBuffer::new(0, 1, 5).duration_secs(), 0.0); - assert_eq!(AudioBuffer::default().frames(), 0); -} - -#[cfg(feature = "serde")] -#[test] -fn serde_types_roundtrip() { - let opts = EncodeOptions::default().with_bwf(BwfInfo::default().with_time_reference(42)); - let s = serde_json::to_string(&opts).unwrap(); - assert_eq!(serde_json::from_str::(&s).unwrap(), opts); - let info = probe(&encode(&sine(48_000, 1, 4), &opts).unwrap(), None).unwrap(); - let s = serde_json::to_string(&info).unwrap(); - assert_eq!(serde_json::from_str::(&s).unwrap(), info); - // A layout reads back only when its mask describes its channel count. - let l = ChannelLayout::SURROUND_5_1; - assert_eq!(serde_json::from_str::(&serde_json::to_string(&l).unwrap()).unwrap(), l); - assert_eq!(serde_json::from_str::(r#"{"channels":4,"mask":0}"#).unwrap(), ChannelLayout::unordered(4)); - assert!(serde_json::from_str::(r#"{"channels":2,"mask":63}"#).is_err()); - assert!(serde_json::from_str::(r#"{"channels":1,"mask":2147483648}"#).is_err()); -} - -#[test] -fn multichannel_wav_speaker_masks() { - let buf = |n: usize| AudioBuffer { sample_rate: 48_000, channels: (0..n).map(|c| vec![0.01 * c as f32; 64]).collect() }; - let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_dither(false); - for (n, mask) in [(6usize, 0x3Fu32), (8, 0x63F), (12, 0x2_D63F)] { - let bytes = craft_audio::encode(&buf(n), &opts).unwrap(); - assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::from_mask(mask), "{n} channels"); - assert_eq!(craft_audio::decode(&bytes, Some("wav")).unwrap().1.channels.len(), n); - } - // Explicit masks: 7.0 (sides + rears, no LFE) and Ambisonics (no positions). - let bytes = craft_audio::encode(&buf(7), &opts.clone().with_layout(ChannelLayout::from_mask(0x637))).unwrap(); - assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::from_mask(0x637)); - let bytes = craft_audio::encode(&buf(4), &opts.clone().with_layout(ChannelLayout::unordered(4))).unwrap(); - assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::unordered(4)); - // Plain 16-bit stereo stays a plain PCM header (format tag 1), read back as stereo. - let o16 = opts.clone().with_bit_depth(BitDepth::Int16); - let bytes = craft_audio::encode(&buf(2), &o16.clone().with_layout(ChannelLayout::STEREO)).unwrap(); - let fmt = bytes.windows(4).position(|w| w == b"fmt ").unwrap(); - assert_eq!(bytes.get(fmt + 8..fmt + 10), Some(&[1u8, 0][..])); - assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::STEREO); - // FLAC (decoded by symphonia) reports its channel assignment: six channels are 5.1. - let flac = o16.clone().with_format(EncodeFormat::Flac); - let info = probe(&craft_audio::encode(&buf(6), &flac).unwrap(), None).unwrap(); - assert_eq!((info.container, info.codec, info.layout), (craft_audio::Container::Flac, craft_audio::CodecId::Flac, ChannelLayout::SURROUND_5_1)); - // A layout for another channel count is refused. - assert!(craft_audio::encode(&buf(2), &o16.clone().with_layout(ChannelLayout::SURROUND_5_1)).is_err()); -} - -#[test] -fn float_wav_header_is_rewritten_in_place_as_the_file_grows() { - let take = sine(48_000, 2, 1_000); - let mut file = wav_float_header(48_000, 2, 0).unwrap(); - let len = file.len(); - file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes())); - assert_eq!(decode(&file, None).unwrap().1.frames(), 1_000); - file[..len].copy_from_slice(&wav_float_header(48_000, 2, 600).unwrap()); - assert_eq!(decode(&file, None).unwrap().1.frames(), 600); - file[..len].copy_from_slice(&wav_float_header(48_000, 2, 1_000).unwrap()); - assert_eq!(file, encode(&take, &EncodeOptions::default().with_bit_depth(BitDepth::Float32)).unwrap()); - let big = wav_float_header(48_000, 2, 600_000_000).unwrap(); - assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len)); - assert!(wav_float_header(48_000, 0, 0).is_err()); -} - -#[test] -fn zero_frame_flac_round_trips_like_wav_and_aiff() { - for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] { - for depth in [BitDepth::Int16, BitDepth::Int24] { - for channels in [1, 2] { - let opts = EncodeOptions::new(format).with_bit_depth(depth); - let bytes = encode(&AudioBuffer::new(48_000, channels, 0), &opts).unwrap(); - let info = probe(&bytes, None).unwrap(); - assert_eq!((info.container, info.sample_format, info.sample_rate, info.frames), (format.container(), expected_sf(depth), 48_000, 0)); - assert_eq!(info.channels, channels); - let (info, buf) = decode(&bytes, None).unwrap(); - assert_eq!((info.frames, buf.frames(), buf.num_channels()), (0, 0, channels)); - } - } - } -} - -#[test] -fn flac_claiming_frames_but_holding_none_still_errors() { - let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int16); - let mut bytes = encode(&AudioBuffer::new(48_000, 2, 0), &opts).unwrap(); - bytes[25] = 1; // STREAMINFO total samples (low byte of the 36-bit field) = 1 - assert!(decode(&bytes, None).is_err()); -} - -#[test] -fn float_wav_header_rejects_a_frame_count_whose_total_size_overflows() { - // 4 bytes per frame: the data length fits in u64, but adding the header to it does not. - let frames = u64::MAX / 4; - assert!(matches!(wav_float_header(48_000, 1, frames), Err(craft_audio::AudioError::TooLarge(_)))); -} - -#[test] -fn dither_changes_integer_output() { - // a quiet signal whose samples fall between the integer levels - let mut src = AudioBuffer::new(48_000, 1, 4800); - for (i, s) in src.channels[0].iter_mut().enumerate() { - *s = 0.001 * (i as f32 * 0.01).sin(); - } - for depth in [BitDepth::Int16, BitDepth::Int24, BitDepth::Int32] { - let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(depth); - let plain = encode(&src, &opts.clone().with_dither(false)).unwrap(); - let dithered = encode(&src, &opts.with_dither(true)).unwrap(); - assert_ne!(plain, dithered, "{depth:?}"); - } -} - -#[test] -fn bwf_text_is_cut_at_a_character_boundary() { - // 255 ASCII bytes then a 2-byte character: the 256-byte description field cannot hold it - let description = format!("{}é", "a".repeat(255)); - let bwf = BwfInfo::default().with_description(&description); - let opts = EncodeOptions::new(EncodeFormat::Wav).with_bwf(bwf); - let info = probe(&encode(&sine(48_000, 1, 100), &opts).unwrap(), None).unwrap(); - assert_eq!(info.bwf.unwrap().description, "a".repeat(255)); -} - -#[test] -fn a_byte_rate_past_32_bits_is_an_error() { - // 4 GHz × 8 bytes per frame does not fit the 32-bit nAvgBytesPerSec field - assert!(matches!(wav_float_header(4_000_000_000, 2, 0), Err(craft_audio::AudioError::Encode(_)))); - assert!(wav_float_header(4_000_000_000 / 8, 2, 0).is_ok()); -} - -/// The channel mask comment of a FLAC file is its layout, for `probe`, `decode` and `Decoder`, and -/// for a file with no audio frames. -#[test] -fn flac_layouts_read_back_from_the_mask_comment() { - use craft_audio::{DecodeOptions, Decoder}; - let cases = [ - (6, Some(ChannelLayout::SURROUND_5_1_SIDE), ChannelLayout::SURROUND_5_1_SIDE), - (6, None, ChannelLayout::SURROUND_5_1), - (7, Some(ChannelLayout::SURROUND_6_1), ChannelLayout::SURROUND_6_1), - (7, None, ChannelLayout::default_for(7)), - (4, Some(ChannelLayout::from_mask(0x107)), ChannelLayout::from_mask(0x107)), - (2, Some(ChannelLayout::unordered(2)), ChannelLayout::unordered(2)), - ]; - for (channels, layout, expected) in cases { - for frames in [4096, 0] { - let mut opts = EncodeOptions::new(EncodeFormat::Flac); - opts.layout = layout; - let file = craft_audio::encode(&AudioBuffer::new(48_000, channels, frames), &opts).unwrap(); - assert_eq!(probe(&file, None).unwrap().layout, expected, "probe {channels} {layout:?} {frames}"); - assert_eq!(decode(&file, None).unwrap().0.layout, expected, "decode {channels} {layout:?} {frames}"); - let dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap(); - assert_eq!(dec.info().layout, expected, "Decoder {channels} {layout:?} {frames}"); - } - } -} diff --git a/crates/audio/tests/audio/stream.rs b/crates/audio/tests/audio/stream.rs index 183bdab9c3..62ffb02b11 100644 --- a/crates/audio/tests/audio/stream.rs +++ b/crates/audio/tests/audio/stream.rs @@ -1,5 +1,5 @@ -use craft_audio::{AudioBuffer, AudioError, BitDepth, BwfInfo, ChannelLayout, EncodeFormat, EncodeOptions, FileEncoder, encode}; -use std::io::{Cursor, Seek, SeekFrom, Write}; +use craft_audio::{AudioBuffer, BitDepth, BwfInfo, ChannelLayout, EncodeFormat, EncodeOptions, FileEncoder, encode}; +use std::io::Cursor; fn tone(channels: usize, frames: usize) -> AudioBuffer { let channels = (0..channels).map(|c| (0..frames).map(|i| ((i * (c + 3)) as f32 * 0.013).sin() * 1.2).collect()).collect(); @@ -58,219 +58,3 @@ fn streamed_files_match_whole_buffer_encodes() { } } } - -/// A `Write + Seek` sink that accepts `budget` bytes in total and then fails every write, so -/// a `write_all` on it appends a prefix of the block and only then reports the error. -struct FailAfter { - inner: Cursor>, - budget: usize, -} - -impl Write for FailAfter { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - if self.budget == 0 { - return Err(std::io::Error::other("sink is full")); - } - let n = buf.len().min(self.budget); - self.budget -= n; - self.inner.write(&buf[..n]) - } - - fn flush(&mut self) -> std::io::Result<()> { - self.inner.flush() - } -} - -impl Seek for FailAfter { - fn seek(&mut self, pos: SeekFrom) -> std::io::Result { - self.inner.seek(pos) - } -} - -#[test] -fn a_failed_write_poisons_the_encoder() { - let buf = tone(2, 20_001); - for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] { - let opts = EncodeOptions::new(format).with_bit_depth(BitDepth::Int16).with_dither(false); - let sink = FailAfter { inner: Cursor::new(Vec::new()), budget: 256 }; - let mut enc = FileEncoder::new(sink, &opts, buf.sample_rate, 2).unwrap(); - // The sink accepts a prefix of the first block, then fails. - assert!(enc.write(&buf.channels, buf.frames()).is_err(), "{format:?}"); - // Later calls must not claim success: the bytes on the sink no longer match the - // encoder's counters (and for FLAC the failed frame's samples are already gone). - assert!(matches!(enc.write(&buf.channels, 16), Err(AudioError::Encode(_))), "{format:?}"); - assert!(matches!(enc.finish(), Err(AudioError::Encode(_))), "{format:?}"); - } -} - -#[test] -fn blocks_past_a_format_limit_are_refused_before_anything_is_written() { - let buf = tone(2, 100); - for (format, limit) in [(EncodeFormat::Aiff, 1u64 << 30), (EncodeFormat::Flac, 1u64 << 36)] { - let opts = EncodeOptions::new(format).with_bit_depth(BitDepth::Int16).with_dither(false); - let mut enc = FileEncoder::new(Cursor::new(Vec::new()), &opts, buf.sample_rate, 2).unwrap(); - enc.write(&buf.channels, 100).unwrap(); - assert!(enc.check_room(limit / 2).is_ok(), "{format:?}"); - assert!(matches!(enc.check_room(limit), Err(AudioError::TooLarge(_))), "{format:?}"); - if format == EncodeFormat::Flac { - // 100 frames are in: STREAMINFO counts up to 2^36 - 1 in all. - assert!(enc.check_room(limit - 101).is_ok()); - assert!(matches!(enc.check_room(limit - 100), Err(AudioError::TooLarge(_)))); - } - // A block that does not hold the frames it claims is refused before the limit is checked. - if let Ok(frames) = usize::try_from(limit) { - assert!(matches!(enc.write::>(&[], frames), Err(AudioError::Encode(_))), "{format:?}"); - } - assert_eq!(enc.finish().unwrap().into_inner(), encode(&buf, &opts).unwrap()); - } -} - -// A source that stops serving reads past `fail_from`, as a network-backed file might. -struct FlakySource { - bytes: Vec, - fail_from: u64, -} - -use craft_media::ByteSource; - -impl ByteSource for FlakySource { - fn len(&self) -> u64 { - self.bytes.len() as u64 - } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { - if offset + buf.len() as u64 > self.fail_from { - return Err(std::io::Error::other("connection reset")); - } - self.bytes.as_slice().read_at(offset, buf) - } -} - -#[test] -fn decoder_reads_any_read_seek_source_and_reports_source_failures() { - use craft_audio::{DecodeOptions, Decoder}; - use craft_media::ReadSeekSource; - let wav = encode(&tone(2, 48_000), &EncodeOptions::new(EncodeFormat::Wav)).unwrap(); - - // `ReadSeekSource` (any `Read + Seek`) is accepted, so a `BufReader` works the same way. - let source = ReadSeekSource::new(Cursor::new(wav.clone())).unwrap(); - let info = Decoder::open(source, Some("wav"), &DecodeOptions::default()).unwrap().probe().unwrap(); - assert_eq!((info.frames, info.damaged), (48_000, 0)); - - // A source failing half way through gives an I/O error, not concealed silence. - let half = wav.len() as u64 / 2; - let mut dec = Decoder::open(FlakySource { bytes: wav, fail_from: half }, Some("wav"), &DecodeOptions::default()).unwrap(); - let err = loop { - match dec.next_block() { - Ok(Some(_)) => continue, - Ok(None) => panic!("the source failure was not reported"), - Err(e) => break e, - } - }; - assert!(matches!(err, AudioError::Io(_)), "{err}"); - assert_eq!(dec.info().damaged, 0); -} - -#[test] -fn seeking_to_or_past_the_end_ends_the_stream() { - use craft_audio::{DecodeOptions, Decoder}; - let buf = tone(2, 4800); - for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] { - let file = encode(&buf, &EncodeOptions::new(format).with_bit_depth(BitDepth::Int16)).unwrap(); - for target in [4800, 4801, 1_000_000] { - let mut dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap(); - assert_eq!(dec.seek(target).unwrap(), 4800, "{format:?} seek({target})"); - assert!(dec.next_block().unwrap().is_none(), "{format:?} seek({target})"); - // Seeking back still works. - assert_eq!(dec.seek(4000).unwrap(), 4000, "{format:?}"); - let mut left = vec![Vec::new(); buf.channels.len()]; - while let Some(b) = dec.next_block().unwrap() { - for (l, c) in left.iter_mut().zip(b.channels) { - l.extend(c); - } - } - for (l, source) in left.iter().zip(&buf.channels) { - assert_eq!(l.len(), 800, "{format:?}"); - assert!(l.iter().zip(&source[4000..]).all(|(a, b)| (a - b.clamp(-1.0, 1.0)).abs() <= 2.0 / 32768.0), "{format:?}"); - } - } - } -} - -#[test] -fn single_track_files_refuse_other_track_indexes() { - use craft_audio::{DecodeOptions, decode_with}; - let buf = tone(1, 1000); - for format in [EncodeFormat::Wav, EncodeFormat::Aiff] { - let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); - assert!(decode_with(&file, None, &DecodeOptions::default().with_track(0)).is_ok(), "{format:?}"); - let e = decode_with(&file, None, &DecodeOptions::default().with_track(1)).unwrap_err(); - assert!(matches!(e, AudioError::Unsupported(_)), "{format:?}: {e}"); - } -} - -#[test] -fn short_or_missing_channels_are_refused_without_writing() { - let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16); - let mut enc = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, 2).unwrap(); - let left = vec![0.1f32; 4]; - // More frames than the channels hold, or too few channels: refused, nothing written. - assert!(matches!(enc.write(&[&left, &left], 10), Err(AudioError::Encode(_)))); - assert!(matches!(enc.write(&[&left], 4), Err(AudioError::Encode(_)))); - // The encoder is still usable. - enc.write(&[&left, &left], 4).unwrap(); - let wav = enc.finish().unwrap().into_inner(); - assert_eq!(craft_audio::probe(&wav, None).unwrap().frames, 4); -} - -/// A 48 kHz mono float PCM Matroska file: ten 10 ms blocks from `first_ns`, with block durations -/// when `durations` is set (otherwise its length is unknown), and a `CodecDelay` of `delay_ns`. -fn pcm_mkv(first_ns: i64, durations: bool, delay_ns: u64) -> Vec { - use craft_media::matroska::{LacingMode, MkvWriter, MuxOptions, TrackKind, TrackSpec}; - let mut spec = TrackSpec::new(TrackKind::Audio, "A_PCM/FLOAT/IEEE"); - spec.audio = Some((48_000.0, 1, Some(32))); - spec.codec_delay_ns = delay_ns; - let opts = MuxOptions { lacing: LacingMode::None, ..MuxOptions::default() }; - let mut w = MkvWriter::new(Cursor::new(Vec::new()), vec![spec], opts).unwrap(); - for k in 0..10i64 { - let data: Vec = (0..480).flat_map(|i| ((k * 480 + i) as f32 * 0.001).sin().to_le_bytes()).collect(); - w.write_frame(0, first_ns + k * 10_000_000, true, &data, durations.then_some(10_000_000)).unwrap(); - } - w.finish().unwrap().into_inner() -} - -#[test] -fn a_matroska_track_that_starts_late_counts_only_its_own_frames() { - use craft_audio::{DecodeOptions, Decoder}; - let file = pcm_mkv(1_000_000_000, true, 0); - let dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap(); - assert!(dec.length_known()); - assert_eq!(dec.info().frames, 4800); - let decoded: usize = dec.probe().map(|i| i.frames as usize).unwrap(); - assert_eq!(decoded, 4800); -} - -#[test] -fn a_matroska_codec_delay_is_taken_off_the_length() { - use craft_audio::{decode, probe}; - // `probe` reports the length the container gives, before anything is decoded; `decode` - // reports what it presented. 100 ms are decoded and the 20 ms of codec delay dropped, wherever - // the first block is stored. - for first_ns in [-20_000_000, 0, 50_000_000] { - let file = pcm_mkv(first_ns, true, 20_000_000); - let (_, buf) = decode(&file, None).unwrap(); - assert_eq!((probe(&file, None).unwrap().frames, buf.frames()), (3840, 3840), "first block at {first_ns} ns"); - } -} - -#[test] -fn seeking_far_past_an_unknown_end_does_not_overflow() { - use craft_audio::{DecodeOptions, Decoder}; - let file = pcm_mkv(0, false, 1_000_000); - let mut dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap(); - assert!(!dec.length_known()); - dec.seek(u64::MAX).unwrap(); - assert!(dec.next_block().unwrap().is_none()); - // and back to the start - assert_eq!(dec.seek(0).unwrap(), 0); - assert!(dec.next_block().unwrap().is_some_and(|b| b.frames() > 0)); -} diff --git a/crates/audio/tests/audio/wav_empty_data.rs b/crates/audio/tests/audio/wav_empty_data.rs index 2802d109e5..338b9bd33a 100644 --- a/crates/audio/tests/audio/wav_empty_data.rs +++ b/crates/audio/tests/audio/wav_empty_data.rs @@ -37,30 +37,6 @@ fn riff(chunks: &[Vec]) -> Vec { out } -fn list_info() -> Vec { - let mut l = b"INFO".to_vec(); - l.extend_from_slice(&chunk(b"INAM", b"Silence")); - chunk(b"LIST", &l) -} - -#[test] -fn an_empty_data_chunk_followed_by_metadata_has_no_frames() { - let file = riff(&[chunk(b"fmt ", &fmt16(2, 48_000)), chunk(b"data", &[]), list_info(), chunk(b"bext", &[0u8; 602])]); - let info = probe(&file, Some("wav")).unwrap(); - assert_eq!(info.frames, 0, "the LIST and bext chunks are not samples"); - let (info, buf) = decode(&file, Some("wav")).unwrap(); - assert_eq!((info.frames, buf.frames()), (0, 0)); - // The same with the metadata first. - let file = riff(&[chunk(b"fmt ", &fmt16(1, 44_100)), list_info(), chunk(b"data", &[])]); - assert_eq!(probe(&file, Some("wav")).unwrap().frames, 0); - // And with a single trailing chunk of odd size and no pad byte at the very end. - let mut file = riff(&[chunk(b"fmt ", &fmt16(1, 44_100)), chunk(b"data", &[]), chunk(b"note", b"abc")]); - file.pop(); - let riff_size = (file.len() - 8) as u32; - file[4..8].copy_from_slice(&riff_size.to_le_bytes()); - assert_eq!(probe(&file, Some("wav")).unwrap().frames, 0); -} - #[test] fn a_recording_that_was_never_finalised_still_gives_its_audio() { let samples: Vec = (0..400i16).flat_map(|i| (i * 40).to_le_bytes()).collect(); @@ -79,12 +55,6 @@ fn a_recording_that_was_never_finalised_still_gives_its_audio() { assert_eq!(probe(&file, Some("wav")).unwrap().frames, 200); } -#[test] -fn a_data_chunk_with_audio_is_unchanged() { - let samples: Vec = (0..100i16).flat_map(|i| i.to_le_bytes()).collect(); - let file = riff(&[chunk(b"fmt ", &fmt16(1, 44_100)), chunk(b"data", &samples), list_info()]); - assert_eq!(probe(&file, Some("wav")).unwrap().frames, 100); -} /// Whether an empty `data` chunk is followed by chunks alone is decided by walking the rest of the /// file. Doing that for every empty `data` chunk made parsing quadratic in their number (minutes /// for this 4 MB file); only the first one is used. @@ -103,3 +73,64 @@ fn many_empty_data_chunks_parse_in_linear_time() { assert_eq!(info.frames, 0); assert_eq!(decode(&b, Some("wav")).unwrap().1.frames(), 0); } + +/// fmt (mono 16-bit), an empty `data` chunk, then an 8-byte `LIST` chunk (#2123). +fn empty_data_then_list() -> Vec { + riff(&[chunk(b"fmt ", &fmt16(1, 8000)), chunk(b"data", &[]), chunk(b"LIST", b"INFOabcd")]) +} + +/// An empty `data` chunk followed by a `LIST` chunk holds no audio, whether the RIFF size counts +/// the `LIST` chunk or was written before it was appended (#2123): the `LIST` chunk's bytes are +/// never decoded as samples. +#[test] +fn an_empty_data_chunk_followed_by_a_list_chunk_is_no_audio_whatever_the_riff_size() { + let correct = empty_data_then_list(); + // The RIFF size a writer put down before appending the LIST chunk. + let mut stale = correct.clone(); + let before_list = (stale.len() - 8 - 16) as u32; + stale[4..8].copy_from_slice(&before_list.to_le_bytes()); + // A RIFF size past the end of the file. + let mut past = correct.clone(); + past[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); + for (name, file) in [("correct", &correct), ("stale", &stale), ("past the end", &past)] { + assert_eq!(probe(file, Some("wav")).unwrap().frames, 0, "{name} RIFF size: probe"); + assert_eq!(decode(file, Some("wav")).unwrap().1.frames(), 0, "{name} RIFF size: decode"); + } +} + +/// Bytes after an empty `data` chunk that only look like the start of a chunk are a recording that +/// was never finalised: a `LIST` id whose size runs past the file, or a cut-off header, stays +/// audio, as the bytes of PCM can spell any id. +#[test] +fn an_empty_data_chunk_followed_by_a_broken_chunk_header_is_still_audio() { + let base = riff(&[chunk(b"fmt ", &fmt16(1, 8000)), chunk(b"data", &[])]); + let stale = |tail: &[u8]| { + let mut f = base.clone(); + f.extend_from_slice(tail); + f + }; + // A LIST id whose size runs past the end of the file: 12 bytes, 6 frames. + assert_eq!(decode(&stale(b"LIST\0\x10\0\0INFO"), Some("wav")).unwrap().1.frames(), 6); + // A LIST id with a cut-off size field: 6 bytes, 3 frames. + assert_eq!(decode(&stale(b"LIST\0\0"), Some("wav")).unwrap().1.frames(), 3); +} + +/// A WAV with samples in a sized `data` chunk and a `LIST` chunk after it decodes exactly as +/// before: its samples, not the `LIST` chunk. +#[test] +fn a_sized_data_chunk_followed_by_a_list_chunk_decodes_its_samples() { + let samples: Vec = (0..64).map(|i| i * 300 - 9000).collect(); + let bytes: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + let file = riff(&[chunk(b"fmt ", &fmt16(1, 8000)), chunk(b"data", &bytes), chunk(b"LIST", b"INFOabcd")]); + let (info, buf) = decode(&file, Some("wav")).unwrap(); + assert_eq!(info.frames, 64); + assert_eq!(buf.frames(), 64); + let mut stale = file.clone(); + let before_list = (stale.len() - 8 - 16) as u32; + stale[4..8].copy_from_slice(&before_list.to_le_bytes()); + let (_, stale_buf) = decode(&stale, Some("wav")).unwrap(); + assert_eq!(stale_buf.frames(), 64, "a stale RIFF size does not change a sized data chunk"); + assert_eq!(stale_buf, buf, "the same samples"); + let expected: Vec = samples.iter().map(|s| f32::from(*s) / 32768.0).collect(); + assert_eq!(buf.interleaved(), expected, "the data chunk's samples"); +} diff --git a/crates/audio/tests/codecs/aac/common.rs b/crates/audio/tests/codecs/aac/common.rs index 1206c70b26..5c0379ea6b 100644 --- a/crates/audio/tests/codecs/aac/common.rs +++ b/crates/audio/tests/codecs/aac/common.rs @@ -5,13 +5,13 @@ use std::process::Command; use craft_audio::aac::{Decoder, Encoder, EncoderConfig, EncoderStats, split_adts}; -/// ffmpeg (see `crate::testkit::oracle`); `None` after printing `SKIPPED`. +/// ffmpeg (see `crate::integration::codecs::testkit::oracle`); `None` after printing `SKIPPED`. pub fn ffmpeg() -> Option { - crate::testkit::ffmpeg_or_skip("aac oracle") + crate::integration::codecs::testkit::ffmpeg_or_skip("aac oracle") } pub fn fixtures() -> PathBuf { - crate::testkit::fixtures_dir("aac") + crate::integration::codecs::testkit::fixtures_dir("aac") } pub struct Rng(pub u64); diff --git a/crates/audio/tests/codecs/aac/robustness.rs b/crates/audio/tests/codecs/aac/robustness.rs index 2f97f2ae67..e3e622ce33 100644 --- a/crates/audio/tests/codecs/aac/robustness.rs +++ b/crates/audio/tests/codecs/aac/robustness.rs @@ -28,7 +28,8 @@ fn mutated_access_units_never_panic() { let mut errors = 0usize; for (asc, aus) in corpus() { let mut dec = Decoder::new(&asc).unwrap(); - for round in 0..3000 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the rounds. + for round in 0..3000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut au = aus[rand(aus.len())].clone(); match round % 6 { 0 => { diff --git a/crates/audio/tests/codecs/ac3_encoder_oracle.rs b/crates/audio/tests/codecs/ac3_encoder_oracle.rs index 77607aaf8f..08a6a8dcbb 100644 --- a/crates/audio/tests/codecs/ac3_encoder_oracle.rs +++ b/crates/audio/tests/codecs/ac3_encoder_oracle.rs @@ -101,7 +101,7 @@ fn check_packets(packets: &[Packet], config: Config, label: &str) -> Vec { fn external_decode(ffmpeg: &Path, config: Config, label: &str, stream: &[u8], decoded_samples: usize) -> Vec { let channels = config.channels(); let format = if config.codec == Codec::Ac3 { "ac3" } else { "eac3" }; - let path = crate::testkit::fixtures_dir("ac3-encoder-oracle").join(format!( + let path = crate::integration::codecs::testkit::fixtures_dir("ac3-encoder-oracle").join(format!( "{}-{:?}-lfe{}-{}-{}.{}", std::process::id(), config.mode, diff --git a/crates/audio/tests/codecs/ac3_oracle.rs b/crates/audio/tests/codecs/ac3_oracle.rs index 3d3f319a19..23e5a3a6a2 100644 --- a/crates/audio/tests/codecs/ac3_oracle.rs +++ b/crates/audio/tests/codecs/ac3_oracle.rs @@ -133,8 +133,8 @@ const SPECS: &[Spec] = &[ ]; fn make(ff: &Path, s: &Spec) -> Option { - let out = crate::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec)); - crate::testkit::fixtures::generate(&out, |tmp| { + let out = crate::integration::codecs::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec)); + crate::integration::codecs::testkit::fixtures::generate(&out, |tmp| { let st = Command::new(ff) .args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i", s.input, "-t", "1"]) .args(["-c:a", s.codec]) @@ -257,10 +257,10 @@ fn damaged_eac3_frames_never_panic() { #[test] #[ignore] fn generate_fixtures() { - let Some(ff) = crate::testkit::ffmpeg_or_skip("ac3 fixtures") else { return }; + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("ac3 fixtures") else { return }; for s in SPECS { - let out = crate::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec)); - crate::testkit::fixtures::generate_and_report(&format!("ac3/{}", s.name), &[out], || make(&ff, s)); + let out = crate::integration::codecs::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec)); + crate::integration::codecs::testkit::fixtures::generate_and_report(&format!("ac3/{}", s.name), &[out], || make(&ff, s)); } } diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index 5b42f2e836..2d52234e86 100644 --- a/crates/audio/tests/codecs/alac.rs +++ b/crates/audio/tests/codecs/alac.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; fn dir() -> PathBuf { - crate::testkit::fixtures_dir("alac") + crate::integration::codecs::testkit::fixtures_dir("alac") } /// The ffmpeg channel layout ALAC uses for `channels`. @@ -103,7 +103,7 @@ fn our_decode(bytes: &[u8], bits: u32) -> Vec> { #[test] fn ffmpeg_alac_decodes_exactly() { - let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return }; + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return }; for (channels, bits) in [(1, 16), (2, 16), (2, 24), (3, 16), (4, 16), (5, 24), (6, 24), (7, 16), (8, 16)] { let wav = input(channels, bits, 12_345); let name = format!("ffmpeg_{channels}ch_{bits}"); @@ -128,7 +128,7 @@ fn ffmpeg_alac_decodes_exactly() { /// frames ("not yet implemented"), which the noise in the input produces; Apple's decoder does. #[test] fn ffmpeg_decodes_our_alac_exactly() { - let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return }; + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return }; for (channels, bits, frame) in [ (1, 16, 4096), (2, 16, 4096), diff --git a/crates/audio/tests/codecs/file_formats.rs b/crates/audio/tests/codecs/file_formats.rs index 82edf72aa0..17b9dff13a 100644 --- a/crates/audio/tests/codecs/file_formats.rs +++ b/crates/audio/tests/codecs/file_formats.rs @@ -410,7 +410,7 @@ fn the_formats_are_named() { /// ffmpeg's decode of `file` as interleaved `f32`, split into `channels` channels. fn ffmpeg_decode(ff: &std::path::Path, file: &[u8], name: &str, channels: usize) -> Vec> { - let path = crate::testkit::fixtures_dir("file_formats").join(name); + let path = crate::integration::codecs::testkit::fixtures_dir("file_formats").join(name); std::fs::write(&path, file).unwrap(); let out = Command::new(ff).args(["-v", "error", "-i"]).arg(&path).args(["-f", "f32le", "-"]).output().unwrap(); assert!(out.status.success() && out.stderr.is_empty(), "{name}: {}", String::from_utf8_lossy(&out.stderr)); @@ -473,9 +473,9 @@ fn ffmpeg_reads_the_files() { /// file from the edit list, which it does only for a track with a `roll` sample group. #[test] fn apple_reads_the_aac_priming_and_length() { - let Some(afinfo) = crate::testkit::oracle::find_tool("afinfo") else { return }; + let Some(afinfo) = crate::integration::codecs::testkit::oracle::find_tool("afinfo") else { return }; for (frames, remainder) in [(20_000, 480), (1, 1023), (4096, 0)] { - let path = crate::testkit::fixtures_dir("file_formats").join(format!("apple_{frames}.m4a")); + let path = crate::integration::codecs::testkit::fixtures_dir("file_formats").join(format!("apple_{frames}.m4a")); std::fs::write(&path, encode(&tones(48_000, 2, frames), &EncodeOptions::new(EncodeFormat::Aac)).unwrap()).unwrap(); let out = Command::new(&afinfo).arg(&path).output().unwrap(); let text = String::from_utf8_lossy(&out.stdout); diff --git a/crates/audio/tests/codecs/mp3_decoder_oracle.rs b/crates/audio/tests/codecs/mp3_decoder_oracle.rs index 951a9b1294..ff05f2174c 100644 --- a/crates/audio/tests/codecs/mp3_decoder_oracle.rs +++ b/crates/audio/tests/codecs/mp3_decoder_oracle.rs @@ -68,13 +68,13 @@ const LAME: &[Lame] = &[ const MIN_SNR: f64 = 100.0; fn generate(out: &Path, cmd: impl FnOnce(&Path) -> Command) -> Option { - crate::testkit::fixtures::generate(out, |tmp| cmd(tmp).stdin(Stdio::null()).status().is_ok_and(|s| s.success())) + crate::integration::codecs::testkit::fixtures::generate(out, |tmp| cmd(tmp).stdin(Stdio::null()).status().is_ok_and(|s| s.success())) } /// The LAME stream for `s`, or `None` (after saying so) when this ffmpeg has no `libmp3lame`; a /// failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`. fn lame_stream(ff: &Path, s: &Lame) -> Option { - let out = crate::testkit::fixtures_dir("mp3dec").join(format!("{}.mp3", s.name)); + let out = crate::integration::codecs::testkit::fixtures_dir("mp3dec").join(format!("{}.mp3", s.name)); generate(&out, |tmp| { let mut c = Command::new(ff); c.args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i"]) @@ -164,7 +164,7 @@ fn lame_streams_match_ffmpeg() { #[test] fn lame_cli_streams_match_ffmpeg() { let ff = require_ffmpeg!(); - let Some(lame) = crate::testkit::oracle::find_tool("lame") else { + let Some(lame) = crate::integration::codecs::testkit::oracle::find_tool("lame") else { eprintln!("lame not installed, skipped"); return; }; @@ -174,7 +174,7 @@ fn lame_cli_streams_match_ffmpeg() { ("forced_ms_44k", &["-m", "f", "-b", "96"], 44_100, 2), ]; for &(name, args, rate, channels) in cases { - let dir = crate::testkit::fixtures_dir("mp3dec"); + let dir = crate::integration::codecs::testkit::fixtures_dir("mp3dec"); let wav = dir.join(format!("{name}.wav")); let input = if channels == 1 { "aevalsrc=exprs=if(lt(mod(t\\,0.2)\\,0.004)\\,0.9\\,0.05)*sin(2*PI*700*t)" } else { CLICKS }; generate(&wav, |tmp| { @@ -203,7 +203,7 @@ fn lame_cli_streams_match_ffmpeg() { #[test] fn our_encoder_streams_match_ffmpeg() { let ff = require_ffmpeg!(); - let dir = crate::testkit::fixtures_dir("mp3dec"); + let dir = crate::integration::codecs::testkit::fixtures_dir("mp3dec"); for (rate, channels, kbps, stereo) in [ (44_100, 2, 192, StereoMode::JointStereo), (48_000, 2, 128, StereoMode::Stereo), @@ -286,7 +286,7 @@ struct Candidate { /// Write `frames` (edited copies) as a stream and compare it with ffmpeg. fn check_edited(ff: &Path, frames: Vec>, rate: u32, channels: usize, name: &str) { - let path = crate::testkit::fixtures_dir("mp3dec").join(format!("{name}.mp3")); + let path = crate::integration::codecs::testkit::fixtures_dir("mp3dec").join(format!("{name}.mp3")); std::fs::write(&path, frames.concat()).unwrap(); check(ff, &path, rate, channels, name); } @@ -370,7 +370,7 @@ fn mixed_blocks_match_ffmpeg() { #[test] fn info_tag_of_a_lame_stream() { let ff = require_ffmpeg!(); - let out = crate::testkit::fixtures_dir("mp3dec").join("tagged_44k.mp3"); + let out = crate::integration::codecs::testkit::fixtures_dir("mp3dec").join("tagged_44k.mp3"); let f = generate(&out, |tmp| { let mut c = Command::new(&ff); c.args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=500:sample_rate=44100", "-t", "1"]) diff --git a/crates/audio/tests/codecs/mp3_encoder_oracle.rs b/crates/audio/tests/codecs/mp3_encoder_oracle.rs index c9bbf24fc4..f3a14d5499 100644 --- a/crates/audio/tests/codecs/mp3_encoder_oracle.rs +++ b/crates/audio/tests/codecs/mp3_encoder_oracle.rs @@ -10,7 +10,7 @@ use std::process::{Command, Stdio}; use craft_audio::mp3::{Config, DELAY, Encoder, StereoMode}; fn fixtures() -> PathBuf { - crate::testkit::fixtures_dir("mp3enc") + crate::integration::codecs::testkit::fixtures_dir("mp3enc") } fn chords(rate: u32, n: usize, detune: f32) -> Vec { @@ -117,7 +117,7 @@ fn run(ff: &Path, c: &Case) -> f64 { let frames = dec[0].len() / frame_samples; let nominal = c.kbps as f64 * 1000.0 / 8.0 * (frames * frame_samples) as f64 / c.rate as f64; assert!((bytes.len() as f64 / nominal - 1.0).abs() < 0.01, "{}: {} bytes vs {nominal}", c.name, bytes.len()); - if let Some(probe) = crate::testkit::oracle::find_tool("ffprobe") { + if let Some(probe) = crate::integration::codecs::testkit::oracle::find_tool("ffprobe") { let out = Command::new(probe) .args(["-v", "error", "-show_entries", "stream=codec_name,sample_rate,channels:format=duration", "-of", "default=nw=1"]) .arg(&path) diff --git a/crates/audio/tests/codecs/mpa_oracle.rs b/crates/audio/tests/codecs/mpa_oracle.rs index 53f80c7fc3..7311b969c3 100644 --- a/crates/audio/tests/codecs/mpa_oracle.rs +++ b/crates/audio/tests/codecs/mpa_oracle.rs @@ -182,14 +182,14 @@ const ENCODED: &[Encoded] = &[ ]; fn tool(name: &str) -> Option { - crate::testkit::oracle::find_tool(name) + crate::integration::codecs::testkit::oracle::find_tool(name) } fn make_encoded(ff: &Path, s: &Encoded) -> Option { - let out = crate::testkit::fixtures_dir("mpa").join(format!("{}.mp2", s.name)); + let out = crate::integration::codecs::testkit::fixtures_dir("mpa").join(format!("{}.mp2", s.name)); if s.twolame { let twolame = tool("twolame")?; - return crate::testkit::fixtures::generate(&out, |tmp| { + return crate::integration::codecs::testkit::fixtures::generate(&out, |tmp| { let wav = tmp.with_extension("wav"); let made = Command::new(ff) .args([ @@ -215,7 +215,7 @@ fn make_encoded(ff: &Path, s: &Encoded) -> Option { made }); } - crate::testkit::fixtures::generate(&out, |tmp| { + crate::integration::codecs::testkit::fixtures::generate(&out, |tmp| { Command::new(ff) .args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i", s.input, "-t", "1", "-c:a", "mp2"]) .args(s.enc) @@ -523,8 +523,8 @@ const SYNTHETIC: &[(&str, u8, bool, u8, u8, u8, u8)] = &[ fn synthetic_streams_match_ffmpeg() { let ff = require_ffmpeg!(); for (k, &(name, layer, lsf, br, sr, mode, ext)) in SYNTHETIC.iter().enumerate() { - let out = crate::testkit::fixtures_dir("mpa").join(format!("{name}.mp{layer}")); - let f = crate::testkit::fixtures::generate(&out, |tmp| { + let out = crate::integration::codecs::testkit::fixtures_dir("mpa").join(format!("{name}.mp{layer}")); + let f = crate::integration::codecs::testkit::fixtures::generate(&out, |tmp| { let mut rng = Rng(0x9E37_79B9 ^ k as u32); let h = header(lsf, layer, br, sr, mode, ext); let data: Vec = (0..40).flat_map(|_| if layer == 1 { random_layer1(&mut rng, h) } else { random_layer2(&mut rng, h) }).collect(); @@ -578,9 +578,9 @@ fn damaged_frames_never_panic() { #[test] #[ignore] fn generate_fixtures() { - let Some(ff) = crate::testkit::ffmpeg_or_skip("mpa fixtures") else { return }; + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("mpa fixtures") else { return }; for s in ENCODED { - let out = crate::testkit::fixtures_dir("mpa").join(format!("{}.mp2", s.name)); - crate::testkit::fixtures::generate_and_report(&format!("mpa/{}", s.name), &[out], || make_encoded(&ff, s)); + let out = crate::integration::codecs::testkit::fixtures_dir("mpa").join(format!("{}.mp2", s.name)); + crate::integration::codecs::testkit::fixtures::generate_and_report(&format!("mpa/{}", s.name), &[out], || make_encoded(&ff, s)); } } diff --git a/crates/audio/tests/codecs/opus/common.rs b/crates/audio/tests/codecs/opus/common.rs index 5996dc0ed2..6b2974789f 100644 --- a/crates/audio/tests/codecs/opus/common.rs +++ b/crates/audio/tests/codecs/opus/common.rs @@ -162,13 +162,13 @@ pub fn opus_quality(reference: &[f32], test: &[f32], channels: usize, rate: u32) 100.0 * (1.0 - 0.5 * (1.0 + err).ln() / 1.13f64.ln()) } -/// ffmpeg (see `crate::testkit::oracle`); `None` after printing `SKIPPED`. +/// ffmpeg (see `crate::integration::codecs::testkit::oracle`); `None` after printing `SKIPPED`. pub fn ffmpeg() -> Option { - crate::testkit::ffmpeg_or_skip("opus oracle") + crate::integration::codecs::testkit::ffmpeg_or_skip("opus oracle") } pub fn fixtures() -> PathBuf { - crate::testkit::fixtures_dir("opus/oracle") + crate::integration::codecs::testkit::fixtures_dir("opus/oracle") } /// Minimal Ogg demuxer: returns (packets, last granule position). diff --git a/crates/audio/tests/codecs/opus/oracle.rs b/crates/audio/tests/codecs/opus/oracle.rs index fb44b1ab68..8dbc5d609f 100644 --- a/crates/audio/tests/codecs/opus/oracle.rs +++ b/crates/audio/tests/codecs/opus/oracle.rs @@ -50,8 +50,8 @@ fn run(case: &Case, rate: u32) -> (f64, f64, Vec) { let layout = match case.channels { 1 => "mono", 2 => "stereo", - 6 => "5.1", - _ => unreachable!(), + // The cases have 1, 2 or 6 channels. + _ => "5.1", }; let mut cmd = Command::new(&ff); cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "f32le", "-ar", "48000", "-ch_layout", layout, "-i"]).arg(&raw); @@ -93,14 +93,6 @@ fn run(case: &Case, rate: u32) -> (f64, f64, Vec) { // Our output is in Vorbis channel order; ffmpeg reorders 5.1 to FL FR FC LFE BL BR. let order: Vec = if case.channels == 6 { vec![0, 2, 1, 5, 3, 4] } else { (0..case.channels).collect() }; let ours: Vec = (0..total).flat_map(|i| order.iter().map(|&c| planar[c][i]).collect::>()).collect(); - if std::env::var("DIAG").is_ok_and(|v| v == case.name) { - let blk = 12000 * case.channels; - for (b, (r, o)) in reference.chunks(blk).zip(ours.chunks(blk)).enumerate() { - let er: f32 = r.iter().map(|v| v * v).sum(); - let eo: f32 = o.iter().map(|v| v * v).sum(); - eprintln!("{:5.2}s ref {:9.3e} ours {:9.3e} snr {:6.1}", b as f32 * 0.25, er, eo, common::snr_db(r, o)); - } - } assert_eq!( ours.len(), reference.len(), @@ -124,7 +116,7 @@ fn libopus_oracle() { return; }; if !has_libopus(&ff) { - crate::common::skip::<()>("opus oracle: ffmpeg was built without libopus"); + crate::integration::codecs::common::skip::<()>("opus oracle: ffmpeg was built without libopus"); return; } let cases = [ @@ -218,7 +210,7 @@ fn libopus_oracle_output_rates() { return; }; if !has_libopus(&ff) { - crate::common::skip::<()>("opus oracle: ffmpeg was built without libopus"); + crate::integration::codecs::common::skip::<()>("opus oracle: ffmpeg was built without libopus"); return; } let cases = [ diff --git a/crates/audio/tests/codecs/opus/robustness.rs b/crates/audio/tests/codecs/opus/robustness.rs index 8bcec38258..9ae1e83ea3 100644 --- a/crates/audio/tests/codecs/opus/robustness.rs +++ b/crates/audio/tests/codecs/opus/robustness.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; -use craft_audio::opus::{Decoder, OpusHead, StreamDecoder}; +use craft_audio::opus::{Decoder, StreamDecoder}; struct Rng(u64); impl Rng { @@ -26,7 +26,8 @@ fn random_garbage_never_panics() { for channels in 1..=2 { let mut dec = StreamDecoder::new(rate, channels).unwrap(); let mut out = Vec::new(); - for i in 0..3000 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the packets. + for i in 0..3000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let len = (rng.next() % 400) as usize; let mut pkt: Vec = (0..len).map(|_| rng.next() as u8).collect(); if let Some(t) = pkt.first_mut() { @@ -52,7 +53,7 @@ fn multistream_garbage_never_panics() { h.extend([1, 6, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0, 0, 1, 4, 2, 0, 4, 1, 2, 3, 5]); let mut dec = Decoder::new(&h).unwrap(); let mut rng = Rng(42); - for _ in 0..2000 { + for _ in 0..2000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let len = (rng.next() % 600) as usize; let pkt: Vec = (0..len).map(|_| rng.next() as u8).collect(); if let Ok(out) = dec.decode(Some(&pkt)) { @@ -66,23 +67,17 @@ fn multistream_garbage_never_panics() { assert_eq!(out.len(), 6); } -#[test] -fn concealment_before_and_after_packets() { - let mut dec = Decoder::from_head(OpusHead::simple(2).unwrap(), 48000).unwrap(); - // Loss before any packet: silence of a default duration. - let out = dec.decode(None).unwrap(); - assert_eq!(out.len(), 2); - assert!(out[0].iter().all(|&v| v == 0.0)); -} - /// The RFC 8251 vectors, or `None` after printing `SKIPPED` (a failure with /// `CRAFT_MEDIA_REQUIRE_ORACLES=1`). `scripts/fetch-opus-vectors.sh` fetches them. fn vectors_dir() -> Option { - let d = crate::common::fixture_subdir("opus").join("vectors"); + let d = crate::integration::codecs::common::fixture_subdir("opus").join("vectors"); if d.join("testvector01.bit").exists() { return Some(d); } - crate::common::skip(&format!("the Opus RFC 8251 vectors are not in {} (scripts/fetch-opus-vectors.sh fetches them)", d.display())) + crate::integration::codecs::common::skip(&format!( + "the Opus RFC 8251 vectors are not in {} (scripts/fetch-opus-vectors.sh fetches them)", + d.display() + )) } /// Real packets (from the conformance vectors) truncated and bit-flipped, interleaved with losses. diff --git a/crates/audio/tests/codecs/opus/vectors.rs b/crates/audio/tests/codecs/opus/vectors.rs index 2edab50065..df89f7ec95 100644 --- a/crates/audio/tests/codecs/opus/vectors.rs +++ b/crates/audio/tests/codecs/opus/vectors.rs @@ -17,11 +17,14 @@ use craft_audio::opus::StreamDecoder; /// The RFC 8251 vectors, or `None` after printing `SKIPPED` (a failure with /// `CRAFT_MEDIA_REQUIRE_ORACLES=1`). `scripts/fetch-opus-vectors.sh` fetches them. fn vectors_dir() -> Option { - let d = crate::common::fixture_subdir("opus").join("vectors"); + let d = crate::integration::codecs::common::fixture_subdir("opus").join("vectors"); if d.join("testvector01.bit").exists() { return Some(d); } - crate::common::skip(&format!("the Opus RFC 8251 vectors are not in {} (scripts/fetch-opus-vectors.sh fetches them)", d.display())) + crate::integration::codecs::common::skip(&format!( + "the Opus RFC 8251 vectors are not in {} (scripts/fetch-opus-vectors.sh fetches them)", + d.display() + )) } fn read_bit(path: &PathBuf) -> Vec<(Vec, u32)> { @@ -128,38 +131,3 @@ fn quality_metric_calibration() { assert!(q > lo && q < hi, "{snr} dB -> {q}"); } } - -/// Diagnostic (`VEC=n cargo test ... -- --ignored`): per-second SNR/quality with packet modes. -#[test] -#[ignore] -fn vector_diag() { - let Some(dir) = vectors_dir() else { - return; - }; - let v: usize = std::env::var("VEC").ok().and_then(|s| s.parse().ok()).unwrap_or(2); - let name = format!("testvector{v:02}"); - let packets = read_bit(&dir.join(format!("{name}.bit"))); - let mut dec = StreamDecoder::new(48000, 2).unwrap(); - let mut out = Vec::new(); - let mut lines = Vec::new(); - for (pkt, _) in &packets { - let start = out.len() / 2; - if pkt.is_empty() { - dec.decode_interleaved(None, &mut out).unwrap(); - lines.push((start, "LOST".to_string())); - } else { - let p = craft_audio::opus::Packet::parse(pkt).unwrap(); - dec.decode_interleaved(Some(pkt), &mut out).unwrap(); - lines.push((start, format!("{:?} {:?} st{} n{}", p.toc.mode, p.toc.bandwidth, p.toc.stereo as u8, p.frames.len()))); - } - } - let reference = read_pcm(&dir.join(format!("{name}.dec"))); - let sec = 48000 * 2; - for s in 0..reference.len() / sec { - let r = &reference[s * sec..(s + 1) * sec]; - let o = &out[s * sec..(s + 1) * sec]; - let mut kinds: Vec<&String> = lines.iter().filter(|(st, _)| *st >= s * 48000 && *st < (s + 1) * 48000).map(|(_, c)| c).collect(); - kinds.dedup(); - eprintln!("{s:3}s snr {:6.1} q {:6.1} {:?}", common::snr_db(r, o), common::opus_quality(r, o, 2, 48000), kinds); - } -} diff --git a/crates/audio/tests/codecs/opusenc/ffmpeg.rs b/crates/audio/tests/codecs/opusenc/ffmpeg.rs index 41965be20b..956a8147e4 100644 --- a/crates/audio/tests/codecs/opusenc/ffmpeg.rs +++ b/crates/audio/tests/codecs/opusenc/ffmpeg.rs @@ -12,17 +12,17 @@ use craft_audio::opus::encoder::{Bandwidth, Mode, OpusEncoder}; /// ffmpeg, found and skipped by craft-media's oracle rules (EffectCraft looked in Homebrew's /// directory, then `PATH`). fn ffmpeg() -> Option { - crate::testkit::ffmpeg_or_skip("opus encoder ffmpeg oracle") + crate::integration::codecs::testkit::ffmpeg_or_skip("opus encoder ffmpeg oracle") } /// Decodes an Ogg Opus file with ffmpeg's decoder `codec`; returns interleaved f32 output. fn ffmpeg_decode(exe: &std::path::Path, codec: &str, file: &[u8], channels: usize, tag: &str) -> Option> { let has = match Command::new(exe).args(["-hide_banner", "-decoders"]).output() { Ok(out) => out, - Err(e) => return crate::common::skip(&format!("ffmpeg -decoders failed: {e}")), + Err(e) => return crate::integration::codecs::common::skip(&format!("ffmpeg -decoders failed: {e}")), }; if !String::from_utf8_lossy(&has.stdout).lines().any(|l| l.split_whitespace().nth(1) == Some(codec)) { - return crate::common::skip(&format!("ffmpeg has no {codec} decoder")); + return crate::integration::codecs::common::skip(&format!("ffmpeg has no {codec} decoder")); } let path = std::env::temp_dir().join(format!("effectcraft-opusenc-{}-{tag}.opus", std::process::id())); std::fs::write(&path, file).unwrap(); diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index 2638585603..a48ad2d444 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -49,12 +49,14 @@ fn band_edge(bw: Bandwidth) -> f64 { } const LEN: usize = 96_000; +/// The length of the sweeps over many encodes: one second. +const SHORT: usize = 48_000; #[test] fn every_mode_and_bandwidth_decodes() { - let sp = speech(LEN + 40_000, 11); - let left = sp[..LEN].to_vec(); - let right: Vec = sp[40_000..].iter().map(|v| v * 0.6).collect(); + let sp = speech(SHORT + 20_000, 11); + let left = sp[..SHORT].to_vec(); + let right: Vec = sp[20_000..].iter().map(|v| v * 0.6).collect(); for (mode, bw, config, rate) in [ (Mode::Silk, Bandwidth::Narrowband, 1u8, 8_000u32), (Mode::Silk, Bandwidth::Mediumband, 5, 11_000), @@ -149,8 +151,8 @@ fn silk_music_quality() { #[test] fn bitrate_tracking() { - let sp = speech(LEN, 13); - let mu = music(LEN); + let sp = speech(SHORT, 13); + let mu = music(SHORT); for (name, x) in [("speech", &sp), ("music", &mu)] { for (mode, bw, rate) in [ (Mode::Silk, Bandwidth::Narrowband, 6_000u32), @@ -178,10 +180,10 @@ fn bitrate_tracking() { #[test] fn stereo_silk_and_hybrid() { - let sp = speech(LEN + 40_000, 21); - let a = sp[..LEN].to_vec(); - let b: Vec = sp[40_000..].iter().map(|v| v * 0.7).collect(); - let mu = music(LEN); + let sp = speech(SHORT + 20_000, 21); + let a = sp[..SHORT].to_vec(); + let b: Vec = sp[20_000..].iter().map(|v| v * 0.7).collect(); + let mu = music(SHORT); let cases: Vec<(&str, Vec, Vec)> = vec![ ("dual mono", a.clone(), a.clone()), ("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()), diff --git a/crates/audio/tests/codecs/routing_oracle.rs b/crates/audio/tests/codecs/routing_oracle.rs index 88cf9beec7..a5df09cb81 100644 --- a/crates/audio/tests/codecs/routing_oracle.rs +++ b/crates/audio/tests/codecs/routing_oracle.rs @@ -354,14 +354,14 @@ fn run(ff: &Path, args: &[&str]) -> bool { /// The fixture for `c`, written by ffmpeg (cached), or `None` when this ffmpeg lacks an encoder /// (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). fn fixture(ff: &Path, c: &Case) -> Option { - let out = crate::testkit::fixtures_dir("routing").join(c.name); + let out = super::testkit::fixtures_dir("routing").join(c.name); let source = match (c.mono, c.surround) { (true, _) => MONO.to_string(), (_, true) => format!("{STEREO}{SURROUND_EXTRA}"), _ => STEREO.to_string(), }; let input = format!("{source}:s={}", c.rate); - let made = crate::testkit::fixtures::generate(&out, |tmp| { + let made = super::testkit::fixtures::generate(&out, |tmp| { let tmp = tmp.to_string_lossy(); let mut args = vec!["-f", "lavfi", "-i", &input, "-t", "5"]; args.extend_from_slice(c.args); @@ -464,31 +464,6 @@ fn every_container_and_codec_decodes_home_grown() { } } -#[test] -fn truncated_and_corrupted_files_never_panic() { - let ff = require_ffmpeg!(); - for c in CASES { - let Some(path) = fixture(&ff, c) else { continue }; - let bytes = std::fs::read(&path).unwrap(); - for cut in [1, 7, 64, 500, bytes.len() / 3, bytes.len() / 2, bytes.len() - 1] { - let _ = decode(bytes.get(..cut).unwrap_or_default(), None); - let _ = probe(bytes.get(..cut).unwrap_or_default(), None); - } - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - for _ in 0..6 { - let mut m = bytes.clone(); - for _ in 0..16 { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - let i = (seed % m.len() as u64) as usize; - m[i] ^= (seed >> 32) as u8 | 1; - } - let _ = decode(&m, None); - } - } -} - /// SNR (dB) of `ours` against `reference`, both planar, over the frames both hold. fn snr_planar(ours: &[Vec], reference: &[Vec]) -> f64 { let (mut s, mut e) = (0f64, 0f64); @@ -540,109 +515,6 @@ fn streaming_and_seeking_match_the_whole_file_decode() { } } -/// `TrackDecoder` on the packets craft-media's demuxer reads gives the audio `decode` presents: -/// the same samples once the container's priming is skipped. -#[test] -fn track_decoder_on_demuxed_packets_matches_decode() { - use craft_audio::TrackDecoder; - use craft_media::isobmff; - let ff = require_ffmpeg!(); - for name in ["aac.m4a", "aac-5.1.m4a", "opus.mp4", "mp2.mp4", "mp3.mp4", "pcm-s24be.mov"] { - let c = CASES.iter().find(|c| c.name == name).unwrap(); - let Some(path) = fixture(&ff, c) else { continue }; - let bytes = std::fs::read(&path).unwrap(); - let (info, whole) = decode(&bytes, None).unwrap(); - let file = isobmff::open(bytes.as_slice()).unwrap(); - let track = file.track_of_kind(isobmff::TrackKind::Audio).unwrap(); - let t = &file.tracks[track]; - let params = t.codec_params(); - let packets: Vec> = (0..t.samples.len()).map(|i| file.read_sample(bytes.as_slice(), track, i).unwrap()).collect(); - let lookahead: Vec<&[u8]> = packets.iter().take(8).map(Vec::as_slice).collect(); - let mut dec = TrackDecoder::new(¶ms, &lookahead).unwrap(); - assert_eq!((dec.codec(), dec.sample_rate(), dec.layout()), (info.codec, info.sample_rate, info.layout), "{name}"); - let mut out: Vec> = vec![Vec::new(); usize::from(dec.channels())]; - for p in &packets { - for (o, ch) in out.iter_mut().zip(dec.decode(p).unwrap().channels) { - o.extend(ch); - } - } - // The edit list's media time is the priming `decode` skips. - let skip = t.edits.first().map_or(0, |e| (e.media_time.max(0) as u64 * u64::from(info.sample_rate) / u64::from(t.timescale)) as usize); - let presented: Vec> = out.iter().map(|ch| ch[skip..skip + whole.frames()].to_vec()).collect(); - assert_eq!(presented, whole.channels, "{name}"); - } -} - -/// `tracks` lists every audio track, `DecodeOptions::track` picks one, and `max_samples` refuses -/// a longer decode. -#[test] -fn track_choice_and_the_sample_limit() { - use craft_audio::{AudioError, DecodeOptions, decode_with, tracks}; - let ff = require_ffmpeg!(); - for ext in ["mkv", "mp4"] { - let out = crate::testkit::fixtures_dir("routing").join(format!("two-tracks.{ext}")); - let Some(path) = crate::testkit::fixtures::generate(&out, |tmp| { - let tmp = tmp.to_string_lossy(); - run( - &ff, - &[ - "-f", - "lavfi", - "-i", - "sine=f=440:r=48000:d=2", - "-f", - "lavfi", - "-i", - "aevalsrc=0.3*sin(2*PI*660*t)|0.3*sin(2*PI*880*t):s=44100:d=2", - "-map", - "0:a", - "-map", - "1:a", - "-c:a", - "aac", - "-b:a", - "96k", - &tmp, - ], - ) - }) else { - continue; - }; - let bytes = std::fs::read(&path).unwrap(); - let list = tracks(&bytes, None).unwrap(); - assert_eq!(list.len(), 2, "{ext}"); - assert_eq!((list[0].codec, list[0].sample_rate, list[0].channels), (CodecId::Aac, Some(48_000), Some(1)), "{ext}"); - assert_eq!((list[1].sample_rate, list[1].channels), (Some(44_100), Some(2)), "{ext}"); - let (first, _) = decode_with(&bytes, None, &DecodeOptions::default()).unwrap(); - let (second, buf) = decode_with(&bytes, None, &DecodeOptions::default().with_track(1)).unwrap(); - assert_eq!((first.channels, first.sample_rate), (1, 48_000), "{ext}"); - assert_eq!((second.channels, second.sample_rate, buf.frames()), (2, 44_100, 88_200), "{ext}"); - let limited = decode_with(&bytes, None, &DecodeOptions::default().with_max_samples(1000)); - assert!(matches!(limited, Err(AudioError::TooLarge(_))), "{ext}"); - // Refused from the track list, without reading the file through the fallback. - let missing = decode_with(&bytes, None, &DecodeOptions::default().with_track(2)); - assert!(matches!(&missing, Err(AudioError::Unsupported(m)) if m.contains("no audio track 2")), "{ext}: {missing:?}"); - } -} - -/// `Decoder::open` reads from a file without loading it. -#[test] -fn decoder_reads_from_a_file() { - use craft_audio::{DecodeOptions, Decoder}; - let ff = require_ffmpeg!(); - let c = CASES.iter().find(|c| c.name == "aac.m4a").unwrap(); - let Some(path) = fixture(&ff, c) else { return }; - let (_, whole) = decode(&std::fs::read(&path).unwrap(), None).unwrap(); - let mut d = Decoder::open(std::fs::File::open(&path).unwrap(), None, &DecodeOptions::default()).unwrap(); - assert!(d.length_known()); - assert_eq!(d.info().frames, whole.frames() as u64); - let mut frames = 0; - while let Some(b) = d.next_block().unwrap() { - frames += b.frames(); - } - assert_eq!(frames, whole.frames()); -} - /// `fixture`'s AAC packets in a Matroska file with no block durations, like ffmpeg 6's, /// and a `DURATION` tag for the track when `tag` is given. fn aac_mkv_without_durations(bytes: &[u8], tag: Option<&str>) -> Vec { @@ -834,10 +706,10 @@ fn mp4_with_wrong_durations_or_edits_presents_its_audio() { #[test] fn mp4_with_an_empty_edit_before_its_media_edit_applies_the_media_edit() { let ff = require_ffmpeg!(); - let dir = crate::testkit::fixtures_dir("routing"); + let dir = super::testkit::fixtures_dir("routing"); let out = dir.join("aac-itsoffset.m4a"); let input = format!("{MONO}:s=44100"); - let made = crate::testkit::fixtures::generate(&out, |tmp| { + let made = super::testkit::fixtures::generate(&out, |tmp| { let tmp = tmp.to_string_lossy(); run(ff.as_path(), &["-itsoffset", "0.5", "-f", "lavfi", "-i", &input, "-t", "5", "-c:a", "aac", "-aac_pns", "0", &tmp]) }); diff --git a/crates/audio/tests/codecs/testkit.rs b/crates/audio/tests/codecs/testkit.rs index ba2c927941..292a46bba0 100644 --- a/crates/audio/tests/codecs/testkit.rs +++ b/crates/audio/tests/codecs/testkit.rs @@ -3,20 +3,20 @@ //! `CRAFT_MEDIA_REQUIRE_ORACLES=1`; fixtures go to `$CRAFT_MEDIA_FIXTURES_DIR` or //! `target/fixtures`, never committed. -use crate::common; +use super::common; use std::path::{Path, PathBuf}; /// `let ff = require_ffmpeg!();`: the ffmpeg path, or return from the test after printing /// `SKIPPED` (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). macro_rules! require_ffmpeg { () => { - match $crate::testkit::ffmpeg_or_skip(concat!(module_path!(), ":", line!())) { + match $crate::integration::codecs::testkit::ffmpeg_or_skip(concat!(module_path!(), ":", line!())) { Some(p) => p, None => return, } }; ($ret:expr) => { - match $crate::testkit::ffmpeg_or_skip(concat!(module_path!(), ":", line!())) { + match $crate::integration::codecs::testkit::ffmpeg_or_skip(concat!(module_path!(), ":", line!())) { Some(p) => p, None => return $ret, } @@ -43,7 +43,7 @@ pub mod oracle { /// A tool by name, silently. pub fn find_tool(name: &str) -> Option { - crate::common::tool(name) + crate::integration::codecs::common::tool(name) } } diff --git a/crates/audio/tests/codecs/vorbis_encoder_oracle.rs b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs index 342f4fd9a1..7f681e6d4a 100644 --- a/crates/audio/tests/codecs/vorbis_encoder_oracle.rs +++ b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs @@ -20,7 +20,7 @@ fn tones(rate: u32, channels: usize, frames: usize) -> AudioBuffer { /// Decodes `file` with ffmpeg's `decoder`; planar output in ffmpeg's (WAV) channel order. fn ffmpeg_decode(ff: &Path, decoder: &str, file: &[u8], channels: usize, tag: &str) -> Vec> { - let path = crate::testkit::fixtures_dir("vorbis-encoder").join(format!("{tag}.ogg")); + let path = crate::integration::codecs::testkit::fixtures_dir("vorbis-encoder").join(format!("{tag}.ogg")); std::fs::write(&path, file).unwrap(); let out = Command::new(ff) .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) @@ -90,14 +90,17 @@ fn every_channel_count_decodes_on_the_right_speakers() { /// a valid field name is left out. #[test] fn tags_reach_ffprobe() { - let Some(probe) = crate::common::tool("ffprobe").or_else(|| crate::common::skip("ffprobe not found")) else { return }; + let Some(probe) = crate::integration::codecs::common::tool("ffprobe").or_else(|| crate::integration::codecs::common::skip("ffprobe not found")) + else { + return; + }; let opts = OggVorbisOptions::new(3.0) .with_tag("TITLE", "Smörgåsbord ✓") .with_tag("ARTIST", "Craft") .with_tag("bad=name", "dropped") .with_vendor("craft-audio test"); let file = encode_ogg_vorbis(&tones(44_100, 2, 44_100), &opts).unwrap(); - let path = crate::testkit::fixtures_dir("vorbis-encoder").join("tags.ogg"); + let path = crate::integration::codecs::testkit::fixtures_dir("vorbis-encoder").join("tags.ogg"); std::fs::write(&path, &file).unwrap(); let out = Command::new(probe).args(["-v", "error", "-of", "json", "-show_streams", "-show_format"]).arg(&path).output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs index d252372514..214898c230 100644 --- a/crates/audio/tests/flac_decode.rs +++ b/crates/audio/tests/flac_decode.rs @@ -132,15 +132,17 @@ fn track_decoder_uses_streaminfo_layout_and_packet_length() { #[test] fn hostile_input_is_an_error_not_a_panic() { - let src = signal(2, 6000, 16, 11); + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th cut and flipped byte. + let step = craft_media_testkit::hostile::divisor(); + let src = signal(2, 3500, 16, 11); let file = encode(&src, 44_100, 16, 1152, 5); - for n in 0..file.len().min(3000) { + for n in (0..file.len().min(3000)).step_by(step) { let _ = decode(&file[..n]); } // A cut file is truncated, not silently shorter. assert!(decode(&file[..file.len() - 5]).is_err()); // Every bit flip in the first frames is caught by a CRC or another check, never a panic. - for i in 0..file.len().min(2500) { + for i in (0..file.len().min(2500)).step_by(step) { for bit in 0..8 { let mut c = file.clone(); c[i] ^= 1 << bit; diff --git a/crates/audio/tests/main.rs b/crates/audio/tests/main.rs new file mode 100644 index 0000000000..5470dc5530 --- /dev/null +++ b/crates/audio/tests/main.rs @@ -0,0 +1,53 @@ +//! Integration tests, built into the library's own test executable. + +#[cfg(feature = "adpcm")] +#[path = "adpcm_oracle.rs"] +mod adpcm_oracle; +#[cfg(all(feature = "decode", feature = "lossless-encode", feature = "peaks"))] +#[path = "audio/main.rs"] +mod audio; +#[cfg(all(feature = "decode", feature = "encode"))] +#[path = "codecs/main.rs"] +mod codecs; +#[cfg(feature = "dsd")] +#[path = "dsd_bounds.rs"] +mod dsd_bounds; +#[cfg(feature = "dsd")] +#[path = "dsd_metadata.rs"] +mod dsd_metadata; +#[cfg(feature = "dsd")] +#[path = "dsd_oracle.rs"] +mod dsd_oracle; +#[cfg(all(feature = "flac-decode", feature = "flac-encode"))] +#[path = "flac_decode.rs"] +mod flac_decode; +#[cfg(feature = "g722")] +#[path = "g722_oracle.rs"] +mod g722_oracle; +#[cfg(feature = "g726")] +#[path = "g726_oracle.rs"] +mod g726_oracle; +#[cfg(feature = "gsm")] +#[path = "gsm_oracle.rs"] +mod gsm_oracle; +#[cfg(feature = "mpa-encode")] +#[path = "mp2_encoder_oracle.rs"] +mod mp2_encoder_oracle; +#[cfg(feature = "qoa")] +#[path = "qoa_oracle.rs"] +mod qoa_oracle; +#[cfg(feature = "sbc")] +#[path = "sbc_oracle.rs"] +mod sbc_oracle; +#[cfg(feature = "vmd-decode")] +#[path = "vmd.rs"] +mod vmd; +#[cfg(all(feature = "vorbis-decode", feature = "vorbis-encode"))] +#[path = "vorbis_decode_hostile.rs"] +mod vorbis_decode_hostile; +#[cfg(all(feature = "vorbis-decode", feature = "vorbis-encode", feature = "decode"))] +#[path = "vorbis_decode_oracle.rs"] +mod vorbis_decode_oracle; +#[cfg(feature = "vorbis-decode")] +#[path = "vorbis_decode_synthetic.rs"] +mod vorbis_decode_synthetic; diff --git a/crates/audio/tests/vorbis_decode_hostile.rs b/crates/audio/tests/vorbis_decode_hostile.rs index fba004e109..4bbccfe460 100644 --- a/crates/audio/tests/vorbis_decode_hostile.rs +++ b/crates/audio/tests/vorbis_decode_hostile.rs @@ -57,7 +57,8 @@ fn damaged_headers_never_panic() { let mut seed = 99u32; for which in [0usize, 2] { let len = p.headers[which].len(); - for _ in 0..800 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the mutations. + for _ in 0..800usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut h = p.headers.clone(); for _ in 0..1 + xorshift(&mut seed) % 3 { let at = xorshift(&mut seed) as usize % len; diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml new file mode 100644 index 0000000000..7fd0ce225b --- /dev/null +++ b/crates/automation/Cargo.toml @@ -0,0 +1,64 @@ +[package] +name = "craft-automation" +description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue and synthetic input on every target; server, client, frame profiler and frame trace native only), and recorded actions with the Actions panel (every target)." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +autotests = false + +[lib] +# The lib's test target is the crate's one test executable: its trials and, with `screen-testing`, the +# screen tests in tests/it. +harness = false + +[lints] +workspace = true + +[features] +suite = ["screen-testing", "craft-ui/suite"] +default = [] +# The egui parts: the Actions panel, the control channel's server side (screenshots, synthetic +# input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`, +# `Params` and the recorded actions' model and files. +ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"] +# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`. +screen-testing = ["ui", "agents", "craft-ui/testing"] +# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an +# app's `-cli mcp` reads and that CLI's live client (all `craft-control`'s, re-exported), and +# with `ui` the link host and the Agents page. The agent settings build on every target without it. +agents = ["craft-control/agents", "dep:craft-host"] + +[dependencies] +# The screenshot reply's PNG and its inline base64 (the control channel builds on every target with `ui`). +base64 = "0.23" +craft-behavior = { workspace = true, optional = true } +# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the +# CLI's live client), re-exported by `agents` so every app shares one copy. +craft-control = { workspace = true } +# The recorded actions' file picks (`ui`) go through the host on every target. +craft-host = { workspace = true, optional = true } +craft-keymap = { workspace = true, optional = true } +craft-theme = { workspace = true } +craft-ui = { workspace = true, optional = true } +egui = { workspace = true, optional = true } +png = "0.17" +serde = { workspace = true } +serde_json = { workspace = true } +craft-platform = { workspace = true } +log = "0.4" +# `std::time::Instant` panics on wasm; this is the same type on native. +web-time = "1.1" + +# The server, client, token files, profiler and trace. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +getrandom = "0.3" +hmac = "0.12" +sha2 = { version = "0.10", default-features = false, features = ["std"] } +thiserror = { workspace = true } + +[dev-dependencies] +tempfile = "3" +craft-ui = { workspace = true, features = ["suite"] } +egui = { workspace = true } diff --git a/crates/automation/README.md b/crates/automation/README.md new file mode 100644 index 0000000000..2fdbf75be4 --- /dev/null +++ b/crates/automation/README.md @@ -0,0 +1,25 @@ +# craft-automation + +Drive a running Craft app from tests, agents and the CLI, and record and play actions. The control channel, its transport, screenshots, the profiler and the trace are desktop only; `actions`, `ui::actions` and the agent settings build on every target, the browser included. + +Features: `ui` (the egui parts), `agents` (agents in the open window: the launcher's switch, the connection file, the link host and the Agents page; desktop), `screen-testing` (stories and the integration binary; turns on both). + +| Module | What it gives the app | +| --- | --- | +| `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. | +| `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. | +| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `-cli mcp` finds the open window by; the CLI's live client (`Live`, `LiveConfig`, `Route`). All of these are `craft_control::agents`, re-exported, so apps without the shared UI library use the same code. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. | +| `ui::agents` | `AgentsPage` (desktop, features `agents` and `ui`): the Agents page of Preferences, a custom page over the agent settings in the Preferences draft, with the link's status; the folder rows are `PathSetting`s. `AgentsWords` holds its words. | +| `args` | `ControlOptions`: the `--control `, `--control-token`, `--control-token-file` values and their `_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). | +| `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. | +| `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. | +| `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | +| `profiler` | `FrameStages` and `SlowFrames`: where a frame's time went, the slow ones kept for the control channel's `perf` output and one log line a second. | +| `trace` | `FrameTrace`: every frame of a gesture (a brush stroke, a drag) as a row, a percentile summary per gesture, optional CSV. | + +The app owns its methods (`engine.execute`, `ui.inspect`, `ui.set`, …): `ControlChannel::next_request` hands it each request and `ControlChannel::settle` takes the `Reply`. The library owns everything a method table does not: deadlines, dispatch accounting, waiters, the screenshot budget, injected input and the transport. diff --git a/crates/automation/src/access.rs b/crates/automation/src/access.rs new file mode 100644 index 0000000000..d25f93d112 --- /dev/null +++ b/crates/automation/src/access.rs @@ -0,0 +1,390 @@ +//! Named controls over the window's access tree (`ui.find`, `control` targets) and `ui.inspect` (the reported +//! widgets of a window's access tree, and the lookup of the one node a click or a focus names). +//! +//! Both read the tree the window host keeps from the last presented frame ([`WindowHost::keep_access_tree`], which +//! the control server turns on) and walk only the nodes assistive technology reports ([`AccessTree::keys`]): a hidden node, +//! one below it and one behind an open modal are neither listed nor reachable. + +use std::collections::HashSet; + +use craft_behavior::Mixed; +use craft_ui::runtime::access::Role; +use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey, name}; +use craft_ui::runtime::windows::WindowHost; +use egui::{Rect, ViewportId}; +use serde_json::{Map, Value, json}; + +use crate::protocol::Params; + +/// The error of a request made before the first kept pass has an access tree. +pub const NO_TREE: &str = "no accessibility tree yet: send the request after a frame was drawn"; + +/// The error of a target no control matches. +pub const NO_CONTROL: &str = "no control matches"; + +/// The error of a target several controls match, with no `index`. +pub const AMBIGUOUS: &str = "more than one control matches"; + +/// The error of a control with no bounds to place a point on. +pub const NO_PLACE: &str = "the control has no place on the screen"; + +/// The largest `index` a target takes. +pub const MAX_INDEX: usize = 1024; + +/// The widgets `ui.inspect` lists when the request names no `limit`. +pub const DEFAULT_LIMIT: u64 = 500; + +/// The place of a control a target names: its rect in screen points, or the error why it has none. +pub type ControlMap<'a> = &'a dyn Fn(&Target) -> Result; + +/// A control named by `{name, role?, within?, index?}`. +/// +/// A name match ignores surrounding white space and one trailing `:`; `role` is an AccessKit role name, compared +/// ignoring case; `within` is the name of any matching ancestor. Without `index` exactly one control matches; the +/// reading order is depth first. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Target { + /// The control's accessible name. + pub name: String, + /// The control's role. + pub role: Option, + /// The name of an ancestor the control is inside. + pub within: Option, + /// Which match to take, in reading order. + pub index: Option, +} + +/// `text` as a name is compared: without surrounding white space and one trailing `:`. +fn plain(text: &str) -> &str { + let text = text.trim(); + text.strip_suffix(':').unwrap_or(text).trim() +} + +/// The node a method names: its id or its label. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NodeTarget { + /// The node's id. + Id(u64), + /// The node's label, matched case-insensitively. + Label(String), +} + +impl NodeTarget { + /// The node `params` name (`id` or `label`), or none when they name none. `id` is the id `ui.inspect` lists, a + /// decimal string or a number; `label` is a string; naming both is an error. Other fields are the caller's to + /// check; a `null` field is absent. + pub fn from_params(params: &Value) -> Result, String> { + let field = |key: &str| params.get(key).filter(|value| !value.is_null()); + match (field("id"), field("label")) { + (Some(_), Some(_)) => Err("`id` and `label` exclude each other".into()), + (Some(id), None) => { + let raw = id.as_u64().or_else(|| id.as_str().and_then(|text| text.parse().ok())); + raw.map(|raw| Some(NodeTarget::Id(raw))).ok_or_else(|| "id must be a widget id from ui.inspect".into()) + } + (None, Some(Value::String(label))) => Ok(Some(NodeTarget::Label(label.clone()))), + (None, Some(_)) => Err("label must be a string".into()), + (None, None) => Ok(None), + } + } +} + +/// What a node that takes `action` is, for the refusal of one that does not. +fn able(action: Declared) -> &'static str { + match action { + Declared::Click => "clickable", + Declared::Focus => "focusable", + Declared::ContextMenu => "a widget with a context menu", + _ => "a widget that takes this action", + } +} + +/// Queues `action` on the node `target` names in `viewport`'s kept access tree. +fn inject_node(host: &WindowHost, viewport: ViewportId, target: &NodeTarget, action: Declared) -> Result<(), String> { + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + let node = resolve(&tree, target, action)?; + host.inject_access(viewport, node, action); + Ok(()) +} + +/// Queues a click of the node `target` names in `viewport`, once the kept tree has it as one reported, enabled, +/// clickable node ([`resolve`]). +pub fn inject_click(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::Click) +} + +/// Queues the context menu of the node `target` names in `viewport`, once the kept tree has it as one reported, +/// enabled node with a context menu ([`resolve`]). +pub fn inject_context_menu(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::ContextMenu) +} + +/// Queues the focus request for the node `target` names in `viewport`, once the kept tree has it as one reported, +/// enabled, focusable node ([`resolve`]). +pub fn inject_focus(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::Focus) +} + +/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none, +/// several, disabled or undeclared. An id must be a reported node; a label matches the reported, enabled nodes that +/// declare `action` and whose label equals it, ignoring case, and exactly one must match. +pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result { + let reported = tree.keys(); + let label_of = |key: NodeKey| tree.name_of(key).unwrap_or("unlabelled").to_owned(); + let key = match target { + NodeTarget::Id(raw) => { + let key = NodeKey::from_raw(*raw); + if !reported.contains(&key) { + return Err(format!("no widget with id {raw} on screen (run ui.inspect again)")); + } + key + } + NodeTarget::Label(label) => { + let wanted = label.to_lowercase(); + let named: Vec = + reported.iter().copied().filter(|key| tree.name_of(*key).is_some_and(|name| name.to_lowercase() == wanted)).collect(); + let usable: Vec = named.iter().copied().filter(|key| !tree.is_disabled_key(*key) && tree.declares_key(*key, action)).collect(); + match usable.as_slice() { + [one] => *one, + [] if named.is_empty() => return Err(format!("no widget labelled {label:?} on screen (try ui.inspect with query)")), + [] if named.iter().any(|key| tree.declares_key(*key, action)) => { + return Err(format!("the widget labelled {label:?} is disabled")); + } + [] => return Err(format!("the widget labelled {label:?} is not {}", able(action))), + many => return Err(format!("{} widgets are labelled {label:?}; name one by id", many.len())), + } + } + }; + if tree.is_disabled_key(key) { + return Err(format!("widget {} ({}) is disabled", key.raw(), label_of(key))); + } + if !tree.declares_key(key, action) { + return Err(format!("widget {} ({}) is not {}", key.raw(), label_of(key), able(action))); + } + Ok(key) +} + +/// The accesskit role's name as agents' scripts read it (`Button`, `CheckBox`). +fn role_name(tree: &AccessTree, key: NodeKey) -> Option { + match tree.role_of(key)? { + Role::Node(role) => Some(format!("{role:?}")), + _ => None, + } +} + +impl Target { + /// The target `value` names: `{name, role?, within?, index?}` and no other field. + pub fn from_params(value: &Value) -> Result { + let p = Params(value).only(None, &["name", "role", "within", "index"])?; + let p = Params(&p); + let target = p.str_field("name")?.ok_or_else(|| "missing `name`".to_owned())?; + if target.trim().is_empty() { + return Err("`name` must not be empty".into()); + } + let index = match p.uint_field("index")? { + Some(index) if index > MAX_INDEX as u64 => return Err(format!("`index` must be at most {MAX_INDEX} (got {index})")), + index => index.map(|index| index as usize), + }; + Ok(Self { name: target.to_owned(), role: p.str_field("role")?.map(str::to_owned), within: p.str_field("within")?.map(str::to_owned), index }) + } + + /// Whether the control `key` has this target's name, role and ancestor. + fn accepts(&self, tree: &AccessTree, key: NodeKey) -> bool { + let named = |key: NodeKey, wanted: &str| name(tree, key).is_some_and(|found| plain(found) == plain(wanted)); + if !named(key, &self.name) { + return false; + } + if self.role.as_deref().is_some_and(|wanted| !role_name(tree, key).is_some_and(|role| role.eq_ignore_ascii_case(wanted))) { + return false; + } + let Some(within) = self.within.as_deref() else { return true }; + let mut above = tree.parent_of_key(key); + while let Some(ancestor) = above { + if named(ancestor, within) { + return true; + } + above = tree.parent_of_key(ancestor); + } + false + } + + /// The error of no control matching, with the fields the target gave. + fn missing(&self) -> String { + let mut error = format!("{NO_CONTROL}: name `{}`", self.name); + if let Some(role) = &self.role { + error.push_str(&format!(" role `{role}`")); + } + if let Some(within) = &self.within { + error.push_str(&format!(" within `{within}`")); + } + if let Some(index) = self.index { + error.push_str(&format!(" index {index}")); + } + error + } + + /// The control of `tree` this target names: [`NO_CONTROL`] when none matches, [`AMBIGUOUS`] when several do and + /// there is no `index`. + pub fn find(&self, tree: &AccessTree) -> Result { + let reported: HashSet = tree.keys().into_iter().collect(); + let mut matches = Vec::new(); + let mut pending: Vec = tree.root_key().into_iter().collect(); + while let Some(key) = pending.pop() { + if reported.contains(&key) && self.accepts(tree, key) { + matches.push(key); + } + pending.extend(tree.children_of(key).into_iter().rev()); + } + match (self.index, matches.as_slice()) { + (_, []) => Err(self.missing()), + (Some(index), found) => found.get(index).copied().ok_or_else(|| format!("index {index} is past the {} matching controls", found.len())), + (None, [only]) => Ok(*only), + (None, found) => Err(format!("{AMBIGUOUS} ({}): add `role`, `within` or `index`", found.len())), + } + } + + /// The rect of this target's control in the tree the host kept for `viewport`: [`NO_TREE`] before the first, + /// [`NO_PLACE`] for a control with no area. + pub fn rect(&self, host: &WindowHost, viewport: ViewportId) -> Result { + let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?; + tree.bounds_of(self.find(&tree)?) + .filter(|rect| rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0) + .ok_or_else(|| NO_PLACE.to_owned()) + } +} + +/// What `ui.find` answers for the control `key`: `{name, role, rect or null, enabled, focused, value?, numeric?, +/// expanded?, selected?, toggled?}`, the rect in screen points. +pub fn describe(tree: &AccessTree, key: NodeKey) -> Value { + let mut out = Map::new(); + out.insert("name".into(), json!(name(tree, key))); + out.insert("role".into(), json!(role_name(tree, key))); + out.insert("rect".into(), json!(tree.bounds_of(key).map(|rect| [rect.left(), rect.top(), rect.width(), rect.height()]))); + out.insert("enabled".into(), json!(!tree.is_disabled_key(key))); + out.insert("focused".into(), json!(tree.focused_key() == key)); + if let Some(value) = tree.value_of(key) { + out.insert("value".into(), json!(value)); + } + if let Some(numeric) = tree.numeric_of(key) { + out.insert("numeric".into(), json!({"value": numeric.value, "range": [numeric.range.start(), numeric.range.end()], "step": numeric.step})); + } + if let Some(expanded) = tree.expanded_of(key) { + out.insert("expanded".into(), json!(expanded)); + } + if let Some(selected) = tree.selected_of(key) { + out.insert("selected".into(), json!(selected)); + } + if let Some(toggled) = tree.toggled_of(key) { + out.insert( + "toggled".into(), + match toggled { + Mixed::Same(on) => json!(on), + Mixed::Mixed => json!("mixed"), + }, + ); + } + Value::Object(out) +} + +/// Runs the access method `method` with `params` in `viewport` from the tree the host kept ([`NO_TREE`] before the +/// first); `None` for a method this module does not have. +pub fn access_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId) -> Option> { + match method { + "ui.find" => Some(find(params, host, viewport)), + _ => None, + } +} + +/// `ui.find`: the description of the control `params` names. +fn find(params: &Value, host: &WindowHost, viewport: ViewportId) -> Result { + let target = Target::from_params(params)?; + let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?; + Ok(describe(&tree, target.find(&tree)?)) +} + +/// One listed widget: `{id, role, depth, enabled, clickable, focusable}` and, where the node says, `label`, `value`, +/// `description`, `rect` (`[x0, y0, x1, y1]` in points), `toggled` (`true`, `false` or `mixed`), `selected`, and +/// `focused: true` for the focused node. The id is a decimal string: 64-bit ids do not survive JSON readers that use +/// doubles. +fn widget(tree: &AccessTree, key: NodeKey, depth: usize, focused: bool) -> Value { + let mut w = Map::new(); + w.insert("id".into(), json!(key.raw().to_string())); + w.insert("role".into(), json!(role_name(tree, key))); + w.insert("depth".into(), json!(depth)); + w.insert("enabled".into(), json!(!tree.is_disabled_key(key))); + w.insert("clickable".into(), json!(tree.declares_key(key, Declared::Click))); + w.insert("focusable".into(), json!(tree.declares_key(key, Declared::Focus))); + if let Some(label) = tree.name_of(key) { + w.insert("label".into(), json!(label)); + } + if let Some(value) = tree.value_of(key) { + w.insert("value".into(), json!(value)); + } + if let Some(description) = tree.description_of(key) { + w.insert("description".into(), json!(description)); + } + if let Some(rect) = tree.bounds_of(key) { + w.insert("rect".into(), json!([rect.min.x, rect.min.y, rect.max.x, rect.max.y])); + } + if let Some(toggled) = tree.toggled_of(key) { + let toggled = match toggled { + Mixed::Same(true) => "true", + Mixed::Same(false) => "false", + Mixed::Mixed => "mixed", + }; + w.insert("toggled".into(), json!(toggled)); + } + if let Some(selected) = tree.selected_of(key) { + w.insert("selected".into(), json!(selected)); + } + if focused { + w.insert("focused".into(), json!(true)); + } + Value::Object(w) +} + +/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes +/// of `viewport`'s access tree, in tree order (depth first from the root, which is not listed, children in their +/// order). `query` matches a widget whose label, value or description contains it, ignoring case; `role` its role's +/// name, ignoring case; `focused` whether it is the focused node. `count` is every widget the filters keep, `widgets` +/// the first `limit` of them. No other fields; [`NO_TREE`] before the window presented a frame. +pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let p = Params(params).only(None, &["query", "role", "focused", "limit"])?; + let p = Params(&p); + let query = p.str_field("query")?.map(str::to_lowercase); + let role = p.str_field("role")?.map(str::to_lowercase); + let focused = p.bool_field("focused")?; + let limit = usize::try_from(p.uint_field("limit")?.unwrap_or(DEFAULT_LIMIT)).unwrap_or(usize::MAX); + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + + let reported: HashSet = tree.keys().into_iter().collect(); + let root = tree.root_key(); + let focus = tree.focused_key(); + let (mut widgets, mut count) = (Vec::new(), 0usize); + // A stack, not recursion: the tree comes from the app and may be deep. `walked` keeps a malformed tree that lists + // a node twice from listing it twice or looping. + let mut walked = HashSet::new(); + let mut pending: Vec<(NodeKey, usize)> = root.into_iter().map(|key| (key, 0)).collect(); + while let Some((key, depth)) = pending.pop() { + if !reported.contains(&key) || !walked.insert(key) { + continue; + } + pending.extend(tree.children_of(key).into_iter().rev().map(|child| (child, depth + 1))); + if Some(key) == root { + continue; + } + let text = + [tree.name_of(key), tree.value_of(key), tree.description_of(key)].into_iter().flatten().collect::>().join(" ").to_lowercase(); + let keep = query.as_ref().is_none_or(|query| text.contains(query.as_str())) + && role.as_ref().is_none_or(|role| role_name(&tree, key).is_some_and(|name| name.to_lowercase() == *role)) + && focused.is_none_or(|wanted| (key == focus) == wanted); + if !keep { + continue; + } + count += 1; + if widgets.len() < limit { + widgets.push(widget(&tree, key, depth, key == focus)); + } + } + Ok(json!({"widgets": widgets, "count": count, "truncated": count > widgets.len()})) +} diff --git a/crates/automation/src/actions/file.rs b/crates/automation/src/actions/file.rs new file mode 100644 index 0000000000..3553932c91 --- /dev/null +++ b/crates/automation/src/actions/file.rs @@ -0,0 +1,144 @@ +//! [`ActionsFile`]: the `actions.json` form, compatible with PhotoCraft's. + +use super::model::Action; + +/// The actions file (PhotoCraft's `actions.json` in its preset store): `{"version": 1, +/// "actions": [...]}`, plus `sets` with the names of empty sets, left out when there are none +/// and optional on load, so PhotoCraft's files load and save unchanged. Unknown fields are +/// ignored. +/// +/// A file PhotoCraft wrote with its folder occurrences (`set_rows`, and per action `set_slot`, +/// `action_id`, `legacy_shortcut_owner`) loads too: those fields are read into +/// `FileOccurrences` and [`ActionList::merge_file`](super::ActionList::merge_file) turns them +/// into unique set and action names. Names are the list's only identity, so they are never +/// written back. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(from = "RawFile")] +pub struct ActionsFile { + /// The file version, [`ActionsFile::VERSION`]. + pub version: u32, + /// The actions in list order. + pub actions: Vec, + /// Sets that hold no action. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sets: Vec, + /// Every set name in display order, empty sets included. Written only when loading `actions` + /// and `sets` would not give this order (the actions' sets in order of first appearance, then + /// the empty sets), so files in that natural order, PhotoCraft's included, save unchanged. + /// Files without it load in the natural order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub set_order: Vec, + /// The folder occurrences a PhotoCraft file carried; empty for every other file. + #[serde(skip)] + pub(super) occurrences: FileOccurrences, +} + +/// What a PhotoCraft file says beside the names: its ordered folder occurrences (same-name and +/// empty ones included) and, per action at the same index, its occurrence, stored id and whether +/// it owns the old name-keyed shortcut among actions of its name. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct FileOccurrences { + pub(super) set_rows: Vec, + pub(super) actions: Vec, +} + +/// One action's occurrence fields in a PhotoCraft file. +#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)] +pub(super) struct ActionOccurrence { + #[serde(default)] + pub(super) set_slot: Option, + #[serde(default)] + pub(super) action_id: Option, + #[serde(default)] + pub(super) legacy_shortcut_owner: bool, +} + +/// The file as it is read: each action with its occurrence fields beside it. +#[derive(serde::Deserialize)] +struct RawFile { + version: u32, + actions: Vec, + #[serde(default)] + sets: Vec, + #[serde(default)] + set_order: Vec, + #[serde(default)] + set_rows: Vec, +} + +#[derive(serde::Deserialize)] +struct RawAction { + #[serde(flatten)] + action: Action, + #[serde(flatten)] + occurrence: ActionOccurrence, +} + +impl From for ActionsFile { + fn from(raw: RawFile) -> Self { + let (actions, occurrences): (Vec, Vec) = raw.actions.into_iter().map(|raw| (raw.action, raw.occurrence)).unzip(); + let empty = raw.set_rows.is_empty() && occurrences.iter().all(|occurrence| *occurrence == ActionOccurrence::default()); + let occurrences = if empty { FileOccurrences::default() } else { FileOccurrences { set_rows: raw.set_rows, actions: occurrences } }; + ActionsFile { version: raw.version, actions, sets: raw.sets, set_order: raw.set_order, occurrences } + } +} + +/// Why an actions file did not load. +#[derive(Debug)] +#[non_exhaustive] +pub enum ActionsFileError { + /// The file's version is not [`ActionsFile::VERSION`]; a newer file is refused so it is never + /// loaded and then overwritten. + Version(u32), + /// The text is not a valid actions file. + Json(serde_json::Error), +} + +impl std::fmt::Display for ActionsFileError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ActionsFileError::Version(version) => write!(f, "unsupported actions file version {version}"), + ActionsFileError::Json(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for ActionsFileError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + ActionsFileError::Version(_) => None, + ActionsFileError::Json(error) => Some(error), + } + } +} + +impl From for ActionsFileError { + fn from(error: serde_json::Error) -> Self { + ActionsFileError::Json(error) + } +} + +impl ActionsFile { + /// The version this crate writes (PhotoCraft's). + // pc: crates/engine/src/preset_store.rs:1112. + pub const VERSION: u32 = 1; + + /// A file of version [`VERSION`](Self::VERSION) with `actions` and the empty `sets`. + pub fn new(actions: Vec, sets: Vec) -> Self { + ActionsFile { version: Self::VERSION, actions, sets, set_order: Vec::new(), occurrences: FileOccurrences::default() } + } + + /// Reads a file's JSON text. + pub fn from_json(text: &str) -> Result { + let file: ActionsFile = serde_json::from_str(text)?; + if file.version != Self::VERSION { + return Err(ActionsFileError::Version(file.version)); + } + Ok(file) + } + + /// The file as pretty JSON text. + pub fn to_json(&self) -> Result { + serde_json::to_string_pretty(self) + } +} diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs new file mode 100644 index 0000000000..ce533f7469 --- /dev/null +++ b/crates/automation/src/actions/list.rs @@ -0,0 +1,882 @@ +//! [`ActionList`]: the flat list of actions with an optional set each, and every edit the panel +//! and the app's commands need. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use super::file::{ActionOccurrence, ActionsFile}; +use super::model::{Action, ActionColor, ActionInclude, ActionStep}; + +/// Why an [`ActionList`] edit was refused. The app shows the message; nothing changed. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ActionListError { + /// No action at this index. + NoSuchAction(usize), + /// No step at this index of the action. + NoSuchStep { + /// The action. + action: usize, + /// The step. + step: usize, + }, + /// A destination past the end. + OutOfRange, + /// No set of this name. + NoSuchSet(String), + /// Another action (or set) already has the name. + NameTaken(String), + /// The name is empty or only white space. + EmptyName, + /// No Clear All, Reset or Replace to undo: none was made, or an edit since ended its undo. + NothingToUndo, +} + +impl std::fmt::Display for ActionListError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ActionListError::NoSuchAction(_) => f.write_str("no such action"), + ActionListError::NoSuchStep { .. } => f.write_str("no such step"), + ActionListError::NoSuchSet(_) => f.write_str("no such set"), + ActionListError::OutOfRange => f.write_str("destination is out of range"), + ActionListError::NameTaken(_) => f.write_str("an action with this name already exists"), + ActionListError::EmptyName => f.write_str("\"name\" is empty"), + ActionListError::NothingToUndo => f.write_str("no Actions library change is available to undo"), + } + } +} + +impl std::error::Error for ActionListError {} + +/// What [`ActionList::merge_file`] added. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct MergedFile { + /// The indices of the actions added. + pub added: Vec, + /// The (name in the file, name given) pair of each action renamed to stay unique. + pub renames: Vec<(String, String)>, + /// The (stored id, name given) pair of each action a PhotoCraft file gave an `action_id`, so + /// the app moves what it keyed by the id (`actions.playById:` shortcuts, calls by + /// `actionId`) to the name. An id the file repeats is left out, as PhotoCraft ignores it. + pub ids: Vec<(String, String)>, +} + +/// Which whole-list command an undo reverts: the Actions panel's Clear All Actions, Reset +/// Actions… or Replace Actions…. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum LibraryEdit { + /// [`ActionList::clear_all`]. + ClearAll, + /// [`ActionList::reset`]. + Reset, + /// [`ActionList::replace_all`]. + Replace, +} + +/// The list before the last whole-list command. +#[derive(Clone, Debug, PartialEq)] +struct LibrarySnapshot { + edit: LibraryEdit, + actions: Vec, + sets: Vec, +} + +/// The recorded actions: one flat list (PhotoCraft's engine, journal and file are flat), each +/// action with an optional set name, plus the order of every set, with or without actions, so New +/// Set works before anything is recorded into it and a set keeps its place as it fills and empties +/// (VectorCraft's nested sets map onto it). +/// +/// The list is app data shared by the panel, the app's commands, the CLI and the control channel: +/// the panel only reads it and reports events, and the app applies each event with these calls +/// (owner question 1, recommended answer). Every successful edit bumps [`revision`](Self::revision), +/// so a store can skip unchanged writes; the revision only moves forward, also when the whole list +/// is [replaced](Self::replace). Indices are into [`actions`](Self::actions). +/// +/// Action names are unique across the whole list, whatever their sets: the app finds an action +/// by its name (calls, function keys, scripts). An edit that would repeat a name is refused, and +/// a loaded file's repeated names are renamed (`Foo`, `Foo 2`). Set names are unique likewise. +/// +/// Clear All, Reset and Replace keep one undo: [`undo_library`](Self::undo_library) restores the +/// list as it was before the last of them, until any other edit ends it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ActionList { + pub(super) actions: Vec, + pub(super) sets: Vec, + pub(super) revision: u64, + undo: Option>, +} + +impl ActionList { + /// An empty list. + pub fn new() -> Self { + Self::default() + } + + /// The actions in list order. + pub fn actions(&self) -> &[Action] { + &self.actions + } + + /// The action at `index`. + pub fn action(&self, index: usize) -> Option<&Action> { + self.actions.get(index) + } + + /// Every set name in display order: the order sets were made or loaded, with or without actions. + /// A set an action names that the order lacks follows, by first appearance. + pub fn sets(&self) -> Vec<&str> { + let mut sets: Vec<&str> = self.sets.iter().map(String::as_str).collect(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()) { + if !sets.contains(&set) { + sets.push(set); + } + } + sets + } + + /// The set of the action at `index`. + pub fn set_of(&self, index: usize) -> Option<&str> { + self.actions.get(index).and_then(|action| action.set.as_deref()) + } + + /// The panel's order of action indices: loose actions first, then each set's actions, sets + /// in [`sets`](Self::sets) order. + pub fn display_order(&self) -> Vec { + let mut order: Vec = (0..self.actions.len()).filter(|&i| self.actions[i].set.is_none()).collect(); + for set in self.sets() { + order.extend((0..self.actions.len()).filter(|&i| self.actions[i].set.as_deref() == Some(set))); + } + order + } + + /// The number of steps of the action at `index` (0 when there is none). + pub fn step_count(&self, index: usize) -> usize { + self.actions.get(index).map_or(0, |action| action.steps.len()) + } + + /// `base` if no action has it, else `base 2`, `base 3` … the first free one. With an empty + /// `base`, PhotoCraft's `Action n` from the list's length + 1 up. + pub fn unique_name(&self, base: &str) -> String { + let mut names = Names::of(&self.actions); + if base.is_empty() { + let mut n = self.actions.len() + 1; + loop { + let name = format!("Action {n}"); + if !names.taken.contains(&name) { + return name; + } + n += 1; + } + } + names.claim(base) + } + + /// Adds an empty action named `name` at the end (in `set` when given); returns its index. + pub fn new_action(&mut self, name: &str, set: Option) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + let set = set.map(|set| set.trim().to_owned()).filter(|set| !set.is_empty()); + if self.name_in_use(name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + if let Some(set) = &set { + self.record_set(set); + } + self.actions.push(Action { set, ..Action::new(name, Vec::new()) }); + self.touch(); + Ok(self.actions.len() - 1) + } + + /// Adds an empty set named `name`; refuses a taken or empty name. + pub fn new_set(&mut self, name: &str) -> Result<(), ActionListError> { + let name = name.trim(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + if self.sets().contains(&name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + self.sets.push(name.to_owned()); + self.touch(); + Ok(()) + } + + /// Renames the action at `index` to `name` (trimmed name not empty, not taken; the same name + /// is a success that changes nothing). `calls` sees every step of every action with the old + /// and new names, so the app rewrites its own calls (PhotoCraft: `actions.play`'s `action`, + /// `actions.conditional`'s `then` and `else`); the app also moves its shortcut override and + /// rewrites its pending journal itself. + pub fn rename(&mut self, index: usize, name: &str, mut calls: impl FnMut(&mut ActionStep, &str, &str)) -> Result<(), ActionListError> { + let name = name.trim(); + let old = self.actions.get(index).ok_or(ActionListError::NoSuchAction(index))?.name.clone(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + if old == name { + return Ok(()); + } + if self.name_in_use(name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + self.actions[index].name = name.to_owned(); + for step in self.actions.iter_mut().flat_map(|action| action.steps.iter_mut()) { + calls(step, &old, name); + } + self.touch(); + Ok(()) + } + + /// Removes and returns the action at `index`; the set it leaves empty stays, in its place. + pub fn delete_action(&mut self, index: usize) -> Result { + if index >= self.actions.len() { + return Err(ActionListError::NoSuchAction(index)); + } + let action = self.actions.remove(index); + self.touch(); + Ok(action) + } + + /// Removes and returns step `step` of action `action`; `disabled` and `dialogs` follow (the + /// removed index is dropped, later ones move down). + pub fn delete_step(&mut self, action: usize, step: usize) -> Result { + let target = self.actions.get_mut(action).ok_or(ActionListError::NoSuchAction(action))?; + if step >= target.steps.len() { + return Err(ActionListError::NoSuchStep { action, step }); + } + let removed = target.steps.remove(step); + target.remap_steps(|i| match i.cmp(&step) { + std::cmp::Ordering::Less => Some(i), + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => Some(i - 1), + }); + self.touch(); + Ok(removed) + } + + /// Moves the action at `from` to `to` (an index in the list after the removal, PhotoCraft's + /// `actions.move`). + pub fn move_action(&mut self, from: usize, to: usize) -> Result<(), ActionListError> { + if from >= self.actions.len() { + return Err(ActionListError::NoSuchAction(from)); + } + if to >= self.actions.len() { + return Err(ActionListError::OutOfRange); + } + let moved = self.actions.remove(from); + self.actions.insert(to, moved); + self.touch(); + Ok(()) + } + + /// Puts the action at `index` into `set` (`None`: out of any set), as a drop into or out of a + /// set folder does. A new set goes at the end of the order; the set the action leaves stays, in + /// its place, even when it is now empty. + pub fn assign_set(&mut self, index: usize, set: Option) -> Result<(), ActionListError> { + if index >= self.actions.len() { + return Err(ActionListError::NoSuchAction(index)); + } + let set = match set { + None => None, + Some(set) if set.trim().is_empty() => return Err(ActionListError::EmptyName), + Some(set) => Some(set.trim().to_owned()), + }; + if let Some(set) = &set { + self.record_set(set); + } + self.actions[index].set = set; + self.touch(); + Ok(()) + } + + /// Moves step `step` of action `from` to position `to` of action `into` (the same action or + /// another). Within one action `disabled` and `dialogs` follow [`moved_index`]; between + /// actions the step takes its include and dialog flags along. A set never changes: one whose last + /// step moves away keeps its place. + pub fn move_step(&mut self, from: usize, step: usize, into: usize, to: usize) -> Result<(), ActionListError> { + let source = self.actions.get(from).ok_or(ActionListError::NoSuchAction(from))?; + if step >= source.steps.len() { + return Err(ActionListError::NoSuchStep { action: from, step }); + } + let target_len = self.actions.get(into).ok_or(ActionListError::NoSuchAction(into))?.steps.len(); + if from == into { + if to >= target_len { + return Err(ActionListError::OutOfRange); + } + let action = &mut self.actions[from]; + let moved = action.steps.remove(step); + action.steps.insert(to, moved); + action.remap_steps(|i| Some(moved_index(i, step, to))); + } else { + if to > target_len { + return Err(ActionListError::OutOfRange); + } + let (enabled, dialog) = (source.step_enabled(step), source.dialogs.contains(&step)); + let source = &mut self.actions[from]; + let moved = source.steps.remove(step); + source.remap_steps(|i| match i.cmp(&step) { + std::cmp::Ordering::Less => Some(i), + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => Some(i - 1), + }); + let target = &mut self.actions[into]; + target.steps.insert(to, moved); + target.remap_steps(|i| Some(if i >= to { i + 1 } else { i })); + if !enabled { + target.disabled.insert(to); + } + if dialog { + target.dialogs.insert(to); + } + } + self.touch(); + Ok(()) + } + + /// Switches step `step` of `action` on or off for playback; returns its new state. + pub fn toggle_step(&mut self, action: usize, step: usize) -> Result { + let on = !self.action(action).ok_or(ActionListError::NoSuchAction(action))?.step_enabled(step); + self.set_step(action, step, on)?; + Ok(on) + } + + /// Sets whether playback runs step `step` of `action`: the panel's include cell on a step + /// row, as a [`Toggle`](crate::ui::actions::ActionsEvent::Toggle) event reports it. + pub fn set_step(&mut self, action: usize, step: usize, on: bool) -> Result<(), ActionListError> { + let target = self.actions.get_mut(action).ok_or(ActionListError::NoSuchAction(action))?; + if step >= target.steps.len() { + return Err(ActionListError::NoSuchStep { action, step }); + } + let changed = if on { target.disabled.remove(&step) } else { target.disabled.insert(step) }; + if changed { + self.touch(); + } + Ok(()) + } + + /// The include column on an action row: every step on unless all already are, in which case + /// every step off. Returns whether the steps are now on. + pub fn toggle_all(&mut self, action: usize) -> Result { + let target = self.actions.get(action).ok_or(ActionListError::NoSuchAction(action))?; + if target.steps.is_empty() { + return Ok(false); + } + let enable = target.include() != ActionInclude::All; + self.set_all(action, enable)?; + Ok(enable) + } + + /// Switches every step of `action` on or off: the panel's include cell on an action row, as + /// a [`Toggle`](crate::ui::actions::ActionsEvent::Toggle) event reports it. An action with + /// no steps stays as it is. + pub fn set_all(&mut self, action: usize, on: bool) -> Result<(), ActionListError> { + let target = self.actions.get_mut(action).ok_or(ActionListError::NoSuchAction(action))?; + let disabled = if on { BTreeSet::new() } else { (0..target.steps.len()).collect() }; + if target.disabled != disabled { + target.disabled = disabled; + self.touch(); + } + Ok(()) + } + + /// Switches the dialog flag of step `step` of `action`; returns its new state. + pub fn toggle_dialog(&mut self, action: usize, step: usize) -> Result { + let on = !self.action(action).ok_or(ActionListError::NoSuchAction(action))?.dialogs.contains(&step); + self.set_dialog(action, step, on)?; + Ok(on) + } + + /// Sets the dialog flag of step `step` of `action`: the panel's dialog cell, as a + /// [`Toggle`](crate::ui::actions::ActionsEvent::Toggle) event reports it. + pub fn set_dialog(&mut self, action: usize, step: usize, on: bool) -> Result<(), ActionListError> { + let target = self.actions.get_mut(action).ok_or(ActionListError::NoSuchAction(action))?; + if step >= target.steps.len() { + return Err(ActionListError::NoSuchStep { action, step }); + } + let changed = if on { target.dialogs.insert(step) } else { target.dialogs.remove(&step) }; + if changed { + self.touch(); + } + Ok(()) + } + + /// Sets the Button Mode colour of the action at `index`. + pub fn set_color(&mut self, index: usize, color: ActionColor) -> Result<(), ActionListError> { + self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?.color = color; + self.touch(); + Ok(()) + } + + /// Replaces the app's own options of the action at `index` ([`Action::options`]). Setting the options it holds + /// changes nothing, so the revision stays. + pub fn set_options(&mut self, index: usize, options: serde_json::Map) -> Result<(), ActionListError> { + let action = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if action.options != options { + action.options = options; + self.touch(); + } + Ok(()) + } + + /// Appends a whole action and returns its index; an empty or taken name is refused. + pub fn push(&mut self, action: Action) -> Result { + if action.name.trim().is_empty() { + return Err(ActionListError::EmptyName); + } + if self.name_in_use(&action.name) { + return Err(ActionListError::NameTaken(action.name)); + } + if let Some(set) = &action.set { + self.record_set(set); + } + self.actions.push(action); + self.touch(); + Ok(self.actions.len() - 1) + } + + /// Inserts `step` at `at` in action `action`; `disabled` and `dialogs` at or after `at` move + /// up. + pub fn insert_step(&mut self, action: usize, at: usize, step: ActionStep) -> Result<(), ActionListError> { + let target = self.actions.get_mut(action).ok_or(ActionListError::NoSuchAction(action))?; + if at > target.steps.len() { + return Err(ActionListError::OutOfRange); + } + target.steps.insert(at, step); + target.remap_steps(|i| Some(if i >= at { i + 1 } else { i })); + self.touch(); + Ok(()) + } + + /// Inserts a copy of action `index` below itself under a unique name and returns its index; + /// `shift(step, at, count)` sees every step of every action so the app moves its calls by + /// index. + pub fn duplicate_action(&mut self, index: usize, mut shift: impl FnMut(&mut ActionStep, usize, usize)) -> Result { + let mut copy = self.actions.get(index).ok_or(ActionListError::NoSuchAction(index))?.clone(); + copy.name = self.unique_name(&format!("{} copy", copy.name)); + let at = index + 1; + self.actions.insert(at, copy); + self.shift_calls(at, 1, &mut shift); + self.touch(); + Ok(at) + } + + /// Inserts a copy of step `step` of action `action` after itself, with its include and dialog + /// flags. + pub fn duplicate_step(&mut self, action: usize, step: usize) -> Result<(), ActionListError> { + let source = self.actions.get(action).ok_or(ActionListError::NoSuchAction(action))?; + let copied = source.steps.get(step).cloned().ok_or(ActionListError::NoSuchStep { action, step })?; + let (disabled, dialog) = (!source.step_enabled(step), source.dialogs.contains(&step)); + let at = step + 1; + self.insert_step(action, at, copied)?; + let target = &mut self.actions[action]; + if disabled { + target.disabled.insert(at); + } + if dialog { + target.dialogs.insert(at); + } + Ok(()) + } + + /// Renames the set `set` to `name` (trimmed) in the order and in every member's `set`: [`ActionListError::EmptyName`] + /// for an empty name, [`ActionListError::NameTaken`] for a name another set has, [`ActionListError::NoSuchSet`] for an + /// unknown set. The same name succeeds and changes nothing. + pub fn rename_set(&mut self, set: &str, name: &str) -> Result<(), ActionListError> { + let name = name.trim(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + let order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let at = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + if name == set { + return Ok(()); + } + if order.iter().any(|each| each == name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + self.sets = order; + self.sets[at] = name.to_owned(); + for action in self.actions.iter_mut().filter(|action| action.set.as_deref() == Some(set)) { + action.set = Some(name.to_owned()); + } + self.touch(); + Ok(()) + } + + /// Removes the set `set` from the order and its actions from the list, and returns the actions in list order: + /// [`ActionListError::NoSuchSet`] for an unknown set. + pub fn delete_set(&mut self, set: &str) -> Result, ActionListError> { + if !self.sets().contains(&set) { + return Err(ActionListError::NoSuchSet(set.to_owned())); + } + let (removed, kept): (Vec, Vec) = + std::mem::take(&mut self.actions).into_iter().partition(|action| action.set.as_deref() == Some(set)); + self.actions = kept; + self.sets.retain(|each| each != set); + self.touch(); + Ok(removed) + } + + /// Duplicates the set `set` under a unique name and returns that name; `shift` is as for + /// [`duplicate_action`](Self::duplicate_action). The new set goes right after `set` in the order; + /// the copies of its actions go after its last action, and a set with none gives an empty set. + pub fn duplicate_set(&mut self, set: &str, mut shift: impl FnMut(&mut ActionStep, usize, usize)) -> Result { + let mut order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let position = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + let name = Names::new(order.iter().cloned()).claim(&format!("{set} copy")); + order.insert(position + 1, name.clone()); + self.sets = order; + let members: Vec = (0..self.actions.len()).filter(|&i| self.actions[i].set.as_deref() == Some(set)).collect(); + if let Some(&last) = members.last() { + let at = last + 1; + // Each copy's name is claimed before the next, so the copies never repeat one. + let mut names = Names::of(&self.actions); + for (offset, &source) in members.iter().enumerate() { + let mut copy = self.actions[source].clone(); + copy.set = Some(name.clone()); + copy.name = names.claim(&format!("{} copy", copy.name)); + self.actions.insert(at + offset, copy); + } + self.shift_calls(at, members.len(), &mut shift); + } + self.touch(); + Ok(name) + } + + /// Replaces step `step` of action `action` with `with` and returns the step it replaced. + pub fn replace_step(&mut self, action: usize, step: usize, with: ActionStep) -> Result { + let target = self.actions.get_mut(action).ok_or(ActionListError::NoSuchAction(action))?; + let slot = target.steps.get_mut(step).ok_or(ActionListError::NoSuchStep { action, step })?; + let replaced = std::mem::replace(slot, with); + self.touch(); + Ok(replaced) + } + + /// Marks action `index` as written (or not) by an automation client. Marking it as it already + /// is changes nothing, so the revision stays. + pub fn set_automation(&mut self, index: usize, on: bool) -> Result<(), ActionListError> { + let action = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if action.automation != on { + action.automation = on; + self.touch(); + } + Ok(()) + } + + /// Adds the actions of `file`, each under a name unique in the list; with `replace`, the + /// actions of every set the file names are dropped first. The file's empty sets are added when + /// absent. `calls(step, &renames)` runs once on every step of every action just added, after + /// all renames are known (also when there are none). + /// + /// A PhotoCraft file's folder occurrences become sets: the first occurrence of a set name + /// keeps it (and joins a set of that name already in the list, as a plain file's set does), + /// each later one gets a unique name (`Set 2`), and an empty one becomes an empty set. Of the + /// actions sharing a name, the file's shortcut owner keeps the name. The stored ids come back + /// in [`MergedFile::ids`]. + pub fn merge_file(&mut self, file: ActionsFile, replace: bool, mut calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { + let ActionsFile { mut actions, sets, set_order, occurrences, .. } = file; + if replace { + let named: BTreeSet<&str> = actions + .iter() + .filter_map(|action| action.set.as_deref()) + .chain(sets.iter().map(String::as_str)) + .chain(set_order.iter().map(String::as_str)) + .chain(occurrences.set_rows.iter().map(String::as_str)) + .collect(); + self.actions.retain(|action| !action.set.as_deref().is_some_and(|set| named.contains(set))); + } + let fields = |index: usize| occurrences.actions.get(index).cloned().unwrap_or_default(); + let empty_sets = self.fold_occurrences(&mut actions, sets, &occurrences.set_rows, &fields); + // The shortcut owners claim first, so each keeps its name over an earlier namesake. + let owners = (0..actions.len()).filter(|&i| fields(i).legacy_shortcut_owner); + let order: Vec = owners.chain((0..actions.len()).filter(|&i| !fields(i).legacy_shortcut_owner)).collect(); + let claimed = Names::of(&self.actions).claim_all(order.iter().map(|&i| actions[i].name.as_str())); + let mut given = vec![String::new(); actions.len()]; + for (&i, name) in order.iter().zip(claimed) { + given[i] = name; + } + for set in &set_order { + self.record_set(set); + } + let mut merged = MergedFile::default(); + let ids = file_ids(&occurrences.actions); + for (index, (mut action, name)) in actions.into_iter().zip(given).enumerate() { + if name != action.name { + merged.renames.push((action.name.clone(), name.clone())); + } + if let Some(Some(id)) = ids.get(index) { + merged.ids.push((id.clone(), name.clone())); + } + action.name = name; + if let Some(set) = &action.set { + self.record_set(set); + } + self.actions.push(action); + merged.added.push(self.actions.len() - 1); + } + for &index in &merged.added { + for step in &mut self.actions[index].steps { + calls(step, &merged.renames); + } + } + for set in empty_sets { + self.record_set(&set); + } + self.touch(); + merged + } + + /// Gives each action of a file the set name of its folder occurrence and returns the file's + /// empty sets: the plain ones, then each occurrence that holds no action. The first + /// occurrence of a name keeps it; a later one, or one whose name a plain set of the file has, + /// claims a name unique among the list's sets and the file's. + fn fold_occurrences( + &self, + actions: &mut [Action], + sets: Vec, + set_rows: &[String], + fields: &dyn Fn(usize) -> ActionOccurrence, + ) -> Vec { + if set_rows.is_empty() { + return sets; + } + // An action's slot counts only where the file's occurrence still has its set name. + let slot_of = + |index: usize, action: &Action| fields(index).set_slot.filter(|&slot| set_rows.get(slot).map(String::as_str) == action.set.as_deref()); + let plain: HashSet<&str> = actions + .iter() + .enumerate() + .filter(|(index, action)| slot_of(*index, action).is_none()) + .filter_map(|(_, action)| action.set.as_deref()) + .chain(sets.iter().map(String::as_str)) + .collect(); + let mut names = Names::new(self.sets().into_iter().chain(plain.iter().copied()).map(str::to_owned)); + let mut first: HashSet<&str> = HashSet::new(); + let slot_names: Vec = set_rows + .iter() + .map(|caption| { + if !plain.contains(caption.as_str()) && first.insert(caption.as_str()) { + names.taken.insert(caption.clone()); + caption.clone() + } else { + names.claim(caption) + } + }) + .collect(); + let mut filled = vec![false; set_rows.len()]; + let slots: Vec> = actions.iter().enumerate().map(|(index, action)| slot_of(index, action)).collect(); + for (action, slot) in actions.iter_mut().zip(slots) { + if let Some(slot) = slot { + action.set = Some(slot_names[slot].clone()); + filled[slot] = true; + } + } + let mut empty = sets; + empty.extend(slot_names.into_iter().zip(filled).filter(|(_, filled)| !filled).map(|(name, _)| name)); + empty + } + + /// The list a file holds (its empty sets included), named as [`merge_file`](Self::merge_file) + /// names a file's actions and sets in an empty list: a name the file repeats is renamed + /// (`Foo`, `Foo 2`), and a call by that name keeps reaching the first action that has it. The + /// app that keys anything by a PhotoCraft file's stored ids uses [`load`](Self::load). + pub fn from_file(file: ActionsFile) -> Self { + Self::load(file).0 + } + + /// [`from_file`](Self::from_file) with what loading renamed and the stored ids. + pub fn load(file: ActionsFile) -> (Self, MergedFile) { + let mut list = Self::new(); + let merged = list.merge_file(file, false, |_, _| {}); + list.revision = 0; + (list, merged) + } + + /// Clear All Actions: no action and no set. [`undo_library`](Self::undo_library) restores + /// them. + pub fn clear_all(&mut self) { + self.library_edit(LibraryEdit::ClearAll, |list| { + list.actions.clear(); + list.sets.clear(); + }); + } + + /// Reset Actions…: the app's `defaults` (its starting sets), added to the list with `append` + /// (renamed where a name is taken, as [`merge_file`](Self::merge_file) does), else in place + /// of everything. `calls` is as for `merge_file`. + pub fn reset(&mut self, defaults: ActionsFile, append: bool, calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { + self.library_edit(LibraryEdit::Reset, |list| { + if !append { + list.actions.clear(); + list.sets.clear(); + } + list.merge_file(defaults, false, calls) + }) + } + + /// Replace Actions…: the list becomes what `file` holds, named as [`load`](Self::load) names + /// it. `calls` is as for [`merge_file`](Self::merge_file). + pub fn replace_all(&mut self, file: ActionsFile, calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { + self.library_edit(LibraryEdit::Replace, |list| { + list.actions.clear(); + list.sets.clear(); + list.merge_file(file, false, calls) + }) + } + + /// The whole-list command [`undo_library`](Self::undo_library) would revert, for the app's + /// Undo label; `None` when an edit since ended it. + pub fn library_undo(&self) -> Option { + self.undo.as_ref().map(|snapshot| snapshot.edit) + } + + /// Restores the list as it was before the last Clear All, Reset or Replace and returns which + /// one it reverted. + pub fn undo_library(&mut self) -> Result { + let snapshot = self.undo.take().ok_or(ActionListError::NothingToUndo)?; + let LibrarySnapshot { edit, actions, sets } = *snapshot; + self.actions = actions; + self.sets = sets; + self.touch(); + Ok(edit) + } + + /// Runs a whole-list command and keeps the list from before it as the one undo. + fn library_edit(&mut self, edit: LibraryEdit, apply: impl FnOnce(&mut Self) -> R) -> R { + let snapshot = LibrarySnapshot { edit, actions: self.actions.clone(), sets: self.sets.clone() }; + let result = apply(self); + self.touch(); + self.undo = Some(Box::new(snapshot)); + result + } + + /// Replaces the whole list with `with` (a list loaded or restored from elsewhere): its actions + /// and sets, under this list's revision bumped once, so the revision only moves forward and a + /// store that compares revisions sees the change. + pub fn replace(&mut self, with: ActionList) { + let revision = self.revision; + *self = Self { revision, ..with }; + self.touch(); + } + + /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`, the set order in `set_order` when it is not the natural one). + pub fn to_file(&self) -> ActionsFile { + let empty = self.sets().into_iter().filter(|set| !self.actions.iter().any(|action| action.set.as_deref() == Some(*set))); + let mut file = ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()); + let mut natural: Vec<&str> = Vec::new(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()).chain(file.sets.iter().map(String::as_str)) { + if !natural.contains(&set) { + natural.push(set); + } + } + if natural != self.sets() { + file.set_order = self.sets().into_iter().map(str::to_owned).collect(); + } + file + } + + /// Puts `set` at the end of the set order when the order lacks it. + fn record_set(&mut self, set: &str) { + if !self.sets.iter().any(|each| each == set) { + self.sets.push(set.to_owned()); + } + } + + /// Whether an action has `name`. + fn name_in_use(&self, name: &str) -> bool { + self.actions.iter().any(|action| action.name == name) + } + + /// Calls `shift(step, at, count)` on every step of every action, after `count` actions were + /// inserted at `at`. + fn shift_calls(&mut self, at: usize, count: usize, shift: &mut impl FnMut(&mut ActionStep, usize, usize)) { + for step in self.actions.iter_mut().flat_map(|action| action.steps.iter_mut()) { + shift(step, at, count); + } + } + + /// Bumped by every successful edit. + pub fn revision(&self) -> u64 { + self.revision + } + + /// Marks the list changed by an edit made outside these calls (the app replaced an action's + /// steps). Every edit ends the undo of the last Clear All, Reset or Replace. + pub fn touch(&mut self) { + self.revision = self.revision.wrapping_add(1); + self.undo = None; + } +} + +/// Each action's stored id, where it is PhotoCraft's form (32 lowercase hex digits) and no other +/// action of the file has it. +fn file_ids(occurrences: &[ActionOccurrence]) -> Vec> { + let valid = |id: &&String| id.len() == 32 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + let mut count: HashMap<&str, usize> = HashMap::new(); + for id in occurrences.iter().filter_map(|occurrence| occurrence.action_id.as_ref()).filter(valid) { + *count.entry(id).or_default() += 1; + } + occurrences.iter().map(|occurrence| occurrence.action_id.clone().filter(|id| valid(&id) && count.get(id.as_str()) == Some(&1))).collect() +} + +/// The names taken so far and, per base name, the next suffix to try, so claiming one base many +/// times (a file that repeats a name) stays linear. +#[derive(Default)] +struct Names { + taken: HashSet, + next: HashMap, +} + +impl Names { + fn new(taken: impl IntoIterator) -> Self { + Self { taken: taken.into_iter().collect(), next: HashMap::new() } + } + + /// The names of `actions`. + fn of(actions: &[Action]) -> Self { + Self::new(actions.iter().map(|action| action.name.clone())) + } + + /// The names for `bases`, in order. Every base that is free keeps its name, even when an + /// earlier repeat of another base would have picked it as a suffix; only the repeats and the + /// clashes with taken names go through [`claim`](Self::claim). + fn claim_all<'a>(&mut self, bases: impl IntoIterator) -> Vec { + let bases: Vec<&str> = bases.into_iter().collect(); + let free: Vec = bases.iter().map(|base| self.taken.insert((*base).to_owned())).collect(); + bases.iter().zip(free).map(|(base, free)| if free { (*base).to_owned() } else { self.claim(base) }).collect() + } + + /// `base` if it is free, else `base 2`, `base 3` … the first free one; the name returned is + /// taken from then on. + fn claim(&mut self, base: &str) -> String { + if self.taken.insert(base.to_owned()) { + return base.to_owned(); + } + let mut n = self.next.get(base).copied().unwrap_or(2); + loop { + let name = format!("{base} {n}"); + n += 1; + if self.taken.insert(name.clone()) { + self.next.insert(base.to_owned(), n); + return name; + } + } + } +} + +/// Where the item at `index` ends up after the item at `from` moved to `to`: the moved item goes +/// to `to`, items between shift by one toward `from`, others stay. A selection or the recording +/// index follows a move with it. +pub fn moved_index(index: usize, from: usize, to: usize) -> usize { + if index == from { + to + } else if from < index && index <= to { + index - 1 + } else if to <= index && index < from { + index + 1 + } else { + index + } +} diff --git a/crates/automation/src/actions/mod.rs b/crates/automation/src/actions/mod.rs new file mode 100644 index 0000000000..777272ebc2 --- /dev/null +++ b/crates/automation/src/actions/mod.rs @@ -0,0 +1,31 @@ +//! Recorded actions (F13.06): the action list, its file form, playback and recording. Builds on +//! every target, the browser included. +//! +//! | Part | Names | +//! |---|---| +//! | The model | [`Action`], [`ActionStep`], [`ActionColor`], [`ActionInclude`] | +//! | The list and its edits | [`ActionList`], [`ActionListError`], [`LibraryEdit`], [`moved_index`] | +//! | The file | [`ActionsFile`] (PhotoCraft's `actions.json`), [`ActionsFileError`] | +//! | Playback | [`ActionPlayer`], [`ActionRunner`], [`StepOutcome`], [`PlaybackBudget`], [`PlaybackReport`], [`StepFailure`], [`PlaybackRefusal`], [`MAX_PLAYBACK_STEPS`], [`MAX_PLAYBACK_DEPTH`] | +//! | Recording | [`Recording`], [`ActionList::begin_recording`], [`ActionList::append_recorded`] | +//! +//! The app keeps the command table: what a step id means, which journal entries are replayable, +//! `.atn` import and export, shortcuts, and the pause-for-dialog resume. The Actions panel +//! ([`crate::ui::actions`]) reads an [`ActionList`] and reports events; the app applies them with +//! these calls, so its CLI and control channel share them. + +mod file; +mod list; +mod model; +mod player; +mod recording; +#[cfg(test)] +pub(crate) mod tests; + +pub use file::{ActionsFile, ActionsFileError}; +pub use list::{ActionList, ActionListError, LibraryEdit, MergedFile, moved_index}; +pub use model::{Action, ActionColor, ActionInclude, ActionStep}; +pub use player::{ + ActionPlayer, ActionRunner, MAX_PLAYBACK_DEPTH, MAX_PLAYBACK_STEPS, PlaybackBudget, PlaybackRefusal, PlaybackReport, StepFailure, StepOutcome, +}; +pub use recording::Recording; diff --git a/crates/automation/src/actions/model.rs b/crates/automation/src/actions/model.rs new file mode 100644 index 0000000000..09b3b6df1b --- /dev/null +++ b/crates/automation/src/actions/model.rs @@ -0,0 +1,208 @@ +//! [`Action`], [`ActionStep`], [`ActionColor`] and [`ActionInclude`]. + +use std::collections::BTreeSet; + +use craft_theme::LabelColor; + +use serde_json::Value; + +/// One recorded step: a command id and its parameters, the shape batch and droplets accept. +/// Serialised as the pair `[id, params]` (PhotoCraft's `(String, Value)`). +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(from = "(String, Value)", into = "(String, Value)")] +pub struct ActionStep { + /// The app's command id ("image.adjustments.levels", "actions.play"). + pub command: String, + /// The command's parameters. + pub params: Value, +} + +impl ActionStep { + /// A step running `command` with `params`. + pub fn new(command: impl Into, params: Value) -> Self { + Self { command: command.into(), params } + } +} + +impl From<(String, Value)> for ActionStep { + fn from((command, params): (String, Value)) -> Self { + Self { command, params } + } +} + +impl From for (String, Value) { + fn from(step: ActionStep) -> Self { + (step.command, step.params) + } +} + +/// An action's Button Mode colour: none and Photoshop's seven, serialised as +/// PhotoCraft's `BUTTON_COLORS` names (`""` for none, `"red"` … `"gray"`). An unknown name reads as +/// `None`. The file keeps this type (lead call 40) because [`LabelColor`] has eleven colours and +/// no "none"; [`label_color`](Self::label_color) maps it for words and tints. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(from = "String", into = "String")] +pub enum ActionColor { + /// No colour. + #[default] + None, + #[allow(missing_docs)] + Red, + #[allow(missing_docs)] + Orange, + #[allow(missing_docs)] + Yellow, + #[allow(missing_docs)] + Green, + #[allow(missing_docs)] + Blue, + #[allow(missing_docs)] + Violet, + #[allow(missing_docs)] + Gray, +} + +impl ActionColor { + /// Every colour in Photoshop's order, `None` first (the Color submenu's order). + pub const ALL: [ActionColor; 8] = [ + ActionColor::None, + ActionColor::Red, + ActionColor::Orange, + ActionColor::Yellow, + ActionColor::Green, + ActionColor::Blue, + ActionColor::Violet, + ActionColor::Gray, + ]; + + /// The file name: `""`, `"red"`, `"orange"`, `"yellow"`, `"green"`, `"blue"`, `"violet"`, + /// `"gray"`. + pub const fn name(self) -> &'static str { + match self { + ActionColor::None => "", + ActionColor::Red => "red", + ActionColor::Orange => "orange", + ActionColor::Yellow => "yellow", + ActionColor::Green => "green", + ActionColor::Blue => "blue", + ActionColor::Violet => "violet", + ActionColor::Gray => "gray", + } + } + + /// The [`LabelColor`] this colour is, for the shared colour words + /// (`LabelColorLabels::name`); `None` for no + /// colour. + pub const fn label_color(self) -> Option { + match self { + ActionColor::None => None, + ActionColor::Red => Some(LabelColor::Red), + ActionColor::Orange => Some(LabelColor::Orange), + ActionColor::Yellow => Some(LabelColor::Yellow), + ActionColor::Green => Some(LabelColor::Green), + ActionColor::Blue => Some(LabelColor::Blue), + ActionColor::Violet => Some(LabelColor::Violet), + ActionColor::Gray => Some(LabelColor::Gray), + } + } + + /// The colour a file name stands for; `None` for `""` and any unknown name. + pub fn from_name(name: &str) -> ActionColor { + ActionColor::ALL.into_iter().find(|color| color.name() == name).unwrap_or(ActionColor::None) + } +} + +impl From for ActionColor { + fn from(name: String) -> Self { + ActionColor::from_name(&name) + } +} + +impl From for String { + fn from(color: ActionColor) -> Self { + color.name().to_owned() + } +} + +/// How many of an action's steps playback runs: the include column's mark on an action row. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ActionInclude { + /// Every step (a check). + All, + /// Some steps are switched off (Photoshop's partial mark, "2/3 steps"). + Partial, + /// No step, or the action has none. + None, +} + +/// One recorded action, in PhotoCraft's `actions.json` shape: `steps` is the `[[id, params], …]` +/// list, `disabled` and `dialogs` hold step indices and are left out of the file when empty, `set`, +/// `color` and `automation` likewise. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Action { + /// The name, unique in its [`ActionList`](super::ActionList). + pub name: String, + /// The steps in order. + #[serde(default)] + pub steps: Vec, + /// Steps playback skips (unchecked in the include column). + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub disabled: BTreeSet, + /// Steps whose dialog shows during playback (the dialog column); what that means is the + /// app's ([`ActionRunner::run_step`](super::ActionRunner::run_step) gets the flag). + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub dialogs: BTreeSet, + /// The set the action belongs to (Photoshop's set folder); `None` for a loose action. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub set: Option, + /// The Button Mode colour. + #[serde(default, skip_serializing_if = "is_no_color")] + pub color: ActionColor, + /// Written by an automation client: playback keeps that client's gate. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub automation: bool, + /// The app's own options for the action. The framework never reads them; every edit, duplicate, move, merge and + /// the file keep them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub options: serde_json::Map, +} + +fn is_no_color(color: &ActionColor) -> bool { + *color == ActionColor::None +} + +impl Action { + /// An action named `name` with `steps`, all included, no dialogs, no set, no colour. + pub fn new(name: impl Into, steps: Vec) -> Self { + Self { name: name.into(), steps, ..Self::default() } + } + + /// Whether playback runs step `step`. + pub fn step_enabled(&self, step: usize) -> bool { + !self.disabled.contains(&step) + } + + /// The steps playback runs, with their indices. + pub fn enabled_steps(&self) -> impl Iterator { + self.steps.iter().enumerate().filter(|(i, _)| self.step_enabled(*i)) + } + + /// The include column's mark. + pub fn include(&self) -> ActionInclude { + let enabled = self.enabled_steps().count(); + if enabled == 0 { + ActionInclude::None + } else if enabled == self.steps.len() { + ActionInclude::All + } else { + ActionInclude::Partial + } + } + + /// Applies `map` to every index in `disabled` and `dialogs` after steps moved; `None` drops the + /// index. + pub fn remap_steps(&mut self, map: impl Fn(usize) -> Option) { + self.disabled = self.disabled.iter().filter_map(|&i| map(i)).collect(); + self.dialogs = self.dialogs.iter().filter_map(|&i| map(i)).collect(); + } +} diff --git a/crates/automation/src/actions/player.rs b/crates/automation/src/actions/player.rs new file mode 100644 index 0000000000..e0280dbd56 --- /dev/null +++ b/crates/automation/src/actions/player.rs @@ -0,0 +1,223 @@ +//! [`ActionPlayer`], [`ActionRunner`], [`StepOutcome`], [`PlaybackBudget`] and +//! [`PlaybackReport`]. + +use serde_json::Value; + +use super::list::ActionList; +use super::model::{Action, ActionStep}; + +/// The most steps one top-level playback runs, nested calls included (PhotoCraft's). +// pc: crates/engine/src/cmd/actions_cmds.rs:84 `MAX_PLAYBACK_STEPS`. +pub const MAX_PLAYBACK_STEPS: u64 = 100_000; + +/// The deepest nesting of actions playing actions (PhotoCraft's). +// pc: crates/engine/src/cmd/actions_cmds.rs:190 (`playback_stack.len() >= 16`). +pub const MAX_PLAYBACK_DEPTH: usize = 16; + +/// What one step did. +#[derive(Clone, Debug, PartialEq)] +pub enum StepOutcome { + /// It ran; the command's result (a nested call's result is checked by the runner). + Done(Value), + /// It ran and playback stops for the user to continue (Step by Step, Pause For): the step + /// counts as run, sets `paused_at` and `waiting`. + Wait(Value), + /// It stopped for a dialog (a step with its dialog flag, an Insert Stop): playback stops here + /// and the app resumes later with `from` = this step + 1. + Paused, + /// It stopped playback with no failure (a Stop with its dialog off): sets `stopped_at`. + Stopped, + /// It failed with this message: playback stops. + Failed(String), +} + +/// The app's side of playback: running one step. The player decides the order, skipping and +/// limits; the runner decides what a step means. Nested `actions.play` and +/// `actions.conditional` steps call [`ActionPlayer::play`] again from `run_step` with the same +/// budget. +pub trait ActionRunner { + /// Runs `step` (index `index` of `action`); `show_dialog` is the step's dialog flag. + fn run_step(&mut self, action: &Action, index: usize, step: &ActionStep, show_dialog: bool, budget: &mut PlaybackBudget) -> StepOutcome; + + /// Charges one step on `budget`; `false` stops playback with the step limit. A host whose + /// limit also counts scripts, batches and droplets charges that one counter here. + fn charge(&mut self, budget: &mut PlaybackBudget) -> bool { + budget.charge() + } + + /// The untrusted session's gate, asked before every step, nested ones included: an `Err` + /// stops playback with that message before the step runs. Allows every step by default. + fn authorize(&mut self, step: &ActionStep) -> Result<(), String> { + let _ = step; + Ok(()) + } + + /// A step Photoshop plays as a silent no-op (Deselect with nothing selected): it counts as run + /// without calling [`run_step`](Self::run_step). None by default. + fn is_noop(&self, step: &ActionStep) -> bool { + let _ = step; + false + } +} + +/// Why playback did not start or stopped, besides a step's own failure. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum PlaybackRefusal { + /// The action called is already playing further up (a loop). + Recursive(String), + /// More than [`MAX_PLAYBACK_DEPTH`] actions are playing inside one another. + TooDeep, + /// The [`MAX_PLAYBACK_STEPS`] limit was reached. + StepLimit, +} + +/// The step count and call stack shared by one top-level playback and every action it calls. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlaybackBudget { + pub(super) steps: u64, + pub(super) limit: u64, + pub(super) stack: Vec, +} + +impl PlaybackBudget { + /// A budget of [`MAX_PLAYBACK_STEPS`] for a new top-level playback. + pub fn new() -> Self { + Self { steps: 0, limit: MAX_PLAYBACK_STEPS, stack: Vec::new() } + } + + /// Charges one step; `false` once the limit is reached (the step must not run). A script host + /// with its own limit charges that one itself. + pub fn charge(&mut self) -> bool { + if self.steps >= self.limit { + return false; + } + self.steps += 1; + true + } + + /// Enters the action named `name`: refused when it is already on the stack (a call back to a + /// running action) or the stack is [`MAX_PLAYBACK_DEPTH`] deep. + pub fn enter(&mut self, name: &str) -> Result<(), PlaybackRefusal> { + if self.stack.iter().any(|running| running == name) { + return Err(PlaybackRefusal::Recursive(name.to_owned())); + } + if self.stack.len() >= MAX_PLAYBACK_DEPTH { + return Err(PlaybackRefusal::TooDeep); + } + self.stack.push(name.to_owned()); + Ok(()) + } + + /// Leaves the innermost action. + pub fn leave(&mut self) { + self.stack.pop(); + } + + /// Steps charged so far. + pub fn steps(&self) -> u64 { + self.steps + } +} + +impl Default for PlaybackBudget { + fn default() -> Self { + Self::new() + } +} + +/// A step that stopped playback. +#[derive(Clone, Debug, PartialEq)] +pub struct StepFailure { + /// The step's index in its action. + pub step: usize, + /// Its command id. + pub command: String, + /// The message (the runner's, the gate's, or the limit's: "action playback exceeded the + /// 100000-step limit"). + pub message: String, +} + +/// What one [`ActionPlayer::play`] did. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PlaybackReport { + /// Steps run (no-ops included). + pub ran: u64, + /// The step that failed, if one did. + pub failed: Option, + /// The step that paused for a dialog, if one did; the app resumes from the next step. + pub paused_at: Option, + /// Playback did not start or stopped for a limit or a loop. + pub refused: Option, + /// A step returned [`StepOutcome::Wait`]: playback stopped for the user to continue. + pub waiting: bool, + /// The step that returned [`StepOutcome::Stopped`], if one did. + pub stopped_at: Option, +} + +/// Plays recorded actions. +pub struct ActionPlayer; + +impl ActionPlayer { + /// Plays the action at `index` of `list` from step `from`: enters it on `budget` (refusing a + /// loop or depth), then for each included step at or after `from`, in order: charges it + /// through [`ActionRunner::charge`] (stops with the step-limit failure when refused), asks + /// [`authorize`](ActionRunner::authorize) (a denial stops without running or pausing), counts + /// a [no-op](ActionRunner::is_noop) as run, else runs the step; stops at the first `Failed`, + /// at `Paused` (reporting `paused_at`), at `Wait` (counted as run, reporting `paused_at` and + /// `waiting`) and at `Stopped` (reporting `stopped_at`, no failure). Skipped (disabled) steps + /// are not charged. Leaves + /// the action on `budget` before returning. An index past the list reports + /// `failed` with the message "no such action". Playing the action being recorded into is the + /// app's to refuse (PhotoCraft's `playback_plan` does), since the list holds no recording. + pub fn play(list: &ActionList, index: usize, from: usize, runner: &mut dyn ActionRunner, budget: &mut PlaybackBudget) -> PlaybackReport { + let Some(action) = list.action(index) else { + let failure = StepFailure { step: 0, command: String::new(), message: "no such action".to_owned() }; + return PlaybackReport { failed: Some(failure), ..PlaybackReport::default() }; + }; + let mut report = PlaybackReport::default(); + if let Err(refusal) = budget.enter(&action.name) { + report.refused = Some(refusal); + return report; + } + for (i, step) in action.enabled_steps().filter(|(i, _)| *i >= from) { + let fail = |message: String| StepFailure { step: i, command: step.command.clone(), message }; + if !runner.charge(budget) { + report.failed = Some(fail(format!("action playback exceeded the {}-step limit", budget.limit))); + report.refused = Some(PlaybackRefusal::StepLimit); + break; + } + if let Err(message) = runner.authorize(step) { + report.failed = Some(fail(message)); + break; + } + if runner.is_noop(step) { + report.ran += 1; + continue; + } + match runner.run_step(action, i, step, action.dialogs.contains(&i), budget) { + StepOutcome::Done(_) => report.ran += 1, + StepOutcome::Wait(_) => { + report.ran += 1; + report.paused_at = Some(i); + report.waiting = true; + break; + } + StepOutcome::Stopped => { + report.stopped_at = Some(i); + break; + } + StepOutcome::Paused => { + report.paused_at = Some(i); + break; + } + StepOutcome::Failed(message) => { + report.failed = Some(fail(message)); + break; + } + } + } + budget.leave(); + report + } +} diff --git a/crates/automation/src/actions/recording.rs b/crates/automation/src/actions/recording.rs new file mode 100644 index 0000000000..bc12757887 --- /dev/null +++ b/crates/automation/src/actions/recording.rs @@ -0,0 +1,49 @@ +//! [`Recording`]: steps the app's journal gives, appended to an action. + +use super::list::{ActionList, ActionListError}; +use super::model::ActionStep; + +/// A recording under way: the action it records into and where the app's journal stood when it +/// started. The app keeps it (PhotoCraft's `ActionState::recording`), filters its journal past +/// `journal_start` for replayable commands (its own rule: not `actions.*` edits, not +/// `edit.transform.again`), and appends them with [`ActionList::append_recorded`] on Stop or +/// before an edit of that action. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Recording { + /// The action recorded into. + pub action: usize, + /// The app's journal length when the recording started or last flushed. + pub journal_start: usize, +} + +impl ActionList { + /// Starts a recording: into the action at `into`, or into a new action with a + /// [unique name](ActionList::unique_name) (in `set` when given) when `into` is `None`. + /// `journal_start` is the app's journal length now. + pub fn begin_recording(&mut self, into: Option, set: Option, journal_start: usize) -> Result { + let index = match into { + Some(index) => { + if index >= self.actions.len() { + return Err(ActionListError::NoSuchAction(index)); + } + index + } + None => { + let name = self.unique_name(""); + self.new_action(&name, set)? + } + }; + Ok(Recording { action: index, journal_start }) + } + + /// Appends `steps` to the action at `index` (a flush of the journal while recording). + pub fn append_recorded(&mut self, index: usize, steps: impl IntoIterator) -> Result<(), ActionListError> { + let action = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + let before = action.steps.len(); + action.steps.extend(steps); + if action.steps.len() != before { + self.touch(); + } + Ok(()) + } +} diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs new file mode 100644 index 0000000000..2ae7845e9f --- /dev/null +++ b/crates/automation/src/actions/tests.rs @@ -0,0 +1,367 @@ +//! The action list, its file and the player. + +use craft_ui::testing::trial; +use serde_json::{Value, json}; + +use super::*; + +fn step(command: &str) -> ActionStep { + ActionStep::new(command, Value::Null) +} + +fn action(name: &str, commands: &[&str]) -> Action { + Action::new(name, commands.iter().map(|c| step(c)).collect()) +} + +fn list_of(actions: Vec) -> ActionList { + ActionList::from_file(ActionsFile::new(actions, Vec::new())) +} + +/// Runs every step by recording its command. +#[derive(Default)] +struct Script { + ran: Vec, +} + +impl ActionRunner for Script { + fn run_step(&mut self, _: &Action, _: usize, step: &ActionStep, _: bool, _: &mut PlaybackBudget) -> StepOutcome { + self.ran.push(step.command.clone()); + StepOutcome::Done(Value::Null) + } +} + +// `moved_index` cases (the moved item, items between, items outside); `move_step` within an action +// remaps `disabled` and `dialogs`, and between actions carries the flags along. +#[trial] +fn action_list_moves_follow_the_selection() { + assert_eq!(moved_index(1, 1, 3), 3); + assert_eq!(moved_index(2, 1, 3), 1); + assert_eq!(moved_index(2, 3, 1), 3); + assert_eq!(moved_index(0, 1, 3), 0); + assert_eq!(moved_index(4, 1, 3), 4); + + let mut list = list_of(vec![action("A", &["a", "b", "c"]), action("B", &["x"])]); + list.actions[0].disabled.insert(0); + list.actions[0].dialogs.insert(2); + list.move_step(0, 0, 0, 2).unwrap(); + let commands: Vec<_> = list.actions[0].steps.iter().map(|s| s.command.as_str()).collect(); + assert_eq!(commands, ["b", "c", "a"]); + assert_eq!(list.actions[0].disabled.iter().copied().collect::>(), [2]); + assert_eq!(list.actions[0].dialogs.iter().copied().collect::>(), [1]); + + list.move_step(0, 2, 1, 0).unwrap(); + assert_eq!(list.actions[0].steps.len(), 2); + assert!(list.actions[0].disabled.is_empty()); + assert_eq!(list.actions[1].steps[0].command, "a"); + assert!(list.actions[1].disabled.contains(&0)); + assert_eq!(list.move_step(0, 0, 1, 5), Err(ActionListError::OutOfRange)); + + list.move_action(0, 1).unwrap(); + assert_eq!(list.actions[1].name, "A"); +} +// PhotoCraft's `actions.json` shape (steps as `[id, params]`, colour names, no `sets`, the +// `automation` mark only when set) loads and saves unchanged; empty sets survive in `sets`; a file +// of another version is refused. +#[trial] +fn action_list_file_round_trip_keeps_pc_json() { + let text = r#"{"version":1,"actions":[{"name":"A","steps":[["image.levels",{"gamma":1.2}]],"disabled":[0],"set":"S","color":"red"},{"name":"B","steps":[],"automation":true}]}"#; + let file = ActionsFile::from_json(text).unwrap(); + assert!(!file.actions[0].automation && file.actions[1].automation); + assert!(matches!(ActionsFile::from_json(r#"{"version":2,"actions":[]}"#), Err(ActionsFileError::Version(2)))); + assert_eq!(file.actions[0].color, ActionColor::Red); + assert_eq!(file.actions[0].steps[0], ActionStep::new("image.levels", json!({"gamma": 1.2}))); + let mut list = ActionList::from_file(file); + let saved: Value = serde_json::from_str(&list.to_file().to_json().unwrap()).unwrap(); + assert_eq!(saved, serde_json::from_str::(text).unwrap()); + + list.new_set("Empty").unwrap(); + assert_eq!(list.sets(), ["S", "Empty"]); + let back = ActionsFile::from_json(&list.to_file().to_json().unwrap()).unwrap(); + assert_eq!(back.sets, ["Empty"]); + assert_eq!(ActionList::from_file(back).sets(), ["S", "Empty"]); +} +// An empty set made before filled ones keeps its place through a save; a file of the older layout +// (empty sets in `sets`, no `set_order`) loads with its filled sets first. +#[trial] +fn set_order_survives_the_file() { + let mut list = ActionList::new(); + list.new_set("A").unwrap(); + list.new_set("B").unwrap(); + list.new_set("C").unwrap(); + list.push(Action { set: Some("B".into()), ..action("X", &[]) }).unwrap(); + list.push(Action { set: Some("C".into()), ..action("Y", &[]) }).unwrap(); + let back = ActionList::from_file(ActionsFile::from_json(&list.to_file().to_json().unwrap()).unwrap()); + assert_eq!(back.sets(), ["A", "B", "C"]); + + let old = r#"{"version":1,"actions":[{"name":"X","steps":[],"set":"F"}],"sets":["E"]}"#; + assert_eq!(ActionList::from_file(ActionsFile::from_json(old).unwrap()).sets(), ["F", "E"]); +} +// A file that repeats a name keeps a later action's own name: `Foo, Foo, Foo 2` renames the repeat +// (`Foo 3`), never the real `Foo 2`; a merge does the same against the names already in the list. +#[trial] +fn action_names_in_a_file_keep_their_own_names_and_rename_only_repeats() { + let names = |list: &ActionList| list.actions.iter().map(|action| action.name.clone()).collect::>(); + let file = || ActionsFile::new(vec![action("Foo", &[]), action("Foo", &[]), action("Foo 2", &[])], Vec::new()); + assert_eq!(names(&ActionList::from_file(file())), ["Foo", "Foo 3", "Foo 2"]); + + let mut list = list_of(vec![action("Foo", &[])]); + let merged = list.merge_file(file(), false, |_, _| {}); + assert_eq!(names(&list), ["Foo", "Foo 3", "Foo 4", "Foo 2"]); + assert_eq!(merged.renames, [("Foo".to_owned(), "Foo 3".to_owned()), ("Foo".to_owned(), "Foo 4".to_owned())]); +} + +// A PhotoCraft file with folder occurrences: two folders named "Basics" and an empty one become +// sets with unique names, the empty one an empty set; of two actions named "Play", the shortcut +// owner keeps the name; each unique stored id maps to its action's final name, a repeated one to +// none; and the occurrence fields are never written back. +#[trial] +fn action_file_folder_occurrences_become_unique_names() { + let text = r#"{"version":1,"set_rows":["Basics","Basics","Empty"],"actions":[ + {"name":"Play","steps":[],"set":"Basics","set_slot":0,"action_id":"0123456789abcdef0123456789abcdef"}, + {"name":"Play","steps":[],"set":"Basics","set_slot":1,"legacy_shortcut_owner":true}, + {"name":"Loose","steps":[],"action_id":"ffffffffffffffffffffffffffffffff"}, + {"name":"Twin","steps":[],"action_id":"ffffffffffffffffffffffffffffffff"}]}"#; + let (list, merged) = ActionList::load(ActionsFile::from_json(text).unwrap()); + let names: Vec<(&str, Option<&str>)> = list.actions().iter().map(|action| (action.name.as_str(), action.set.as_deref())).collect(); + assert_eq!(names, [("Play 2", Some("Basics")), ("Play", Some("Basics 2")), ("Loose", None), ("Twin", None)]); + assert_eq!(list.sets(), ["Basics", "Basics 2", "Empty"]); + assert_eq!(merged.ids, [("0123456789abcdef0123456789abcdef".to_owned(), "Play 2".to_owned())]); + let saved = list.to_file().to_json().unwrap(); + assert!(["set_rows", "set_slot", "action_id", "legacy_shortcut_owner"].iter().all(|field| !saved.contains(field))); +} + +// Clear All, Reset (append and replace) and Replace each keep one undo that restores the list as it +// was, actions and empty sets alike; any other edit after them leaves nothing to undo. +#[trial] +fn action_library_commands_keep_one_undo() { + let mut list = list_of(vec![action("Invert Colors", &["image.invert"])]); + list.new_set("Empty").unwrap(); + let before = (list.actions().to_vec(), list.sets().into_iter().map(str::to_owned).collect::>()); + let state = |list: &ActionList| (list.actions().to_vec(), list.sets().into_iter().map(str::to_owned).collect::>()); + let defaults = || ActionsFile::new(vec![Action { set: Some("Basics".into()), ..action("Invert Colors", &["image.invert"]) }], Vec::new()); + + list.clear_all(); + assert!(list.actions().is_empty() && list.sets().is_empty()); + assert_eq!(list.library_undo(), Some(LibraryEdit::ClearAll)); + assert_eq!(list.undo_library(), Ok(LibraryEdit::ClearAll)); + assert_eq!(state(&list), before); + + list.reset(defaults(), true, |_, _| {}); + let names: Vec<&str> = list.actions().iter().map(|action| action.name.as_str()).collect(); + assert_eq!(names, ["Invert Colors", "Invert Colors 2"]); + assert_eq!(list.undo_library(), Ok(LibraryEdit::Reset)); + assert_eq!(state(&list), before); + + list.reset(defaults(), false, |_, _| {}); + assert_eq!(list.sets(), ["Basics"]); + list.undo_library().unwrap(); + assert_eq!(state(&list), before); + + list.replace_all(ActionsFile::new(vec![action("Other", &[])], Vec::new()), |_, _| {}); + assert_eq!(list.actions().len(), 1); + list.set_color(0, ActionColor::Red).unwrap(); + assert_eq!(list.library_undo(), None); + assert_eq!(list.undo_library(), Err(ActionListError::NothingToUndo)); +} + +/// A runner whose steps are named by what they do: `pause`, `wait`, `stop`, `deny` (refused by the +/// gate), `noop`; any other is `Done`. Its own `charge` refuses once `charges` are spent. +struct Scripted { + ran: Vec, + charges: u64, +} + +impl Scripted { + fn new(charges: u64) -> Self { + Self { ran: Vec::new(), charges } + } +} + +impl ActionRunner for Scripted { + fn run_step(&mut self, _: &Action, _: usize, step: &ActionStep, _: bool, _: &mut PlaybackBudget) -> StepOutcome { + self.ran.push(step.command.clone()); + match step.command.as_str() { + "pause" => StepOutcome::Paused, + "wait" => StepOutcome::Wait(Value::Null), + "stop" => StepOutcome::Stopped, + _ => StepOutcome::Done(Value::Null), + } + } + + fn charge(&mut self, _: &mut PlaybackBudget) -> bool { + if self.charges == 0 { + return false; + } + self.charges -= 1; + true + } + + fn authorize(&mut self, step: &ActionStep) -> Result<(), String> { + if step.command == "deny" { Err("denied".to_owned()) } else { Ok(()) } + } + + fn is_noop(&self, step: &ActionStep) -> bool { + step.command == "noop" + } +} + +// The runner's `charge` ends playback with the step limit; `Paused` is not counted, `Wait` is; a +// resume continues after `paused_at`; `Stopped` is no failure; a denial fails before the step runs; +// a no-op counts without running. +#[trial] +fn paused_waiting_and_stopped_steps_end_playback_as_reported() { + let list = list_of(vec![ + action("Limit", &["a", "b"]), + action("Pause", &["a", "pause", "b"]), + action("Wait", &["a", "wait", "b"]), + action("Stop", &["a", "stop", "b"]), + action("Deny", &["a", "deny", "b"]), + action("Noop", &["noop", "a"]), + ]); + let play = |index: usize, from: usize, runner: &mut Scripted| ActionPlayer::play(&list, index, from, runner, &mut PlaybackBudget::new()); + + let mut runner = Scripted::new(1); + let report = play(0, 0, &mut runner); + assert_eq!((report.ran, report.refused), (1, Some(PlaybackRefusal::StepLimit))); + assert_eq!(report.failed.map(|failure| failure.step), Some(1)); + + let mut runner = Scripted::new(99); + let report = play(1, 0, &mut runner); + assert_eq!((report.ran, report.paused_at, report.waiting), (1, Some(1), false)); + let resumed = play(1, 2, &mut runner); + assert_eq!((resumed.ran, resumed.paused_at), (1, None)); + assert_eq!(runner.ran, ["a", "pause", "b"]); + + let mut runner = Scripted::new(99); + let report = play(2, 0, &mut runner); + assert_eq!((report.ran, report.paused_at, report.waiting), (2, Some(1), true)); + assert_eq!(runner.ran, ["a", "wait"]); + + let mut runner = Scripted::new(99); + let report = play(3, 0, &mut runner); + assert_eq!((report.ran, report.stopped_at, report.paused_at), (1, Some(1), None)); + assert!(report.failed.is_none()); + + let mut runner = Scripted::new(99); + let report = play(4, 0, &mut runner); + assert_eq!(report.failed.map(|failure| (failure.step, failure.message)), Some((1, "denied".to_owned()))); + assert_eq!(runner.ran, ["a"], "the denied step never ran"); + + let mut runner = Scripted::new(99); + let report = play(5, 0, &mut runner); + assert_eq!(report.ran, 2); + assert_eq!(runner.ran, ["a"], "the no-op counted without running"); +} +// One budget is charged across nested plays and stops at the limit; a call back to a running +// action is refused as `Recursive`. +#[trial] +fn action_player_charges_a_shared_budget_and_detects_loops() { + struct Nested<'a>(&'a ActionList, Vec); + impl ActionRunner for Nested<'_> { + fn run_step(&mut self, _: &Action, _: usize, step: &ActionStep, _: bool, budget: &mut PlaybackBudget) -> StepOutcome { + if let Some(callee) = step.command.strip_prefix("play:") { + let index = self.0.actions().iter().position(|a| a.name == callee).unwrap(); + let report = ActionPlayer::play(self.0, index, 0, self, budget); + self.1.extend(report.refused); + } + StepOutcome::Done(Value::Null) + } + } + let list = list_of(vec![action("A", &["x", "play:B", "y"]), action("B", &["z", "play:A"])]); + let mut runner = Nested(&list, Vec::new()); + let mut budget = PlaybackBudget::new(); + let report = ActionPlayer::play(&list, 0, 0, &mut runner, &mut budget); + assert_eq!(report.ran, 3); + assert_eq!(runner.1, [PlaybackRefusal::Recursive("A".to_owned())]); + assert_eq!(budget.steps(), 5); + + let mut small = PlaybackBudget { limit: 2, ..PlaybackBudget::new() }; + let report = ActionPlayer::play(&list, 0, 0, &mut Script::default(), &mut small); + assert_eq!(report.ran, 2); + assert_eq!(report.refused, Some(PlaybackRefusal::StepLimit)); + assert_eq!(report.failed.map(|f| f.step), Some(2)); + + let mut deep = PlaybackBudget::new(); + for n in 0..MAX_PLAYBACK_DEPTH { + deep.enter(&n.to_string()).unwrap(); + } + assert_eq!(deep.enter("more"), Err(PlaybackRefusal::TooDeep)); +} + +// A set keeps its place as it gets its first action and loses its last; a duplicate goes right after its source; +// rename keeps the place and moves the members and refuses empty, taken and unknown names; delete returns the members +// in list order. +#[trial] +fn sets_keep_their_place_as_they_fill_empty_rename_and_go() { + let mut list = ActionList::new(); + for set in ["A", "B", "C"] { + list.new_set(set).unwrap(); + } + list.new_action("x", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it gets its first action"); + list.delete_action(0).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it loses its last"); + + assert_eq!(list.duplicate_set("A", |_, _, _| {}).unwrap(), "A copy"); + list.new_action("y", Some("B".into())).unwrap(); + assert_eq!(list.duplicate_set("B", |_, _, _| {}).unwrap(), "B copy"); + list.new_action("z", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "B", "B copy", "C"], "a copy follows its source, with or without actions"); + + let revision = list.revision(); + list.rename_set("B", "B").unwrap(); + assert_eq!(list.revision(), revision, "the same name changes nothing"); + assert_eq!(list.rename_set("B", " "), Err(ActionListError::EmptyName)); + assert_eq!(list.rename_set("B", "C"), Err(ActionListError::NameTaken("C".into()))); + assert_eq!(list.rename_set("Nope", "Z"), Err(ActionListError::NoSuchSet("Nope".into()))); + assert_eq!(list.revision(), revision, "a refused rename changes nothing"); + list.rename_set("B", " Beta ").unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "Beta", "B copy", "C"]); + let members = list.actions().iter().filter(|action| action.set.as_deref() == Some("Beta")).count(); + assert_eq!(members, 2, "the members follow the rename"); + + let gone = list.delete_set("Beta").unwrap(); + assert_eq!(gone.iter().map(|action| action.name.as_str()).collect::>(), ["y", "z"]); + assert_eq!(list.sets(), ["A", "A copy", "B copy", "C"]); + assert_eq!(list.actions().len(), 1); + assert_eq!(list.delete_set("Beta"), Err(ActionListError::NoSuchSet("Beta".into()))); +} + +// An option of an action stays with it through a duplicate, a set duplicate, a step move, the file and a merge. +#[trial] +fn app_options_ride_with_an_action_through_edits_and_files() { + let mut base = action("A", &["a", "b"]); + base.set = Some("S".into()); + base.options.insert("key".into(), json!(3)); + let mut list = list_of(vec![base]); + list.duplicate_action(0, |_, _, _| {}).unwrap(); + list.duplicate_set("S", |_, _, _| {}).unwrap(); + list.move_step(0, 0, 0, 1).unwrap(); + assert_eq!(list.actions().len(), 4); + assert!(list.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + + let text = list.to_file().to_json().unwrap(); + assert!(text.contains("\"options\"")); + let loaded = ActionList::from_file(ActionsFile::from_json(&text).unwrap()); + assert!(loaded.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + let mut merged = ActionList::new(); + merged.merge_file(ActionsFile::from_json(&text).unwrap(), false, |_, _| {}); + assert!(merged.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); +} + +// An action's options are set in the list, kept through a duplicate and the file, and the same options or an unknown +// action change nothing. +#[trial] +fn an_actions_options_are_set_and_kept_through_a_duplicate_and_the_file() { + let mut list = list_of(vec![action("a", &["one"])]); + let options = json!({"key": "F5", "automaticAlignTo": "artboard"}).as_object().cloned().unwrap(); + list.set_options(0, options.clone()).unwrap(); + assert_eq!(list.action(0).unwrap().options, options); + let revision = list.revision(); + list.set_options(0, options.clone()).unwrap(); + assert_eq!(list.revision(), revision, "the options it holds change nothing"); + assert_eq!(list.set_options(7, serde_json::Map::new()), Err(ActionListError::NoSuchAction(7))); + let copy = list.duplicate_action(0, |_, _, _| {}).unwrap(); + assert_eq!(list.action(copy).unwrap().options, options, "a duplicate keeps them"); + assert_eq!(ActionList::from_file(list.to_file()).action(0).unwrap().options, options, "the file keeps them"); +} diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs new file mode 100644 index 0000000000..6296beea76 --- /dev/null +++ b/crates/automation/src/agents/link.rs @@ -0,0 +1,252 @@ +//! The link host: the control server an app runs for agents while its settings let them in. + +use std::fmt; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::Receiver; +use std::time::{Duration, Instant}; + +use craft_ui::runtime::motion; +use craft_ui::runtime::windows::WindowHost; +use egui::ViewportId; +use serde::{Serialize, Serializer}; + +use super::{AgentSettings, Connection, TOKEN_FILE, remove_connection, write_connection}; +use crate::control::ControlRequest; +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. +pub const RETRY: Duration = Duration::from_secs(5); + +/// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence +/// for logs and `ui.inspect`; the Agents page shows its own words. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum LinkProblem { + /// Allow Agent Control is off. + NotAllowed, + /// The app has no settings folder (no home folder). + NoSettingsFolder, + /// The token file could not be read or written. + TokenFile(String), + /// The control server could not listen on `port`. + Listen { + /// The port asked for (0 is any). + port: u16, + /// Why. + error: String, + }, + /// The control port setting is outside 0..=65535; nothing listens. + PortOutOfRange(u32), + /// The connection file could not be written; nothing listens without it. + Publish(String), + /// The app's own note ([`AgentLink::note`]), such as a folder it could not use. + App(String), +} + +impl fmt::Display for LinkProblem { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotAllowed => f.write_str("Agents can't connect: Allow Agent Control is off in the preferences file."), + Self::NoSettingsFolder => f.write_str("Agents can't connect: the app has no settings folder (no home folder)."), + Self::TokenFile(e) => write!(f, "Agents can't connect: the token file could not be written: {e}"), + Self::Listen { port, error } => write!(f, "Couldn't listen on 127.0.0.1:{port}: {error}"), + Self::PortOutOfRange(port) => write!(f, "Agents can't connect: the control port {port} is outside 0 to 65535."), + Self::Publish(e) => write!(f, "Couldn't publish the agent connection: {e}"), + Self::App(note) => f.write_str(note), + } + } +} + +/// Where the link stands, for the Agents page and `ui.inspect`. Serialised as +/// `{"port", "launchFlags", "error"}`, `error` being the problem's `Display` text. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct AgentLinkStatus { + /// The port agents can connect on while the server runs. + pub port: Option, + /// The launch options (`--control`) manage the connection; the settings don't. + pub launch_flags: bool, + /// Why agents can't connect, or what could not be applied. + #[serde(rename = "error", serialize_with = "problem_text")] + pub problem: Option, +} + +fn problem_text(problem: &Option, s: S) -> Result { + match problem { + Some(p) => s.collect_str(p), + None => s.serialize_none(), + } +} + +/// What one [`AgentLink::sync`] did, for the app to follow. +#[derive(Debug, Default)] +#[non_exhaustive] +pub struct LinkUpdate { + /// A server started: its requests arrive here. The app drains it as its control channel. + pub requests: Option>, + /// The server that ran stopped: the app drops its control channel. + pub stopped: bool, + /// The settings applied or the link's state changed: the app rebuilds what agents may read and + /// write (its policy, its folders) from [`AgentLink::status`] and the settings. + pub changed: bool, +} + +/// The server while it runs; dropping it stops the server and removes the connection file. +struct Running { + server: Listening, + dir: PathBuf, + /// The `controlPort` setting it was started for (0 is any). + port_pref: u32, +} + +impl Drop for Running { + fn drop(&mut self) { + remove_connection(&self.dir, std::process::id()); + log::info!("agent connection on {} stopped", self.server.addr); + } +} + +/// The control server an app runs for agents while its settings let them in, and the connection +/// file the app's `-cli mcp` finds it by. The token stays in the settings folder across +/// launches ([`TOKEN_FILE`]). Dropping the link stops the server and removes the connection file +/// if this process wrote it. +pub struct AgentLink { + dir: Option, + app: String, + running: Option, + /// The server the launch options started; while it is there, the settings change nothing. + launch: Option, + /// The settings of the last sync that ran, once one ran. + applied: Option>, + retry_at: Option, + retry: Duration, + status: AgentLinkStatus, +} + +impl fmt::Debug for AgentLink { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AgentLink").field("dir", &self.dir).field("status", &self.status).finish_non_exhaustive() + } +} + +impl AgentLink { + /// A link that keeps its token and connection file in `settings_dir` and names `app` (the + /// app's version string) in the connection file. Nothing runs until [`Self::sync`]. + pub fn new(settings_dir: Option, app: impl Into) -> Self { + Self { + dir: settings_dir, + app: app.into(), + running: None, + launch: None, + applied: None, + retry_at: None, + retry: RETRY, + status: AgentLinkStatus::default(), + } + } + + /// The server `--control` started: the status names its port and the launch options, and + /// [`Self::sync`] changes nothing. + pub fn from_launch(server: Listening) -> Self { + let mut link = Self::new(None, String::new()); + link.status = AgentLinkStatus { port: Some(server.addr.port()), launch_flags: true, problem: None }; + link.launch = Some(server); + link + } + + /// [`RETRY`] replaced by `delay`, so a test retries at once. + #[doc(hidden)] + pub fn retry_after(mut self, delay: Duration) -> Self { + self.retry = delay; + self + } + + /// 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. + pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { + let mut update = LinkUpdate::default(); + if self.launch.is_some() { + return update; + } + 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 { + return update; + } + let before = (self.status.clone(), self.applied.clone().flatten()); + self.applied = Some(want.cloned()); + self.retry_at = None; + self.status.problem = None; + if let Err(problem) = self.apply(want, host, &mut update) { + self.status.problem = Some(problem); + } + self.status.port = self.running.as_ref().map(|r| r.server.addr.port()); + update.changed = self.status != before.0 || want != before.1.as_ref(); + update + } + + fn apply(&mut self, want: Option<&AgentSettings>, host: &WindowHost, update: &mut LinkUpdate) -> Result<(), LinkProblem> { + let Some(want) = want else { + update.stopped = self.running.take().is_some(); + return Ok(()); + }; + // Allow Agent Control off refuses every control server, this one as `--control`. + if !want.allow_agent_control { + update.stopped = self.running.take().is_some(); + return Err(LinkProblem::NotAllowed); + } + let Some(dir) = self.dir.clone() else { + update.stopped = self.running.take().is_some(); + return Err(LinkProblem::NoSettingsFolder); + }; + if self.running.as_ref().is_some_and(|r| r.port_pref == want.control_port) { + return Ok(()); + } + update.stopped = self.running.take().is_some(); + // A setting outside 0..=65535 names no port; a retry would not change that, so none is scheduled. + let Ok(port) = u16::try_from(want.control_port) else { + return Err(LinkProblem::PortOutOfRange(want.control_port)); + }; + match self.start(&dir, port, want.control_port, host) { + Ok((running, requests)) => { + log::info!("agents can connect on {}", running.server.addr); + self.running = Some(running); + update.requests = Some(requests); + Ok(()) + } + Err(problem) => { + log::warn!("{problem}"); + self.retry_at = Some(motion::now() + self.retry); + host.repaint_in(ViewportId::ROOT, self.retry.as_secs_f64()); + Err(problem) + } + } + } + + /// 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> { + 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 (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()))?; + Ok((running, requests)) + } + + /// Where the link stands. + pub fn status(&self) -> &AgentLinkStatus { + &self.status + } + + /// The app reports what it could not apply (a folder it could not use); shown until the next + /// change. + pub fn note(&mut self, problem: LinkProblem) { + self.status.problem = Some(problem); + } +} diff --git a/crates/automation/src/agents/mod.rs b/crates/automation/src/agents/mod.rs new file mode 100644 index 0000000000..0ff21d3a80 --- /dev/null +++ b/crates/automation/src/agents/mod.rs @@ -0,0 +1,49 @@ +//! AI agents in the open window: whether the person lets agents use the app, and how an agent's +//! client finds the app's control server without being told. +//! +//! One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents +//! use Craft apps*, which writes the launcher's app list (`craft_ai_agents`). With the suite's +//! `AI-MCP` flag on, an app lets agents in when that list names it ([`AgentSwitch`]); without the +//! flag, the app's own earlier consent decides ([`agents_allowed`]). +//! +//! While agents may connect, the app serves its control channel on loopback ([`AgentLink`], over +//! [`crate::server`]) and publishes where in its settings folder ([`CONNECTION_FILE`]): the port, +//! its process id and the token file ([`TOKEN_FILE`], created `0600` on Unix). The app's +//! `-cli mcp` reads that file on every tool call ([`Live`]), then the token from the file it +//! names, so an MCP client's configuration never holds a port or a token. +//! +//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch removes it +//! ([`remove_stale_connection`]). Until then another program could take that port, so a client +//! checks that [`Connection::pid`] is still running before it sends anything derived from the +//! token, and authenticates with the challenge handshake ([`crate::security::ServerHandshake`]). +//! +//! Everything but the link host is `craft_control::agents`, re-exported here: apps that don't use +//! the shared UI library use it from there, with the same files and formats. +//! +//! | Part | Names | Builds | +//! |---|---|---| +//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target | +//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` | +//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | +//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | +//! | The link host | [`AgentLink`], [`AgentLinkStatus`], [`LinkProblem`], [`LinkUpdate`] | desktop, features `agents` and `ui` | +//! +//! The Agents page of Preferences is [`crate::ui::agents`]. + +// The links above name items of the `agents` and `ui` features; without them they have nothing to +// point at, and the docs of the settings alone still build. +#![cfg_attr(not(all(feature = "agents", feature = "ui", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))] + +pub use craft_control::agents::{AgentSettings, WhenAppClosed, agents_allowed, folder}; + +#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))] +mod link; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use craft_control::agents::{ + AgentSwitch, CONNECTION_FILE, ConnectFn, Connection, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn, + Live, LiveConfig, POLL, PROBE_TIMEOUT, Route, TOKEN_FILE, Window, find_window, launcher, launcher_allows, mcp_flag, probe, read_connection, + remove_connection, remove_stale_connection, write_connection, +}; +#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))] +pub use link::{AgentLink, AgentLinkStatus, LinkProblem, LinkUpdate, RETRY}; diff --git a/crates/automation/src/args.rs b/crates/automation/src/args.rs new file mode 100644 index 0000000000..79ef22ac33 --- /dev/null +++ b/crates/automation/src/args.rs @@ -0,0 +1,230 @@ +//! The control channel's command-line values and their environment fallbacks. +//! +//! An app's command line has `--control `, `--control-token <64-HEX>` and +//! `--control-token-file `; each has a variable (`_CONTROL_PORT`, +//! `_CONTROL_TOKEN`, `_CONTROL_TOKEN_FILE`) that stands in for it when the flag is +//! absent. A flag wins over its variable; a blank variable counts as unset; a bad variable value (not a port, or not Unicode) +//! is a usage error that names the variable, never the token's value. Parsing the command line +//! itself (clap in PhotoCraft) stays in the app: this module checks the values and reports them +//! in the apps' wording, so the exit code is 2 and the message is the one the apps' integration +//! tests look for. +//! +//! What the user sees: `photocraft --control 0 --control-token abcd --control-token-file t` +//! prints `error: the argument '--control-token' cannot be used with '--control-token-file'` +//! and exits 2; with the token from `PHOTOCRAFT_CONTROL_TOKEN` the message names the variable +//! instead of the flag. + +use std::path::PathBuf; + +use crate::security::AutomationError; + +/// The exit status of a bad control configuration (usage errors, clap's convention). +pub const USAGE_EXIT_CODE: i32 = 2; + +/// The environment variable names an app reads for its control flags: `_CONTROL_PORT`, +/// `_CONTROL_TOKEN`, `_CONTROL_TOKEN_FILE`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EnvNames { + /// Variable name for the control port. + pub port: String, + /// Variable name for the control token. + pub token: String, + /// Variable name for the file that holds the control token. + pub token_file: String, +} + +impl EnvNames { + /// Names with `prefix` (`"PHOTOCRAFT"` gives `PHOTOCRAFT_CONTROL_PORT` and friends). + pub fn for_app(prefix: &str) -> Self { + Self { port: format!("{prefix}_CONTROL_PORT"), token: format!("{prefix}_CONTROL_TOKEN"), token_file: format!("{prefix}_CONTROL_TOKEN_FILE") } + } +} + +/// Where a control value came from, for error messages: the flag's own spelling, or the variable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Source { + /// The command-line flag. + Flag, + /// The environment variable. + Env, +} + +/// The control values after the command line and the environment were read. +/// +/// `port` on means the control server starts; `None` means no `--control` and no port variable. +/// The pair `token` / `token_file` is either-or (checked by [`Self::check`]); neither set means +/// a token is generated and printed to stderr at start. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ControlOptions { + /// The port to listen on (`0` picks a free one); `None` leaves the control server off. + pub port: Option, + /// The token given inline. + pub token: Option, + /// The file to read the token from. + pub token_file: Option, + /// Where each set value came from, so an error names the flag or the variable. + pub sources: Sources, +} + +/// The [`Source`] of each set field of [`ControlOptions`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Sources { + /// Where `port` came from. + pub port: Option, + /// Where `token` came from. + pub token: Option, + /// Where `token_file` came from. + pub token_file: Option, +} + +/// A bad control configuration, worded like clap's usage errors; printed by the app with its +/// `error: ` prefix and a pointer at `--help`, then exit [`USAGE_EXIT_CODE`]. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum OptionsError { + /// `invalid value 'nope' for 'PHOTOCRAFT_CONTROL_PORT'` (or `'--control '`). + #[error("invalid value '{value}' for '{shown}': expected a port, 0-65535")] + NotAPort { + /// The value as given. + value: String, + /// The flag or variable name, as the user wrote it. + shown: String, + }, + /// `the argument '--control-token' cannot be used with 'PHOTOCRAFT_CONTROL_TOKEN_FILE'`. + /// Never contains the token. + #[error("the argument '{a}' cannot be used with '{b}'")] + Conflict { + /// The first of the two, as shown. + a: String, + /// The second of the two, as shown. + b: String, + }, + /// `invalid UTF-8 was detected in 'PHOTOCRAFT_CONTROL_TOKEN'`: a variable that is set but is + /// not Unicode. The token file's path is the exception: any path is accepted. + #[error("invalid UTF-8 was detected in '{shown}'")] + NotUnicode { + /// The variable name. + shown: String, + }, +} + +impl ControlOptions { + /// The values from the environment alone: a blank variable is unset; a bad port is + /// [`OptionsError::NotAPort`] and a non-Unicode port or token is [`OptionsError::NotUnicode`], + /// each naming the variable. The token file's path may be any OS string. + pub fn from_env(names: &EnvNames) -> Result { + Self::from_lookup(names, |name| std::env::var_os(name)) + } + + /// [`Self::from_env`] over any variable source, so tests need not touch the process + /// environment. + fn from_lookup(names: &EnvNames, get: impl Fn(&str) -> Option) -> Result { + let read = |name: &str| get(name).filter(|v| !v.to_str().is_some_and(|v| v.trim().is_empty())); + let text = |name: &String| match read(name) { + Some(value) => value.into_string().map(Some).map_err(|_| OptionsError::NotUnicode { shown: name.clone() }), + None => Ok(None), + }; + let port = match text(&names.port)? { + Some(value) => Some(control_port(&value).map_err(|_| OptionsError::NotAPort { value, shown: names.port.clone() })?), + None => None, + }; + let token = text(&names.token)?; + let token_file = read(&names.token_file).map(PathBuf::from); + let from_env = Some(Source::Env); + Ok(Self { + sources: Sources { port: port.and(from_env), token: token.as_ref().and(from_env), token_file: token_file.as_ref().and(from_env) }, + port, + token, + token_file, + }) + } + + /// `flags` over the environment: each variable is looked up only when its flag is absent, so + /// a bad exported value does not stop a launch whose flag overrides it (clap's behaviour). + pub fn resolve(flags: Self, names: &EnvNames) -> Result { + Self::resolve_with(flags, names, |name| std::env::var_os(name)) + } + + fn resolve_with(flags: Self, names: &EnvNames, get: impl Fn(&str) -> Option) -> Result { + let skipped = [(flags.port.is_some(), &names.port), (flags.token.is_some(), &names.token), (flags.token_file.is_some(), &names.token_file)]; + let env = Self::from_lookup(names, |name| if skipped.iter().any(|(given, var)| *given && var.as_str() == name) { None } else { get(name) })?; + Ok(Self::merged(flags, env)) + } + + /// `flags` (what the command line gave, each with `Source::Flag`) over `env`: a flag wins + /// over its variable, field by field. Prefer [`Self::resolve`], which also skips the lookup. + pub fn merged(flags: Self, env: Self) -> Self { + fn pick(flag: Option, flag_source: Option, env: Option, env_source: Option) -> (Option, Option) { + if flag.is_some() { (flag, flag_source) } else { (env, env_source) } + } + let (port, port_source) = pick(flags.port, flags.sources.port, env.port, env.sources.port); + let (token, token_source) = pick(flags.token, flags.sources.token, env.token, env.sources.token); + let (token_file, token_file_source) = pick(flags.token_file, flags.sources.token_file, env.token_file, env.sources.token_file); + Self { port, token, token_file, sources: Sources { port: port_source, token: token_source, token_file: token_file_source } } + } + + /// Rejects `token` together with `token_file` ([`OptionsError::Conflict`], naming the flag or + /// variable each came from). Only checked when `port` is set: without `--control` the token + /// pair is ignored, as in PhotoCraft. + pub fn check(&self, flags: &FlagNames, names: &EnvNames) -> Result<(), OptionsError> { + if self.port.is_none() || self.token.is_none() || self.token_file.is_none() { + return Ok(()); + } + let shown = |source: Option, flag: &str, var: &str| match source { + Some(Source::Env) => var.to_owned(), + _ => flag.to_owned(), + }; + Err(OptionsError::Conflict { + a: shown(self.sources.token, &flags.token, &names.token), + b: shown(self.sources.token_file, &flags.token_file, &names.token_file), + }) + } + + /// The server token: the supplied one (validated), the file's content, or a fresh one. + /// `Err` is "cannot configure control authentication", exit 2. + pub fn server_token(&self) -> Result { + crate::security::server_token(self.token.as_deref(), self.token_file.as_deref()) + } + + /// The line the app prints to stderr about the token, without the app's name prefix or a + /// trailing newline: `control token file: `, `control token: ` for a generated + /// one, `using supplied control token` otherwise. The token is printed only when the app + /// generated it. + pub fn token_notice(&self, token: &str) -> String { + if let Some(path) = &self.token_file { + format!("control token file: {}", path.display()) + } else if self.token.is_none() { + format!("control token: {token}") + } else { + "using supplied control token".to_owned() + } + } +} + +/// The flags' spellings in usage errors (`--control `, `--control-token`, +/// `--control-token-file`), so an app with other names reports its own. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FlagNames { + /// Spelling of the port flag. + pub port: String, + /// Spelling of the token flag. + pub token: String, + /// Spelling of the token-file flag. + pub token_file: String, +} + +impl Default for FlagNames { + /// PhotoCraft's spellings: `--control`, `--control-token`, `--control-token-file`. + fn default() -> Self { + Self { port: "--control".into(), token: "--control-token".into(), token_file: "--control-token-file".into() } + } +} + +/// `"0"`–`"65535"` with surrounding spaces to a port. +pub fn control_port(s: &str) -> Result { + s.trim().parse().map_err(|_| NotAPort) +} + +/// Not a port number. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("expected a port, 0-65535")] +pub struct NotAPort; diff --git a/crates/automation/src/client.rs b/crates/automation/src/client.rs new file mode 100644 index 0000000000..7d6ca67e72 --- /dev/null +++ b/crates/automation/src/client.rs @@ -0,0 +1,219 @@ +//! A JSON-lines client for integration tests and CLIs. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::SocketAddr; + +use serde_json::{Value, json}; + +use crate::protocol::REPLY_DEADLINE; +use crate::security::{AUTH_METHOD, IO_TIMEOUT}; + +/// How long a call waits for its reply: the server's [`REPLY_DEADLINE`] plus a margin, so the +/// server's own timeout error arrives before the client gives up. +pub const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(REPLY_DEADLINE.as_secs() + 5); + +/// How long [`ControlClient::connect`] waits for the connection: 800 ms, as the server is on loopback only. +pub const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(800); + +/// The longest reply line a client reads: 256 MiB. A longer one is an error and closes the connection. +pub const MAX_REPLY_BYTES: u64 = 256 << 20; + +/// Why [`ControlClient::connect`] failed. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ConnectError { + /// A socket or read failure: the server was not reached. + Transport(String), + /// The server answered the `auth` request with an error. + Refused(String), +} + +impl std::fmt::Display for ConnectError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConnectError::Transport(why) | ConnectError::Refused(why) => f.write_str(why), + } + } +} + +impl std::error::Error for ConnectError {} + +/// One authenticated connection. +pub struct ControlClient { + stream: std::net::TcpStream, + broken: bool, + reader: BufReader, + next_id: u64, +} + +impl ControlClient { + /// True after a transport failure closed the connection; an error reply leaves it false. A + /// caller tells a lost connection from a refused request and never replays a mutation. + pub fn is_broken(&self) -> bool { + self.broken + } + + /// Whether a call can be sent now: false when the connection is broken, the server closed it, + /// or it holds bytes no call asked for (a server that says why it closes), as no reply to the + /// next call could be read from it. Every call checks this before it sends and, when false, + /// closes the connection and fails with nothing sent; a caller reconnects instead. + pub fn is_usable(&self) -> bool { + if self.broken || !self.reader.buffer().is_empty() || self.stream.set_nonblocking(true).is_err() { + return false; + } + let probe = self.stream.peek(&mut [0]); + self.stream.set_nonblocking(false).is_ok() && probe.is_err_and(|e| e.kind() == std::io::ErrorKind::WouldBlock) + } + + /// Connect (read timeout [`CALL_TIMEOUT`]), send + /// `{"id": 1, "method": "auth", "params": {"token": token}}` and read one reply line; `Err` with + /// the reply's `error` text as `Refused` when it isn't `ok`, or the I/O error's message as `Transport`. + /// A line the server wrote before the request (a refusal at accept) is the reply, and nothing is sent. + pub fn connect(addr: SocketAddr, token: &str) -> Result { + let io = |e: std::io::Error| ConnectError::Transport(e.to_string()); + let stream = std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map_err(io)?; + Self::over(stream).map_err(io)?.sign_in(token) + } + + /// A client over a connected `stream`, not yet signed in. + fn over(stream: std::net::TcpStream) -> std::io::Result { + stream.set_read_timeout(Some(CALL_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; + let reader = BufReader::new(stream.try_clone()?); + Ok(Self { stream, broken: false, reader, next_id: 2 }) + } + + /// Sends the sign-in and reads its answer. A server that refuses the connection at once (over its connection + /// limit) writes why before any request: that line answers the sign-in, which is then not sent, so only its + /// error counts. + fn sign_in(mut self, token: &str) -> Result { + let auth = if self.is_usable() { + self.round_trip(1, AUTH_METHOD, json!({"token": token}), None) + } else { + self.read_reply(1, None).and_then(|_| Err(Failure::Io("reply before the sign-in".into()))) + }; + match auth { + Ok(_) => Ok(self), + Err(Failure::Reply(why)) => Err(ConnectError::Refused(why)), + Err(Failure::Io(why)) => { + self.close(); + Err(ConnectError::Transport(why)) + } + } + } + + /// Send `{"id": n, "method", "params"}` as one line (ids count up from 2) and read the reply + /// line with that id (replies to other ids are skipped); `Ok(result)` (`null` when absent) for + /// `"ok": true`, `Err(error)` otherwise. After an I/O error or a timeout the connection is + /// closed and every later call fails, so a late reply can't answer the wrong call. + pub fn call(&mut self, method: &str, params: Value) -> Result { + self.call_with(method, params, None) + } + + /// As [`ControlClient::call`], but gives up with `Err("cancelled")` and closes the connection when `cancelled()` + /// turns true while it waits for the reply. + pub fn call_until(&mut self, method: &str, params: Value, cancelled: &dyn Fn() -> bool) -> Result { + self.call_with(method, params, Some(cancelled)) + } + + fn call_with(&mut self, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let id = self.next_id; + self.next_id += 1; + self.exchange(id, method, params, cancelled) + } + + fn exchange(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + if !self.is_usable() { + self.close(); + return Err("connection closed".into()); + } + let result = self.round_trip(id, method, params, cancelled); + if matches!(result, Err(Failure::Io(_))) { + self.close(); + } + result.map_err(|f| match f { + Failure::Io(e) | Failure::Reply(e) => e, + }) + } + + fn close(&mut self) { + self.broken = true; + let _ = self.stream.shutdown(std::net::Shutdown::Both); + } + + fn round_trip(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let io = |e: std::io::Error| Failure::Io(e.to_string()); + writeln!(self.stream, "{}", json!({"id": id, "method": method, "params": params})).map_err(io)?; + self.stream.flush().map_err(io)?; + self.read_reply(id, cancelled) + } + + /// Reads reply lines until the one with `id`, or with a null id (the server's answer to an unparseable line or a + /// refused connection). + fn read_reply(&mut self, id: u64, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let io = |e: std::io::Error| Failure::Io(e.to_string()); + loop { + if let Some(cancelled) = cancelled { + self.wait_for_reply(cancelled)?; + } + let mut line = String::new(); + let read = (&mut self.reader).take(MAX_REPLY_BYTES + 1).read_line(&mut line).map_err(io)?; + if read == 0 { + return Err(Failure::Io("connection closed".into())); + } + if read as u64 > MAX_REPLY_BYTES { + return Err(Failure::Io(format!("reply longer than {MAX_REPLY_BYTES} bytes"))); + } + let mut reply: Value = serde_json::from_str(&line).map_err(|e| Failure::Io(format!("bad reply: {e}")))?; + // A reply to an earlier request. + if reply.get("id").is_some_and(|got| !got.is_null() && got != &json!(id)) { + continue; + } + return if reply.get("ok") == Some(&Value::Bool(true)) { + Ok(reply.get_mut("result").map(Value::take).unwrap_or(Value::Null)) + } else { + Err(Failure::Reply(reply.get("error").and_then(Value::as_str).unwrap_or("request failed").to_string())) + }; + } + } + + /// Waits until a reply line starts to arrive, asking `cancelled` between short reads, for at most + /// [`CALL_TIMEOUT`]. A cancel is a transport failure, so the connection closes and a late reply can't answer the + /// next call. + fn wait_for_reply(&self, cancelled: &dyn Fn() -> bool) -> Result<(), Failure> { + const POLL: std::time::Duration = std::time::Duration::from_millis(100); + if !self.reader.buffer().is_empty() { + return Ok(()); + } + let io = |e: std::io::Error| Failure::Io(e.to_string()); + let start = std::time::Instant::now(); + self.stream.set_read_timeout(Some(POLL)).map_err(io)?; + let outcome = loop { + match self.stream.peek(&mut [0]) { + Ok(_) => break Ok(()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + if cancelled() { + break Err(Failure::Io("cancelled".into())); + } + if start.elapsed() >= CALL_TIMEOUT { + break Err(io(e)); + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => break Err(io(e)), + } + }; + self.stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?; + outcome + } +} + +/// Why a round trip failed: the transport (the connection is then unusable) or an error reply. +enum Failure { + Io(String), + Reply(String), +} + +#[cfg(all(test, feature = "ui"))] +#[path = "client_tests.rs"] +pub(crate) mod client_tests; diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs new file mode 100644 index 0000000000..46687dae3b --- /dev/null +++ b/crates/automation/src/client_tests.rs @@ -0,0 +1,138 @@ +//! Behaviour tests of `client`. +// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use craft_ui::testing::trial; +use serde_json::json; + +#[allow(clippy::wildcard_imports, reason = "tests use most of the module under test and its helpers")] +use super::*; + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// Writes `reply` and its newline in one write. `writeln!` on a bare stream writes in pieces, so the client can see +/// part of a line and close the connection before the rest is sent. +fn say(out: &mut impl std::io::Write, reply: serde_json::Value) -> std::io::Result<()> { + out.write_all(format!("{reply}\n").as_bytes()) +} + +// call returns Ok(result) for ok replies and Err(error) otherwise. + +// A stale reply left by a timed-out call is skipped, and a transport failure closes the client. +#[trial] +fn replies_are_matched_by_id() { + use std::io::BufRead; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + say(&mut out, json!({"id": 99, "ok": true, "result": "stale"})).unwrap(); + say(&mut out, json!({"id": 2, "ok": true, "result": "fresh"})).unwrap(); + // Closing the connection ends the third call. + }); + let mut client = ControlClient::connect(addr, TOKEN).unwrap(); + assert_eq!(client.call("a", json!({})), Ok(json!("fresh"))); + server.join().unwrap(); + assert!(client.call("b", json!({})).is_err(), "the closed connection fails the call"); + assert_eq!(client.call("c", json!({})), Err("connection closed".to_string()), "a failed client stays closed"); +} + +// A cancelled wait gives up on a reply that never comes and closes the connection, so a late reply can't answer a +// later call. +#[trial] +fn a_cancelled_call_stops_waiting_and_closes_the_connection() { + use std::io::BufRead; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (done, wait) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); + // The call is read and never answered while the client waits. + line.clear(); + reader.read_line(&mut line).unwrap(); + wait.recv().unwrap(); + say(&mut out, json!({"id": 2, "ok": true, "result": "late"})).ok(); + }); + let mut client = ControlClient::connect(addr, TOKEN).unwrap(); + let asked = std::cell::Cell::new(0); + let cancelled = || { + asked.set(asked.get() + 1); + asked.get() > 1 + }; + assert_eq!(client.call_until("slow", json!({}), &cancelled), Err("cancelled".to_string())); + assert!(client.is_broken(), "a cancelled call closes the connection"); + done.send(()).unwrap(); + server.join().unwrap(); + assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()), "the late reply answers nothing"); +} + +// A connection the server closed, or one holding a line no call asked for, is unusable: the next +// call sends nothing and fails, so the caller reconnects instead of reading the wrong answer. +#[trial] +fn an_unasked_line_makes_the_connection_unusable_before_sending() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (said, wait) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); + wait.recv().unwrap(); + say(&mut out, json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap(); + out.flush().unwrap(); + // The client's close shows as an end of input or, with the unread line, a reset. + line.clear(); + reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) + }); + let mut client = ControlClient::connect(addr, TOKEN).unwrap(); + assert!(client.is_usable(), "an idle connection with nothing pending is usable"); + said.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while client.is_usable() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!client.is_usable(), "the unasked line makes the connection unusable"); + assert_eq!(client.call("next", json!({})), Err("connection closed".to_string())); + assert!(client.is_broken(), "the unusable connection is closed"); + assert_eq!(server.join().unwrap(), None, "the call sent nothing"); +} + +// A server that refuses a connection at accept writes why and closes: the sign-in reads that waiting line as its +// answer, so the caller learns the reason, and sends nothing. +#[trial] +fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + say(&mut out, json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); + out.flush().unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) + }); + let stream = std::net::TcpStream::connect(addr).unwrap(); + stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); + assert!(stream.peek(&mut [0]).unwrap() > 0, "the refusal is waiting before the sign-in"); + let signed = ControlClient::over(stream).unwrap().sign_in(TOKEN); + assert_eq!(signed.err(), Some(ConnectError::Refused("connection limit reached".into()))); + assert_eq!(server.join().unwrap(), None, "the sign-in sent nothing"); +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs new file mode 100644 index 0000000000..b1c005dadf --- /dev/null +++ b/crates/automation/src/control.rs @@ -0,0 +1,336 @@ +//! The UI-thread side of the control channel. +//! +//! A transport sends [`ControlRequest`]s; once per frame, between the input and the UI pass, the +//! app drains them through [`ControlChannel::next_request`], runs its own method table on each +//! (`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`]). +//! +//! 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 +//! no reply in time gets [`timeout_error`] (it may still apply). [`Dispatch`] settles which of the +//! two happened, once, between the UI thread and the transport. + +use std::sync::mpsc::{Receiver, Sender}; + +use craft_ui::runtime::motion; +use craft_ui::runtime::windows::WindowHost; +use serde_json::{Value, json}; +use web_time::Instant; + +use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply}; +use crate::synthetic::TARGET_CHANGED; + +/// A reply: the JSON object the transport writes as one line. +pub type ControlResponse = Value; + +/// A background job's id in `jobs.list`, `jobs.cancel` and [`Reply::AfterJob`]. +pub type JobId = u64; + +pub use crate::protocol::REPLY_DEADLINE; + +/// The error for a dispatched request with no reply in [`REPLY_DEADLINE`]: the command may still +/// run and apply, so re-sending it blindly could apply an edit twice. +pub fn timeout_error() -> String { + format!( + "timeout: no reply in {}s — the command may still be running and may still apply, or the app was not drawing frames (display asleep, window fully occluded, or a long operation blocked the frame loop)", + REPLY_DEADLINE.as_secs() + ) +} + +/// The error for a request still queued when its deadline passed: dropped before dispatch, safe to +/// re-send. Same `timeout` prefix as [`timeout_error`], which machines match on. +pub fn expired_error() -> String { + format!( + "timeout: not run — the request was still queued when its {}s deadline passed, so it was dropped before dispatch and is safe to re-send; the app was not drawing frames (display asleep, window fully occluded, or a long operation blocked the frame loop)", + REPLY_DEADLINE.as_secs() + ) +} + +/// One request from a transport, with where its reply goes. +#[non_exhaustive] +pub struct ControlRequest { + /// The method name, such as `ui.click`. + pub method: String, + /// The request parameters as JSON. + pub params: Value, + /// Where the answer goes; the transport reads the other end. + pub reply: Sender, + /// Requests still queued at this instant are rejected; dispatched work continues. + pub deadline: Option, + /// Shared with the transport, so when it stops waiting it knows whether the command ran. + pub dispatch: Dispatch, +} + +impl ControlRequest { + /// A request with no deadline and a fresh reply channel (tests, in-process clients). + pub fn new(method: impl Into, params: Value) -> (Self, Receiver) { + let (tx, rx) = std::sync::mpsc::channel(); + (Self { method: method.into(), params, reply: tx, deadline: None, dispatch: Dispatch::default() }, rx) + } + + /// `self` with its deadline [`REPLY_DEADLINE`] from now. + pub fn with_deadline(mut self) -> Self { + self.deadline = Some(motion::now() + REPLY_DEADLINE); + self + } +} + +/// Whether a request was dispatched, settled once between the UI thread (about to run it) and the +/// transport (giving up on its reply). +#[derive(Clone, Debug, Default)] +pub struct Dispatch(std::sync::Arc); + +const QUEUED: u8 = 0; +const DISPATCHED: u8 = 1; +const ABANDONED: u8 = 2; + +impl Dispatch { + /// Moves a queued request to `to`; returns the state it ends in. + fn settle(&self, to: u8) -> u8 { + use std::sync::atomic::Ordering; + self.0.compare_exchange(QUEUED, to, Ordering::AcqRel, Ordering::Acquire).map_or_else(|state| state, |_| to) + } + + /// The UI thread claims the request to run it: false once the transport gave up on it. + pub fn start(&self) -> bool { + self.settle(DISPATCHED) == DISPATCHED + } + + /// The transport stops waiting: [`expired_error`] when the command can no longer run, + /// [`timeout_error`] when it was dispatched and may still apply. + pub fn give_up(&self) -> String { + if self.settle(ABANDONED) == DISPATCHED { timeout_error() } else { expired_error() } + } +} + +/// What the app's method table answers for one request. +#[non_exhaustive] +pub enum Reply { + /// Reply with this JSON now. + Done(Value), + /// A `ui.screenshot`: admit `token` to the queue; `path` is where the app's write authority + /// puts the PNG, `None` inlines it as base64 in the reply; `region` is refused at admission + /// when it lies outside the window. + #[non_exhaustive] + Screenshot { + /// Identifies the capture; must differ from every pending token. + token: u64, + /// File to write the PNG to, or `None` to inline it. + path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + region: Option, + /// The viewport to capture. + viewport: egui::ViewportId, + }, + /// Synthetic input was queued: reply once the app has processed all of it. + AfterInput, + /// A command started a background job and the caller waits: reply with its result when it + /// has been applied, or with its error or `cancelled`. + AfterJob(JobId), + /// A `ui.accessTree`: hold the reply until the window's settled access tree can be read + /// ([`ControlChannel::poll_access_trees`]). + AccessTree, +} + +impl Reply { + /// A `ui.accessTree` reply: held until the window's settled access tree is available. + pub fn access_tree() -> Reply { + Reply::AccessTree + } + + /// A `ui.screenshot` reply for `token` of `viewport` with what [`ScreenshotParams::from_params`] read: the PNG + /// goes to `params.path` or is inlined when `None`, and shows `params.region` or the whole window. + pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self { + Self::Screenshot { token, path: params.path, region: params.region, viewport } + } + + /// `Done` with the [`result_reply`] of a method's result. + pub fn from_result(r: Result) -> Self { + Self::Done(result_reply(r)) + } +} + +/// The reply for a method's result: `{"ok": true, "result": value}` for `Ok(value)`, +/// `{"ok": false, "error": e}` for `Err(e)`. +pub fn result_reply(r: Result) -> ControlResponse { + match r { + Ok(result) => json!({"ok": true, "result": result}), + Err(e) => json!({"ok": false, "error": e}), + } +} + +/// The requests waiting for the app, and the replies waiting on input, jobs and screenshots. +/// +/// Per frame: `while let Some(req) = channel.next_request() { let outcome = app.handle(&req); channel.settle(ctx, req, outcome, document); }` +/// in the logic phase; [`Self::input_processed`] after the pass that consumed the injected +/// input; [`Self::job_finished`] when a job ends; [`Self::captures`] driven by the app's UI and +/// logic phases as `screenshot` documents. +#[non_exhaustive] +pub struct ControlChannel { + rx: Receiver, + input_waiters: Vec>, + job_waiters: Vec<(JobId, Sender)>, + tree_waiters: Vec>, + /// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases. + pub captures: Captures, +} + +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() } + } + + /// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned + /// requests are replied with [`expired_error`] here and skipped. `None` when the queue is + /// empty this frame. + pub fn next_request(&mut self) -> Option { + while let Ok(req) = self.rx.try_recv() { + if req.deadline.is_some_and(|deadline| motion::now() >= deadline) || !req.dispatch.start() { + let _ = req.reply.send(json!({"ok": false, "error": expired_error()})); + continue; + } + return Some(req); + } + None + } + + /// 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. + pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64) { + let reply = req.reply; + match outcome { + Reply::Done(v) => { + let _ = reply.send(v); + } + Reply::AfterInput => self.input_waiters.push(reply), + Reply::AfterJob(job) => self.job_waiters.push((job, reply)), + Reply::AccessTree => self.tree_waiters.push(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()) { + let _ = reply.send(json!({"ok": false, "error": e})); + } + } + } + } + + /// The pass that consumed the injected input ended: reply + /// `{"ok": true, "result": null}` to every [`Reply::AfterInput`] waiter. Call it only after a + /// pass that reached the end of the UI with the injected queue empty; an early-returning pass + /// keeps the waiters. + pub fn input_processed(&mut self) { + for waiter in self.input_waiters.drain(..) { + let _ = waiter.send(json!({"ok": true, "result": null})); + } + } + + /// The injected input was dropped (the window lost it, a modal took over): reply + /// `{"ok": false, "error": "input cancelled: {reason}"}` to every [`Reply::AfterInput`] + /// waiter. + pub fn input_cancelled(&mut self, reason: &str) { + for waiter in self.input_waiters.drain(..) { + let _ = waiter.send(json!({"ok": false, "error": format!("input cancelled: {reason}")})); + } + } + + /// Answers the [`Reply::AfterInput`] waiters from the window host's input state: with + /// `input cancelled` when the host withdrew queued input ([`TARGET_CHANGED`]), with success + /// once nothing is queued or in flight. Call it once per pass, at the end of the pass (after its + /// UI ran): the step that pass consumed counts as run, so the reply goes out with that pass + /// ([`WindowHost::injected_idle_at_pass_end`]). Called between passes, it waits for the pass. It also has the host + /// keep its access trees, which `control` targets and `ui.find` read. + pub fn poll_input(&mut self, host: &WindowHost) { + host.keep_access_trees(); + if host.take_injected_withdrawn() { + self.input_cancelled(TARGET_CHANGED); + } else if host.injected_idle_at_pass_end() { + self.input_processed(); + } + } + + /// Answers the held `ui.accessTree` requests from the window host's settled access tree; a + /// request stays held while the host has none. Runs in the logic phase of every pass, as + /// [`poll_input`](Self::poll_input) does. + pub fn poll_access_trees(&mut self, ctx: &egui::Context) { + if self.tree_waiters.is_empty() { + return; + } + // `ui.accessTree` takes no window: it reads the main window's tree. + let Some(tree) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return }; + let update = tree.update(); + let nodes: Vec = update + .nodes + .iter() + .map(|(id, node)| { + let children: Vec = node.children().iter().map(|child| child.0).collect(); + let mut entry = json!({"id": id.0, "role": format!("{:?}", node.role()), "children": children}); + if let Some(name) = node.label() { + entry["name"] = json!(name); + } + if let Some(value) = node.value() { + entry["value"] = json!(value); + } + if let Some(selection) = node.text_selection() { + entry["textSelection"] = json!({ + "anchor": {"node": selection.anchor.node.0, "character": selection.anchor.character_index}, + "focus": {"node": selection.focus.node.0, "character": selection.focus.character_index}, + }); + } + entry + }) + .collect(); + let root = update.tree.as_ref().map(|tree| tree.root.0); + let reply = json!({"ok": true, "result": {"nodes": nodes, "focus": update.focus.0, "root": root}}); + for waiter in self.tree_waiters.drain(..) { + let _ = waiter.send(reply.clone()); + } + } + + /// 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. + pub fn cancel_input(&mut self, host: &WindowHost, reason: &str) -> bool { + let pending = host.cancel_injected() || !self.input_waiters.is_empty(); + self.input_cancelled(reason); + pending + } + + /// Job `job` ended: send `reply` to its waiters. It is the reply the command would have given + /// had it run in place, usually [`result_reply`] of the job's result (a cancelled job's error + /// is `cancelled`); a job that ends with an error and partial results carries both. + pub fn job_finished(&mut self, job: JobId, reply: &ControlResponse) { + self.job_waiters.retain(|(waiting, tx)| { + if *waiting == job { + let _ = tx.send(reply.clone()); + false + } else { + true + } + }); + } + + /// Reply to finished screenshots with [`crate::screenshot::screenshot_reply`] (a capture + /// error `e` as `{"ok": false, "error": e}`); `write` is the app's file authority for replies + /// with a `path`. + pub fn finish_captures(&mut self, finished: Vec, write: &mut crate::screenshot::PngWriter<'_>) { + for f in finished { + let reply = match f.result { + Ok(image) => screenshot_reply(f.token, image, f.region, f.geometry, f.path.as_deref(), write), + Err(e) => json!({"ok": false, "error": e}), + }; + if let Some(tx) = f.reply { + let _ = tx.send(reply); + } + } + } + + /// 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() + } +} diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs new file mode 100644 index 0000000000..398c917c57 --- /dev/null +++ b/crates/automation/src/dialogs.rs @@ -0,0 +1,121 @@ +//! `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 +//! [`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. + +use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt}; +use egui::Context; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// The most `fields` one `ui.dialog.set` call takes. +pub const MAX_DIALOG_FIELDS: usize = 256; + +/// The open dialogs, the top one last: `{id, parent, key, fields}`, `null` for a missing parent, key or fields. Ids +/// are 64-bit hashes, so they are listed as decimal strings, which every JSON reader keeps exact. +pub fn inspect(host: &DialogHost) -> Value { + host.open_dialogs() + .into_iter() + .map(|dialog| { + json!({ + "id": dialog.id.value().to_string(), + "parent": dialog.parent.map(|id| id.value().to_string()), + "key": dialog.key, + "fields": dialog.fields, + }) + }) + .collect() +} + +/// Runs a `ui.dialog.*` method on `host`; `None` when `method` is not one of them. +/// +/// - `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. +/// - `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> { + let fields: &[&str] = match method { + "ui.dialog.set" => &["dialog", "field", "value", "fields"], + "ui.dialog.confirm" => &["dialog", "choice"], + "ui.dialog.cancel" => &["dialog"], + _ => return None, + }; + Some(run(host, ctx, method, params, fields)) +} + +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); + let id = dialog_id(host, ¶ms)?; + match method { + "ui.dialog.set" => match params.get("fields") { + Some(list) => { + if params.get("field").is_some() || params.get("value").is_some() { + return Err("`fields` takes the place of `field` and `value`".to_owned()); + } + host.set_json_fields(ctx, id, &field_list(list)?)?; + } + None => { + let field = read.str_field("field")?.ok_or("missing `field`")?; + host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?; + } + }, + "ui.dialog.confirm" => { + if let Some(choice) = params.get("choice") { + host.set_json_field(ctx, id, "choice", choice.clone())?; + } + // A held OK is filed for the app, which answers it: OK was taken, not refused. + if !host.confirm_by_id(ctx, id) && host.held_state(id) != Some(HeldOk::Waiting) { + return Err( + "the dialog refuses OK: it is disabled, its answer has no enabled button, or the dialog has no programmatic OK".to_owned() + ); + } + } + _ => { + // A prompt's Escape is an answer the app reads with the prompt's tag, so it goes through the prompt's + // own OK path rather than the host's outside close. + let escape = host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).and_then(|prompt| { + let choice = prompt.escape_choice()?; + prompt.set_choice(choice); + Some(choice) + }); + if escape.is_none() || !host.confirm_by_id(ctx, id) { + host.cancel_by_id(ctx, id); + } + } + } + Ok(Value::Null) +} + +/// The `(field, value)` pairs of a `fields` list, checked whole before anything is set; a missing `value` is `null`. +fn field_list(list: &Value) -> Result, String> { + let items = list.as_array().ok_or("`fields` is not a list")?; + if items.len() > MAX_DIALOG_FIELDS { + return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len())); + } + items + .iter() + .map(|item| { + let field = item.get("field").and_then(Value::as_str).ok_or("an item of `fields` has no string `field`")?; + Ok((field.to_owned(), item.get("value").cloned().unwrap_or(Value::Null))) + }) + .collect() +} + +/// The open dialog `params.dialog` names: the id `inspect` lists, as a decimal string or a number, or `"top"` for the +/// top dialog of the stack. +pub fn dialog_id(host: &DialogHost, params: &Value) -> Result { + let params = Params(params); + let value = match params.0.get("dialog") { + Some(Value::String(id)) if id == "top" => return host.stack().top().ok_or_else(|| "no hosted dialog is open".to_owned()), + Some(Value::String(id)) => id.parse().map_err(|_| format!("`dialog` {id:?} is not an id `ui.inspect` lists"))?, + _ => params.uint_field("dialog")?.ok_or("missing `dialog`")?, + }; + host.stack().ids().find(|id| id.value() == value).ok_or_else(|| format!("no dialog {value}")) +} diff --git a/crates/automation/src/dock.rs b/crates/automation/src/dock.rs new file mode 100644 index 0000000000..4b8bcbcd49 --- /dev/null +++ b/crates/automation/src/dock.rs @@ -0,0 +1,47 @@ +//! `ui.dock.apply`: one dock action applied to the app's workspace, and the workspace's `ui.inspect` listing. + +use std::hash::Hash; + +use craft_behavior::dock::{Action, Workspace}; +use craft_ui::docking::PanelSpecs; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// `ui.dock.apply {action}`: deserializes one dock action and applies it to `workspace` with the permissions `specs` +/// gives, as the dock area does. It returns `Ok({applied: [...]})`, the panels the action closed, in group order; an +/// error is the dock error's text. `None` for any other method. +pub fn dock_method( + workspace: &mut Workspace

, + specs: &impl PanelSpecs

, + locked: bool, + method: &str, + params: &Value, +) -> Option> { + if method != "ui.dock.apply" { + return None; + } + Some(apply(workspace, specs, locked, params)) +} + +fn apply( + workspace: &mut Workspace

, + specs: &impl PanelSpecs

, + locked: bool, + params: &Value, +) -> Result { + let params = Params(params).only(None, &["action"])?; + let action = params.get("action").cloned().ok_or("missing `action`")?; + let action: Action

= serde_json::from_value(action).map_err(|e| format!("`action` is not a dock action: {e}"))?; + let applied = workspace.apply(action, locked, |panel| specs.permissions(panel)).map_err(|e| e.to_string())?; + let applied = serde_json::to_value(applied).map_err(|e| e.to_string())?; + Ok(json!({ "applied": applied })) +} + +/// The `dock` field of the app's one `ui.inspect`: the workspace as JSON. +pub fn inspect(workspace: &Workspace

) -> Value { + // A panel id that cannot be written lists the dock as null rather than failing the whole `ui.inspect`. + serde_json::to_value(workspace).unwrap_or(Value::Null) +} diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs new file mode 100644 index 0000000000..0d97d9d8e3 --- /dev/null +++ b/crates/automation/src/files.rs @@ -0,0 +1,50 @@ +//! `ui.pick`: answers the next file picker of a running app. + +use std::fmt::Display; +use std::path::PathBuf; + +use craft_host::{FileError, Files, Picked}; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// The fields of `ui.pick`, of which a request names exactly one. +const FIELDS: [&str; 4] = ["files", "folder", "save", "cancel"]; + +/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`, +/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`. +/// Paths are taken as given; the service settles them as it would a panel's answer. +pub fn pick_method(files: &dyn Files, method: &str, params: &Value) -> Option> { + (method == "ui.pick").then(|| pick(files, params)) +} + +fn pick(files: &dyn Files, params: &Value) -> Result { + let params = Params(params).only(None, &FIELDS)?; + let read = Params(¶ms); + let given: Vec<&str> = FIELDS.iter().copied().filter(|field| params.get(*field).is_some()).collect(); + let [field] = given.as_slice() else { return Err(refused("give exactly one field")) }; + let picked = match *field { + "files" => Picked::Paths(paths(params.get("files"))?), + "cancel" => match read.bool_field("cancel").map_err(refused)? { + Some(true) => Picked::Cancelled, + _ => return Err(refused("cancel must be true")), + }, + one => Picked::Paths(vec![PathBuf::from(read.str_field(one).map_err(refused)?.ok_or_else(|| refused(format!("missing `{one}`")))?)]), + }; + files.answer_next(picked).map_err(|e| match e { + FileError::Unsupported => "this window's file service takes no automated answers".to_owned(), + other => other.to_string(), + })?; + Ok(json!({"answered": "next"})) +} + +/// `files` as a non-empty list of paths. +fn paths(files: Option<&Value>) -> Result, String> { + let list = files.and_then(Value::as_array).filter(|list| !list.is_empty()); + let paths = list.and_then(|list| list.iter().map(|path| path.as_str().map(PathBuf::from)).collect::>>()); + paths.ok_or_else(|| refused("files must be a non-empty array of path strings")) +} + +fn refused(why: impl Display) -> String { + format!("{why}; ui.pick takes exactly one of: {}", FIELDS.join(", ")) +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs new file mode 100644 index 0000000000..97a14d3103 --- /dev/null +++ b/crates/automation/src/lib.rs @@ -0,0 +1,84 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::unreachable)] + +//! Drive a running Craft app from tests, agents and the CLI, and record and play actions. +//! +//! [`actions`] and [`ui::actions`] build on every target: the recorded-action list, its player +//! and the Actions panel; so do the agent settings in [`agents`] and, with `ui`, the control +//! channel, its screenshots, synthetic input and the access-tree lookups (a web page feeds +//! [`control::ControlChannel`] from its own request queue). The server, client, token files, +//! profiler and trace are desktop only. +//! +//! A transport thread ([`server`], or a channel in tests) turns each JSON line into a +//! [`control::ControlRequest`]; the UI thread drains them between frames through +//! [`control::ControlChannel`], runs the app's method table on each, and settles the +//! [`control::Reply`]: a reply now, a reply once injected input ([`synthetic`]) has been +//! processed, a reply once a background job ends, or a screenshot through the bounded queue +//! ([`screenshot`]). [`profiler`] and [`trace`] time frames for the channel's `perf` output. +//! +//! The crate never names a document: what `engine.execute`, `ui.inspect` or `ui.set` mean is the +//! app's, through its method table. Everything a method table does not want to own is here. +#![warn(missing_docs)] + +pub mod actions; +pub mod agents; +#[cfg(feature = "ui")] +pub mod ui; + +#[cfg(feature = "ui")] +pub mod access; +#[cfg(not(target_arch = "wasm32"))] +pub mod args; +#[cfg(feature = "ui")] +pub mod control; +#[cfg(feature = "ui")] +pub mod dialogs; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod dock; +#[cfg(feature = "ui")] +pub mod files; +#[cfg(not(target_arch = "wasm32"))] +pub mod profiler; +pub mod protocol; +#[cfg(feature = "ui")] +pub mod screenshot; +#[cfg(not(target_arch = "wasm32"))] +pub mod security; +#[cfg(feature = "ui")] +pub mod synthetic; +#[cfg(not(target_arch = "wasm32"))] +pub mod trace; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod window; + +#[cfg(not(target_arch = "wasm32"))] +pub mod client; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod server; + +#[cfg(feature = "ui")] +pub use control::{ControlChannel, ControlRequest, ControlResponse, Dispatch, Reply}; +pub use protocol::REPLY_DEADLINE; +#[cfg(feature = "ui")] +pub use screenshot::Captures; +#[cfg(not(target_arch = "wasm32"))] +pub use security::AutomationError; + +/// The trials this crate registers, for its integration binary. +#[cfg(feature = "screen-testing")] +pub mod testing { + + #[cfg(feature = "suite")] + craft_ui::registry!(); +} + +#[cfg(all(test, feature = "screen-testing"))] +extern crate self as craft_automation; +#[cfg(all(test, feature = "screen-testing"))] +#[path = "../tests/it/main.rs"] +pub(crate) mod integration; + +#[cfg(test)] +fn main() { + craft_ui::registry!(); + craft_ui::testing::run(module_path!(), env!("CARGO_PKG_NAME"), &craft_ui::testing::Registry::of(&[register])); +} diff --git a/crates/automation/src/profiler.rs b/crates/automation/src/profiler.rs new file mode 100644 index 0000000000..c9a35e8d03 --- /dev/null +++ b/crates/automation/src/profiler.rs @@ -0,0 +1,207 @@ +//! Where each frame's time goes, gathered every frame, and the slow ones kept. +//! +//! [`FrameStages`] is one frame's record; each stage has one writer (the raw input hook starts the +//! frame, the command runner adds commands, the canvas adds damage, composite and upload, the UI +//! pass closes it through [`SlowFrames::finish`]). A frame over [`SLOW_FRAME_MS`] goes into +//! [`SlowFrames`], the last [`SLOW_FRAMES`] of them, which the control channel's `perf` output +//! lists as `slowFrames`; one `info` log line per second names them. [`crate::trace`] reads the +//! same record, so an app times a frame in one place. + +use std::collections::VecDeque; + +/// At most one slow-frame log line per this many ms. +const LOG_EVERY_MS: f64 = 1000.0; + +/// A frame slower than this is kept. +pub const SLOW_FRAME_MS: f64 = 50.0; +/// Slow frames kept. +pub const SLOW_FRAMES: usize = 64; + +/// One frame's stage times in milliseconds. Field names are the `perf` output's JSON keys. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FrameStages { + /// Frame start on the app clock, ms. + pub t: f64, + /// Whole frame time; never less than the sum of its stages. + pub frame_ms: f64, + /// Time from frame start to the UI pass, minus command time. + pub input_ms: f64, + /// Time running the command named in `command`. + pub command_ms: f64, + /// The command id that ran this frame, if any. + pub command: String, + /// Time computing the changed canvas region. + pub damage_ms: f64, + /// Time compositing the canvas on the CPU. + pub composite_ms: f64, + /// Time uploading canvas pixels to a texture. + pub upload_ms: f64, + /// The GPU composite time; `None` off the GPU path. + pub gpu_ms: Option, + /// Presentation time of the previous frame, if known. + pub present_ms: Option, + /// What the canvas refreshed (`"full"`, `"rect"`, `"gpu-full"`, …; `""` none; a kind starting with `gpu` is the GPU path). + pub refresh: &'static str, + /// Pixels the canvas refreshed this frame. + pub refresh_px: u64, + /// The render path name (`"gpu"`, `"cpu"`). + pub path: &'static str, + /// Time in the UI pass. + #[serde(skip)] + pub ui_ms: f64, + /// The live gesture's own render time (a brush stroke). + #[serde(skip)] + pub gesture_ms: f64, + /// Pointer moves delivered this frame. + #[serde(skip)] + pub moves: usize, + /// eframe's CPU time for the previous frame. + #[serde(skip)] + pub cpu_prev_ms: Option, + /// The raw input hook ran for this frame. + #[serde(skip)] + started: bool, +} + +impl FrameStages { + /// Begin the frame at `now` with `moves` pointer moves. + pub fn start(&mut self, now: f64, moves: usize) { + self.t = now; + self.moves = moves; + self.started = true; + } + + /// The UI pass begins: input time is `now - t`. + pub fn ui_start(&mut self, now: f64, cpu_prev: Option) { + if !self.started { + self.start(now, 0); + } + self.input_ms = (now - self.t - self.command_ms).max(0.0); + self.cpu_prev_ms = cpu_prev.map(|s| f64::from(s) * 1000.0); + } + + /// A command `id` took `ms`. + pub fn command(&mut self, id: &str, ms: f64) { + self.command_ms += ms; + id.clone_into(&mut self.command); + } + + /// The canvas refreshed `px` pixels of `kind`. + pub fn refresh(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) { + self.composite_ms += composite_ms; + self.upload_ms += upload_ms; + self.refresh = kind; + self.refresh_px += px; + } + + /// The stages that make up `frame_ms` (`present_ms` belongs to the previous frame). + pub fn stage_ms(&self) -> f64 { + self.input_ms + self.command_ms + self.damage_ms + self.composite_ms + self.upload_ms + } + + /// The frame ends at `now`; never shorter than its stages. + fn end(&mut self, now: f64) { + if !self.started { + self.t = now; + } + self.frame_ms = (now - self.t).max(self.stage_ms()); + } + + /// One log line: `slow frame: 83.0 ms on the gpu path: input 2.0, command 60.0 (filter.blur), …`. + pub fn line(&self) -> String { + let opt = |v: Option| v.map_or("-".to_string(), |v| format!("{v:.1}")); + let command = if self.command.is_empty() { String::new() } else { format!(" ({})", self.command) }; + format!( + "slow frame: {:.1} ms on the {} path: input {:.1}, command {:.1}{command}, damage {:.1}, composite {:.1}, upload {:.1}, gpu {}, present {}; refresh {} {} px", + self.frame_ms, + self.path, + self.input_ms, + self.command_ms, + self.damage_ms, + self.composite_ms, + self.upload_ms, + opt(self.gpu_ms), + opt(self.present_ms), + if self.refresh.is_empty() { "none" } else { self.refresh }, + self.refresh_px, + ) + } +} + +/// The last [`SLOW_FRAMES`] frames over the threshold. +#[derive(Debug)] +pub struct SlowFrames { + frames: VecDeque, + threshold_ms: f64, + prev_ui_ms: Option, + logged_at: Option, + unlogged: usize, +} + +impl Default for SlowFrames { + fn default() -> Self { + Self { frames: VecDeque::with_capacity(SLOW_FRAMES), threshold_ms: SLOW_FRAME_MS, prev_ui_ms: None, logged_at: None, unlogged: 0 } + } +} + +impl SlowFrames { + /// The kept frames, oldest first. + pub fn frames(&self) -> impl DoubleEndedIterator { + self.frames.iter() + } + + /// Keep frames slower than `ms` instead of [`SLOW_FRAME_MS`]. + pub fn set_threshold_ms(&mut self, ms: f64) { + self.threshold_ms = ms; + } + + /// Close frame `s` at `now`: `gpu` says the canvas is on the GPU, `gpu_ms` is the GPU's + /// latest composite time. A slow frame is kept and logged at most once a second. + pub fn finish(&mut self, mut s: FrameStages, now: f64, gpu: bool, gpu_ms: Option) -> FrameStages { + s.end(now); + let on_gpu = if s.refresh.is_empty() { gpu } else { s.refresh.starts_with("gpu") }; + s.path = if on_gpu { "gpu" } else { "cpu" }; + s.gpu_ms = gpu_ms.filter(|_| on_gpu); + s.present_ms = s.cpu_prev_ms.zip(self.prev_ui_ms).map(|(cpu, ui)| (cpu - ui).max(0.0)); + self.prev_ui_ms = Some(s.ui_ms); + if let Some(line) = self.push(&s) { + log::info!("{line}"); + } + s + } + + /// Keep `s` if it is slow; the log line to write, if one is due. + fn push(&mut self, s: &FrameStages) -> Option { + if s.frame_ms.is_nan() || s.frame_ms <= self.threshold_ms { + return None; + } + if self.frames.len() == SLOW_FRAMES { + self.frames.pop_front(); + } + self.frames.push_back(s.clone()); + if self.logged_at.is_some_and(|at| s.t - at < LOG_EVERY_MS) { + self.unlogged += 1; + return None; + } + let mut line = s.line(); + if self.unlogged > 0 { + line.push_str(&format!(" ({} more slow frames)", self.unlogged)); + } + self.logged_at = Some(s.t); + self.unlogged = 0; + Some(line) + } +} + +impl serde::Serialize for SlowFrames { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.frames.iter()) + } +} + +/// Monotonic milliseconds since the first call in this process: `craft_platform::clock::monotonic_ms`, +/// so profiler rows, traces, screenshot deadlines and the app's own timers share one origin. +pub fn now_ms() -> f64 { + craft_platform::clock::monotonic_ms() +} diff --git a/crates/automation/src/protocol.rs b/crates/automation/src/protocol.rs new file mode 100644 index 0000000000..8cf25e09c7 --- /dev/null +++ b/crates/automation/src/protocol.rs @@ -0,0 +1,259 @@ +//! The JSON-lines wire format and the parameter validators every method uses. +//! +//! Request: `{"id": 1, "method": "ui.click", "params": {"x": 10, "y": 20}}` on one line. Reply: +//! `{"id": 1, "ok": true, "result": …}` or `{"id": 1, "ok": false, "error": "…"}` on one line, +//! at most [`MAX_RESPONSE_BYTES`]. Validators reject unknown fields, wrong types, unknown choices +//! and out-of-range numbers before a method acts, with PhotoCraft's `control/params.rs` messages +//! (``unknown button `x` (left, right, secondary, middle)``, `params.rs:187`). + +use std::io::Write; + +use std::time::Duration; + +use serde_json::{Value, json}; + +/// Longest reply, in bytes (the newline included); a longer one is replaced by an error reply. +pub const MAX_RESPONSE_BYTES: usize = 8 << 20; +/// Largest PNG a headless render may return or write: `automation PNG exceeds {MAX_PNG_BYTES} +/// bytes` otherwise (PhotoCraft `crates/automation/src/budgets.rs:15`, checked at `:42`). The +/// UI screenshot reply doesn't apply it; [`crate::screenshot::MAX_IMAGE_BYTES`] bounds that. +pub const MAX_PNG_BYTES: usize = 5 << 20; + +/// One parsed request line. +#[derive(Clone, Debug, PartialEq)] +pub struct Request { + /// The caller's id, echoed in the reply; `null` when absent. + pub id: Value, + /// The method name. + pub method: String, + /// The method parameters; `{}` when absent. + pub params: Value, +} + +impl Request { + /// Parse a line: `id` defaults to `null`, `method` to `""`, `params` to `{}`. Text that is not + /// JSON is `bad JSON: {error}`. + pub fn parse(line: &str) -> Result { + let msg: Value = serde_json::from_str(line).map_err(|e| format!("bad JSON: {e}"))?; + Ok(Self { + id: msg.get("id").cloned().unwrap_or(Value::Null), + method: msg.get("method").and_then(Value::as_str).unwrap_or("").to_owned(), + params: msg.get("params").cloned().unwrap_or_else(|| json!({})), + }) + } +} + +/// `{"id", "ok": true, "result"}`. +pub fn reply_ok(id: &Value, result: Value) -> Value { + json!({"id": id, "ok": true, "result": result}) +} + +/// `{"id", "ok": false, "error"}`. +pub fn reply_err(id: &Value, error: impl std::fmt::Display) -> Value { + json!({"id": id, "ok": false, "error": error.to_string()}) +} + +struct LimitedWriter { + bytes: Vec, + maximum: usize, +} + +impl Write for LimitedWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if buf.len() > self.maximum.saturating_sub(self.bytes.len()) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("response exceeds {} bytes", self.maximum))); + } + self.bytes.try_reserve(buf.len()).map_err(|error| std::io::Error::other(format!("response allocation failed: {error}")))?; + self.bytes.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Serialize into a bounded buffer, failing as soon as `maximum` bytes would be passed. +fn encode_with_limit(value: &Value, maximum: usize) -> std::io::Result> { + let mut writer = LimitedWriter { bytes: Vec::new(), maximum }; + serde_json::to_writer(&mut writer, value).map_err(std::io::Error::from)?; + Ok(writer.bytes) +} + +/// Write `reply` as one line, replacing a reply over [`MAX_RESPONSE_BYTES`] by an error reply with +/// the same `id` and `response exceeds {MAX_RESPONSE_BYTES} bytes; operation may have completed`. +/// The whole reply is encoded before anything is written, so no partial reply goes out. +pub fn write_reply(out: &mut impl Write, reply: &Value) -> std::io::Result<()> { + let encoded = match encode_with_limit(reply, MAX_RESPONSE_BYTES - 1) { + Ok(bytes) => bytes, + Err(_) => { + let error = json!({ + "id": reply.get("id").cloned().unwrap_or(Value::Null), + "ok": false, + "error": format!("response exceeds {MAX_RESPONSE_BYTES} bytes; operation may have completed"), + }); + // Request ids arriving over the wire fit in MAX_REQUEST_BYTES, but a caller can build a + // reply directly, so the error is bounded too. + encode_with_limit(&error, MAX_RESPONSE_BYTES - 1) + .unwrap_or_else(|_| b"{\"id\":null,\"ok\":false,\"error\":\"response budget exceeded\"}".to_vec()) + } + }; + out.write_all(&encoded)?; + out.write_all(b"\n") +} + +/// The pointer buttons a request may name. +pub const BUTTONS: [&str; 4] = ["left", "right", "secondary", "middle"]; +/// The method that reads the window's access tree. Params `{}`; the reply is +/// `{nodes: [{id, role, name?, value?, children, textSelection?}], focus, root}` with AccessKit +/// role names. +pub const ACCESS_TREE_METHOD: &str = "ui.accessTree"; +/// The per-request reply deadline. +pub const REPLY_DEADLINE: Duration = Duration::from_secs(60); + +/// The modifier flags of `ui.key`. +pub const KEY_MODIFIERS: [&str; 4] = ["shift", "alt", "command", "ctrl"]; +/// The modifier flags of `ui.pointer` (`space` is the momentary pan). +pub const POINTER_MODIFIERS: [&str; 5] = ["shift", "alt", "command", "ctrl", "space"]; + +/// Typed readers over a request's `params` object; every error names the field. +#[derive(Clone, Copy, Debug)] +pub struct Params<'a>(pub &'a Value); + +impl Params<'_> { + /// `key` as a bool, `None` when absent. + pub fn bool_field(&self, key: &str) -> Result, String> { + match self.0.get(key) { + None => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| format!("{key} must be a boolean")), + } + } + + /// `key` as a non-negative integer. + pub fn uint_field(&self, key: &str) -> Result, String> { + match self.0.get(key) { + None => Ok(None), + Some(v) if v.is_u64() => Ok(v.as_u64()), + Some(v) => v + .as_f64() + .filter(|f| f.fract() == 0.0 && *f >= 0.0) + .map(|f| Some(f as u64)) + .ok_or_else(|| format!("{key} must be a non-negative integer")), + } + } + + /// `key` as a finite number. + pub fn num_field(&self, key: &str) -> Result, String> { + match self.0.get(key) { + None => Ok(None), + Some(v) => v.as_f64().filter(|f| f.is_finite()).map(Some).ok_or_else(|| format!("{key} must be a finite number")), + } + } + + /// `key` as a finite number within `f32` range. + pub fn f32_field(&self, key: &str) -> Result, String> { + match self.0.get(key) { + None => Ok(None), + Some(v) => v + .as_f64() + .filter(|f| f.abs() <= f64::from(f32::MAX)) + .map(Some) + .ok_or_else(|| format!("{key} must be a finite number within f32 range")), + } + } + + /// `key` as a string. + pub fn str_field(&self, key: &str) -> Result, String> { + self.choice(key, key, &[]) + } + + /// The value must be an object with only `fields`, returned with its null fields dropped so + /// they mean "omitted" (a typo must not reply ok after acting on a default). `what` is `None` + /// for a method's params (`params must be an object`, ``unknown field `x` (fields: a, b)``, + /// `null` is `{}`) and the object's name for a nested one (`modifiers must be an object`, + /// ``unknown modifiers field `x` (fields: a, b)``). + pub fn only(&self, what: Option<&str>, fields: &[&str]) -> Result { + let object = match (self.0, what) { + (Value::Null, None) => return Ok(json!({})), + (Value::Object(o), _) => o, + (_, what) => return Err(format!("{} must be an object", what.unwrap_or("params"))), + }; + if let Some(key) = object.keys().find(|k| !fields.contains(&k.as_str())) { + let field = what.map_or_else(|| "field".to_owned(), |w| format!("{w} field")); + return Err(format!("unknown {field} `{key}` (fields: {})", fields.join(", "))); + } + Ok(Value::Object(object.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect())) + } + + /// `key` as a number within `range` (inclusive), `name` in the error. + pub fn number_in(&self, key: &str, name: &str, range: Option<(f64, f64)>) -> Result, String> { + let n = self.num_field(key).map_err(|_| format!("{name} must be a finite number"))?; + match (n, range) { + (Some(n), Some((lo, hi))) if !(lo..=hi).contains(&n) => Err(format!("{name} must be between {lo} and {hi} (got {n})")), + _ => Ok(n), + } + } + + /// `key` as one of `accepted`. + pub fn choice<'v>(&'v self, key: &str, name: &str, accepted: &[&str]) -> Result, String> { + match self.0.get(key) { + None => Ok(None), + Some(Value::String(s)) if accepted.is_empty() || accepted.contains(&s.as_str()) => Ok(Some(s)), + Some(Value::String(s)) => Err(format!("unknown {name} `{s}` ({})", accepted.join(", "))), + Some(_) => Err(format!("{name} must be a string")), + } + } + + /// The modifier flags, top-level or grouped under `modifiers` (an object of the `flags` + /// only, each a bool, errors prefixed `modifiers.`). When grouped, the top-level flags are + /// ignored but still type-checked. The result is as the platform sees it + /// ([`craft_keymap::Mods::effective`]): off the Mac `ctrl` folds into `cmd`, so a request that + /// sets only one reaches the same shortcuts as a real Ctrl press; on the Mac they stay apart. + #[cfg(feature = "ui")] + pub fn modifiers(&self, flags: &[&str]) -> Result { + for flag in flags { + self.bool_field(flag)?; + } + let grouped = match self.0.get("modifiers") { + None => None, + Some(m) => { + let m = Params(m).only(Some("modifiers"), flags)?; + for flag in flags { + Params(&m).bool_field(flag).map_err(|e| format!("modifiers.{e}"))?; + } + Some(m) + } + }; + let m = grouped.as_ref().unwrap_or(self.0); + let flag = |k: &str| m.get(k).and_then(Value::as_bool).unwrap_or(false); + let held = craft_keymap::Mods { cmd: flag("command"), ctrl: flag("ctrl"), alt: flag("alt"), shift: flag("shift") }; + Ok(held.effective(craft_keymap::Platform::current())) + } + + /// Deserialize `T` from the whole object, replacing `current`. A key `current` doesn't have + /// when serialized is ``unknown {what} field `k` ``, whether or not `T` denies unknown fields; + /// a non-object is `{what} must be an object` and a serde error is `{what}: {error}`. + pub fn whole(&self, what: &str, current: &T) -> Result { + let Some(patch) = self.0.as_object() else { return Err(format!("{what} must be an object")) }; + let known = serde_json::to_value(current).map_err(|e| e.to_string())?; + if let Some(key) = patch.keys().find(|k| known.as_object().is_none_or(|o| !o.contains_key(*k))) { + return Err(format!("unknown {what} field `{key}`")); + } + serde_json::from_value(Value::Object(patch.clone())).map_err(|e| format!("{what}: {e}")) + } + + /// `current` serialized, the object's fields merged over it, deserialized back: a partial + /// `ui.set`-style update. A field `current` doesn't have is ``unknown {what} field `k` ``. + pub fn merged_into(&self, what: &str, current: &T) -> Result { + let Some(patch) = self.0.as_object() else { return Err(format!("{what} must be an object")) }; + let mut merged = serde_json::to_value(current).map_err(|e| e.to_string())?; + let Some(fields) = merged.as_object_mut() else { return Err(format!("{what} must be an object")) }; + for (key, value) in patch { + if !fields.contains_key(key) { + return Err(format!("unknown {what} field `{key}`")); + } + fields.insert(key.clone(), value.clone()); + } + serde_json::from_value(merged).map_err(|e| format!("{what}: {e}")) + } +} diff --git a/crates/automation/src/screenshot.rs b/crates/automation/src/screenshot.rs new file mode 100644 index 0000000000..2b37383a8e --- /dev/null +++ b/crates/automation/src/screenshot.rs @@ -0,0 +1,847 @@ +//! `ui.screenshot`: bounded, cancellable capture requests over [`WindowHost::screenshot`]. +//! +//! The slot correlates one capture with one image. This queue owns what the slot leaves to the +//! app: request identity (token, output path, reply, the viewport it shoots and the region of it, +//! refused at admission when outside the window and cropped in [`screenshot_reply`]), deadlines and +//! settling, the admission budget ([`MAX_PENDING`] requests, [`MAX_IMAGE_BYTES`] per image, +//! [`MAX_TOTAL_BYTES`] in all), the document identity fixed at admission, each viewport's geometry +//! epoch recorded at issue so an image is saved only for the layout it was rendered from (a size, +//! scale, zoom or minimised change between issue and collection is a retry, at most +//! [`MAX_RETRIES`]), and a monotonic clock. A request for a viewport whose geometry is not recorded +//! yet waits instead of failing; one whose window is not open fails with [`WINDOW_CLOSED`]. +//! +//! Phases: [`Captures::issue`] runs in the UI pass (settling counts real layout passes; a +//! discarded pass is skipped); [`Captures::note_windows`] (or [`Captures::note_geometry`] for a +//! synthetic geometry) and [`Captures::drain`] run in the logic phase. The image is encoded and written on the UI thread by +//! [`ControlChannel::finish_captures`](crate::control::ControlChannel::finish_captures), never +//! inside the callback. + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::mpsc::Sender; +use std::time::Duration; + +use base64::Engine as _; +use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost}; +use egui::{ColorImage, Rect, ViewportId}; +use serde_json::Value; +use web_time::Instant; + +use crate::control::ControlResponse; +use crate::protocol::Params; + +/// Requests outstanding at once (issued, completed, waiting for geometry or waiting to be issued). +pub const MAX_PENDING: usize = 4; +/// Largest single image the slot may retain, and the largest a request may reserve. +pub const MAX_IMAGE_BYTES: usize = 128 * 1024 * 1024; +/// Aggregate reserved bytes over every outstanding request. +pub const MAX_TOTAL_BYTES: usize = 256 * 1024 * 1024; +/// A request expires after this long, including retries and settling. +pub const DEADLINE: Duration = Duration::from_secs(8); +/// UI passes a request waits before it is issued, on top of the animation delay. +pub const SETTLE_PASSES: u32 = 3; +/// Retries after the geometry changed while a capture was in flight. +pub const MAX_RETRIES: u8 = 2; +/// The base delay that lets popup open and close animations finish. +const BASE_SETTLE_MS: f64 = 60.0; + +/// The document a screenshot belongs to, fixed at admission. `generation` must be the app's +/// active-document generation: it changes on every switch of the active document, including a +/// switch away and back, so it is not a per-document counter. `revision` is recorded for +/// attribution only. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct DocumentId { + /// The app's active-document generation at admission. + pub generation: u64, + /// The document revision at admission; recorded for attribution only. + pub revision: u64, +} + +impl DocumentId { + /// The document of active-document `generation` at `revision`. + pub const fn new(generation: u64, revision: u64) -> Self { + Self { generation, revision } + } + + /// Whether both ids name the same active document (same `generation`). + pub fn same_document(self, other: Self) -> bool { + self.generation == other.generation + } +} + +/// The layout of the viewport a capture is rendered from: size in points, pixels per point, +/// zoom, the texture side limit and whether the window is minimised. Window position is not part +/// of it. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct CaptureGeometry { + /// Viewport size in logical points, `[width, height]`. + pub size_points: [f32; 2], + /// Physical pixels per point, including zoom. + pub pixels_per_point: f32, + /// The UI zoom factor. + pub zoom: f32, + /// The renderer's largest texture side, in pixels. + pub max_texture_side: usize, + /// Whether the window is minimised. + pub minimized: bool, + /// The active document, if any; not part of the layout identity. + pub document: Option, +} + +impl CaptureGeometry { + /// A visible, unzoomed viewport of `size_points` at one pixel per point, with no active document. + pub const fn new(size_points: [f32; 2], max_texture_side: usize) -> Self { + Self { size_points, pixels_per_point: 1.0, zoom: 1.0, max_texture_side, minimized: false, document: None } + } + + /// The geometry the window reported this pass. + pub fn from_facts(facts: ScreenshotFacts, document: Option) -> Self { + Self { + size_points: [facts.size_points.x, facts.size_points.y], + pixels_per_point: facts.pixels_per_point, + zoom: facts.zoom, + max_texture_side: facts.max_texture_side, + minimized: facts.minimized, + document, + } + } + + /// The image size in pixels: the size in points times the point scale, rounded. `None` for a + /// degenerate viewport (a non-finite or non-positive size, scale or zoom, or a side under one + /// pixel). A window over the texture limit is not rejected: the renderer may fit it, and + /// `check_image` accepts a uniform fit. + pub fn expected_pixels(&self) -> Option<[usize; 2]> { + let valid = |v: f32| v.is_finite() && v > 0.0; + let [width, height] = self.size_points; + if !valid(width) || !valid(height) || !valid(self.pixels_per_point) || !valid(self.zoom) { + return None; + } + let w = (width * self.pixels_per_point).round(); + let h = (height * self.pixels_per_point).round(); + if w < 1.0 || h < 1.0 || w > usize::MAX as f32 || h > usize::MAX as f32 { + return None; + } + Some([w as usize, h as usize]) + } + + /// The identity compared for stale-image rejection: everything but the document. + fn same_layout(&self, other: &Self) -> bool { + self.size_points == other.size_points + && self.pixels_per_point == other.pixels_per_point + && self.zoom == other.zoom + && self.max_texture_side == other.max_texture_side + && self.minimized == other.minimized + } + + /// RGBA bytes of [`Self::expected_pixels`], from checked arithmetic. + pub fn expected_bytes(&self) -> Option { + let [w, h] = self.expected_pixels()?; + w.checked_mul(h)?.checked_mul(std::mem::size_of::()) + } +} + +/// The error a request for a closed window finishes with, after `screenshot {token} failed: `. +pub const WINDOW_CLOSED: &str = "its window is not open"; + +/// One outstanding request; holds the strong slot. +pub struct PendingCapture { + token: u64, + viewport: ViewportId, + path: Option, + region: Option, + reply: Option>, + deadline: Instant, + ready_at: Instant, + settle_passes: u32, + geometry: CaptureGeometry, + epoch: u64, + issued_epoch: Option, + reserved_bytes: usize, + document: Option, + slot: Option, + retries: u8, +} + +impl PendingCapture { + /// The caller's token for this request. + pub fn token(&self) -> u64 { + self.token + } + + /// Whether the render for this capture was already requested. + pub fn issued(&self) -> bool { + self.issued_epoch.is_some() + } +} + +/// A request that is over: an image to save and reply, or an error. +#[non_exhaustive] +pub struct Finished { + /// The request's token. + pub token: u64, + /// File to write the PNG to; `None` inlines it in the reply. + pub path: Option, + /// The part of the window to crop the image to, in points; `None` keeps the whole window. + pub region: Option, + /// The layout the image was captured from; the crop and the reply's `pixels_per_point` read it. + pub geometry: CaptureGeometry, + /// Where to send the answer. + pub reply: Option>, + /// The captured image, or the error text for the reply. + pub result: Result, String>, +} + +impl Finished { + /// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given, + /// cropped to `region` as `geometry` scales it. + pub fn new( + token: u64, + path: Option, + region: Option, + geometry: CaptureGeometry, + reply: Option>, + result: Result, String>, + ) -> Self { + Self { token, path, region, geometry, reply, result } + } +} + +/// A screenshot request as the control surface received it. +#[non_exhaustive] +pub struct ScreenshotRequest { + /// The caller's token: one per pending request. + pub token: u64, + /// Where to write the PNG, when the reply is a file. + pub path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + pub region: Option, + /// The viewport to capture. + pub viewport: ViewportId, + /// Where the reply goes. + pub reply: Sender, + /// The document the capture belongs to. + pub document: Option, + /// The settle delay in milliseconds of animation time. + pub settle_ms: f64, +} + +impl ScreenshotRequest { + /// A request for the whole of `viewport` answered on `reply`: no file, no document, no settle delay. + pub fn new(token: u64, viewport: ViewportId, reply: Sender) -> Self { + Self { token, path: None, region: None, viewport, reply, document: None, settle_ms: 0.0 } + } +} + +/// A request not yet queued: it waits while its viewport's geometry is not recorded. +struct WaitingAdmit { + token: u64, + viewport: ViewportId, + path: Option, + region: Option, + reply: Sender, + deadline: Instant, + settle_ms: f64, + document: Option, +} + +/// What one viewport's window measured: its geometry this pass, `None` while the window is not +/// open, and the epoch that advances on each layout change. +#[derive(Clone, Copy, Default)] +struct Window { + geometry: Option, + epoch: u64, +} + +/// The screenshot request queue and its admission budget. +#[derive(Default)] +pub struct Captures { + records: Vec, + waiting: Vec, + /// One entry per recorded viewport; a viewport with no entry was never measured. + windows: HashMap, +} + +impl Captures { + /// Requests admitted or waiting for geometry. + pub fn pending(&self) -> usize { + self.records.len() + self.waiting.len() + } + + /// Bytes reserved for admitted images; counted against [`MAX_TOTAL_BYTES`]. + pub fn reserved_bytes(&self) -> usize { + self.records.iter().map(|r| r.reserved_bytes).sum() + } + + /// Whether any request is pending. + pub fn any_pending(&self) -> bool { + self.pending() > 0 + } + + /// Requests not yet issued (the app keeps repainting while any). + pub fn any_unissued(&self) -> bool { + !self.waiting.is_empty() || self.records.iter().any(|r| !r.issued()) + } + + /// The geometry recorded by the last [`Self::note_geometry`] for `viewport`, if any. + pub fn last_geometry(&self, viewport: ViewportId) -> Option { + self.windows.get(&viewport).and_then(|window| window.geometry) + } + + /// Record this pass's geometry of `viewport`; advances and returns that viewport's epoch when + /// it changed. + pub fn note_geometry(&mut self, viewport: ViewportId, geometry: CaptureGeometry) -> u64 { + let window = self.windows.entry(viewport).or_default(); + let changed = window.geometry.is_none_or(|old| !old.same_layout(&geometry)); + if changed { + window.epoch = window.epoch.wrapping_add(1); + } + window.geometry = Some(geometry); + window.epoch + } + + /// The app's one call per pass: for the root and each viewport a pending or waiting request + /// names, records `CaptureGeometry::from_facts` of `host.screenshot_facts(viewport)`, or marks + /// the viewport closed when that is `None`. Viewports no request names are forgotten, so a + /// window measured for an earlier request is measured afresh for the next. + pub fn note_windows(&mut self, host: &WindowHost, document: Option) { + let mut named = vec![ViewportId::ROOT]; + for viewport in self.records.iter().map(|r| r.viewport).chain(self.waiting.iter().map(|w| w.viewport)) { + if !named.contains(&viewport) { + named.push(viewport); + } + } + self.windows.retain(|viewport, _| named.contains(viewport)); + for viewport in named { + match host.screenshot_facts(viewport) { + Some(facts) => { + self.note_geometry(viewport, CaptureGeometry::from_facts(facts, document)); + } + None if host.is_open(viewport) => {} + None => self.windows.entry(viewport).or_default().geometry = None, + } + } + } + + /// Admit a request for `viewport` against the budget. `Err` returns the reply sender with the + /// error text: + /// `screenshot token {token} is already pending`, + /// `too many screenshots pending (at most {MAX_PENDING})`, + /// `screenshot {token} failed: {WINDOW_CLOSED}`, + /// `the viewport is not capturable ({w}×{h} points at {ppp} px/pt, texture side {side})`, + /// `a {N} MiB screenshot is over the {MAX_IMAGE_BYTES / 1 MiB} MiB per-image limit` (`N` the + /// expected bytes / 1 MiB, integer division), or + /// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`, or + /// `screenshot {token} failed: the region must lie inside the {w}×{h}-point window`. The budget is reserved for + /// the whole window, region or not: the slot retains the whole image until it is cropped. + /// While the viewport's geometry is not recorded the request waits. + pub fn admit(&mut self, request: ScreenshotRequest, now: Instant) -> Result<(), (Sender, String)> { + let ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms } = request; + if self.records.iter().any(|r| r.token == token) || self.waiting.iter().any(|w| w.token == token) { + return Err((reply, format!("screenshot token {token} is already pending"))); + } + if self.pending() >= MAX_PENDING { + return Err((reply, format!("too many screenshots pending (at most {MAX_PENDING})"))); + } + let request = WaitingAdmit { token, viewport, path, region, reply, deadline: now + DEADLINE, settle_ms, document }; + match self.windows.get(&viewport).copied() { + None => { + self.waiting.push(request); + Ok(()) + } + Some(Window { geometry: None, .. }) => Err((request.reply, window_closed_error(token))), + Some(Window { geometry: Some(geometry), epoch }) => self.admit_with_geometry(request, geometry, epoch), + } + } + + /// Queues `request` at `geometry` and `epoch`, what its viewport's window recorded. + fn admit_with_geometry(&mut self, request: WaitingAdmit, geometry: CaptureGeometry, epoch: u64) -> Result<(), (Sender, String)> { + let WaitingAdmit { token, viewport, path, region, reply, deadline, settle_ms, document } = request; + // The request's clock started when it arrived. + let arrived = deadline - DEADLINE; + if self.records.iter().any(|r| r.token == token) { + return Err((reply, format!("screenshot token {token} is already pending"))); + } + if self.records.len() >= MAX_PENDING { + return Err((reply, format!("too many screenshots pending (at most {MAX_PENDING})"))); + } + let expected = match image_budget(&geometry) { + Ok(bytes) => bytes, + Err(e) => return Err((reply, e)), + }; + if let Err(e) = check_region(token, region, &geometry) { + return Err((reply, e)); + } + if let Err(e) = aggregate_budget(self.reserved_bytes(), expected) { + return Err((reply, e)); + } + // `Duration::from_secs_f64` panics on NaN, infinity and negatives. + let settle = if settle_ms.is_finite() { settle_ms.clamp(0.0, 2000.0) } else { BASE_SETTLE_MS }; + self.records.push(PendingCapture { + token, + viewport, + path, + region, + reply: Some(reply), + deadline, + ready_at: arrived + Duration::from_secs_f64(settle / 1000.0), + settle_passes: 0, + geometry, + epoch, + issued_epoch: None, + reserved_bytes: expected, + document, + slot: None, + retries: 0, + }); + Ok(()) + } + + /// Move waiting requests into the queue once their viewport's geometry is known, fail those + /// whose window is closed, and expire the rest at their deadline. + pub fn admit_waiting(&mut self, now: Instant) { + if self.waiting.is_empty() { + return; + } + let parked = std::mem::take(&mut self.waiting); + let mut still_waiting = Vec::new(); + for w in parked { + if now >= w.deadline { + let _ = w.reply.send(serde_json::json!({"ok": false, "error": timeout_error(w.token)})); + continue; + } + let admitted = match self.windows.get(&w.viewport).copied() { + None => { + still_waiting.push(w); + continue; + } + Some(Window { geometry: None, .. }) => Err((w.reply, window_closed_error(w.token))), + Some(Window { geometry: Some(geometry), epoch }) => self.admit_with_geometry(w, geometry, epoch), + }; + if let Err((reply, e)) = admitted { + let _ = reply.send(serde_json::json!({"ok": false, "error": e})); + } + } + self.waiting = still_waiting; + } + + /// One real UI pass happened (settling). + pub fn note_pass(&mut self) { + for r in &mut self.records { + r.settle_passes = r.settle_passes.saturating_add(1); + } + } + + /// UI phase: issue due requests through `host` (a fresh slot each), each in its own viewport, + /// and return the ones that expired or whose window closed meanwhile. + pub fn issue(&mut self, host: &WindowHost, now: Instant, document: Option) -> Vec { + let mut finished = Vec::new(); + for i in 0..self.records.len() { + if self.records[i].issued() { + continue; + } + let token = self.records[i].token; + if now >= self.records[i].deadline { + finished.push(finish(&mut self.records[i], Err(timeout_error(token)))); + continue; + } + let Some(window) = self.windows.get(&self.records[i].viewport).copied() else { continue }; + let Some(current) = window.geometry else { + finished.push(finish(&mut self.records[i], Err(window_closed_error(token)))); + continue; + }; + if !same_activation(document, self.records[i].document) || !same_activation(current.document, self.records[i].document) { + finished.push(finish(&mut self.records[i], Err(document_changed_error(token)))); + continue; + } + // A document switch inside the pass means neither the drawn frame nor the pass's + // document identity is trustworthy. + if !same_activation(current.document, document) { + continue; + } + // A minimised window has no surface to read back. + if current.minimized { + finished.push(finish(&mut self.records[i], Err(format!("screenshot {token} failed: the window is minimized")))); + continue; + } + if self.records[i].settle_passes < SETTLE_PASSES || now < self.records[i].ready_at { + continue; + } + // No pixels exist yet: finalise the geometry at issue, re-checking the budget, and + // let the new layout settle for another pass. + if self.records[i].epoch != window.epoch || !current.same_layout(&self.records[i].geometry) { + let others: usize = self.records.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, r)| r.reserved_bytes).sum(); + if let Err(e) = revalidate_reservation(&mut self.records[i], others, current, window.epoch) { + finished.push(finish(&mut self.records[i], Err(e))); + } + continue; + } + let slot = host.screenshot(self.records[i].viewport, MAX_IMAGE_BYTES); + let r = &mut self.records[i]; + r.slot = Some(slot); + r.issued_epoch = Some(window.epoch); + } + self.records.retain(|r| !finished.iter().any(|f| f.token == r.token)); + finished + } + + /// Logic phase: collect completed images (retrying after an epoch advance), expire the late + /// and fail those whose window closed. Each request is read against the geometry its own + /// viewport recorded this pass. + pub fn drain(&mut self, now: Instant, document: Option) -> Vec { + // Requests that arrived before their viewport was measured start here, once it is. + self.admit_waiting(now); + let mut finished = Vec::new(); + for i in 0..self.records.len() { + let token = self.records[i].token; + // The deadline comes before the image: a callback that arrives late is a timeout. + if now >= self.records[i].deadline { + finished.push(finish(&mut self.records[i], Err(timeout_error(token)))); + continue; + } + let window = self.windows.get(&self.records[i].viewport).copied(); + if window.is_some_and(|window| window.geometry.is_none()) { + finished.push(finish(&mut self.records[i], Err(window_closed_error(token)))); + continue; + } + let current = window.and_then(|window| window.geometry); + if !same_activation(document, self.records[i].document) || !same_activation(current.and_then(|c| c.document), self.records[i].document) { + finished.push(finish(&mut self.records[i], Err(document_changed_error(token)))); + continue; + } + let Some(slot) = self.records[i].slot.take() else { continue }; + let Some(result) = slot.take() else { + self.records[i].slot = Some(slot); + continue; + }; + let image = match result { + Ok(image) => image, + Err(e) => { + slot.cancel(); + finished.push(finish(&mut self.records[i], Err(format!("screenshot {token} failed: {e}")))); + continue; + } + }; + let Some((current, epoch)) = window.and_then(|window| window.geometry.map(|geometry| (geometry, window.epoch))) else { + finished.push(finish(&mut self.records[i], Err(format!("screenshot {token} failed: the window geometry is unknown")))); + continue; + }; + // An epoch advance since issue means the image may belong to an intermediate layout, + // even if the values changed back. + let epoch_advanced = self.records[i].issued_epoch.is_none_or(|issued| issued != epoch); + let pass_mixed = !same_activation(current.document, document); + if epoch_advanced || !current.same_layout(&self.records[i].geometry) || pass_mixed { + slot.cancel(); + if self.records[i].retries >= MAX_RETRIES { + finished.push(finish(&mut self.records[i], Err(format!("screenshot {token} failed: the layout changed while it was captured")))); + continue; + } + self.records[i].retries = self.records[i].retries.saturating_add(1); + let others: usize = self.records.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, r)| r.reserved_bytes).sum(); + match revalidate_reservation(&mut self.records[i], others, current, epoch) { + Ok(()) => self.records[i].ready_at = now, + Err(e) => finished.push(finish(&mut self.records[i], Err(e))), + } + continue; + } + if let Err(e) = check_image(&image, &self.records[i].geometry) { + slot.cancel(); + finished.push(finish(&mut self.records[i], Err(format!("screenshot {token} failed: {e}")))); + continue; + } + slot.cancel(); + finished.push(finish(&mut self.records[i], Ok(image))); + } + self.records.retain(|r| !finished.iter().any(|f| f.token == r.token)); + finished + } + + /// Fail every outstanding request with `reason` (quit, device lost). + pub fn cancel_all(&mut self, reason: &str) -> Vec { + let mut finished = Vec::new(); + for w in self.waiting.drain(..) { + finished.push(Finished { + token: w.token, + path: w.path, + region: w.region, + // No geometry was recorded for a waiting request; the result is an error, so nothing reads it. + geometry: CaptureGeometry::new([0.0, 0.0], 0), + reply: Some(w.reply), + result: Err(format!("screenshot {} cancelled: {reason}", w.token)), + }); + } + for mut r in self.records.drain(..) { + if let Some(slot) = r.slot.take() { + slot.cancel(); + } + finished.push(Finished { + token: r.token, + path: r.path.take(), + region: r.region, + geometry: r.geometry, + reply: r.reply.take(), + result: Err(format!("screenshot {} cancelled: {reason}", r.token)), + }); + } + finished + } +} + +/// The bytes a geometry reserves, or the reason it cannot be captured at all. +fn image_budget(geometry: &CaptureGeometry) -> Result { + let Some(expected) = geometry.expected_bytes() else { + return Err(format!( + "the viewport is not capturable ({}×{} points at {} px/pt, texture side {})", + geometry.size_points[0], geometry.size_points[1], geometry.pixels_per_point, geometry.max_texture_side + )); + }; + if expected > MAX_IMAGE_BYTES { + return Err(format!("a {} MiB screenshot is over the {} MiB per-image limit", expected / (1 << 20), MAX_IMAGE_BYTES / (1 << 20))); + } + Ok(expected) +} + +/// Check one reservation against the aggregate budget, excluding the request itself. +fn aggregate_budget(others: usize, expected: usize) -> Result<(), String> { + let total = others.saturating_add(expected); + if total > MAX_TOTAL_BYTES { + return Err(format!("screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit")); + } + Ok(()) +} + +/// Whether `region` lies inside the window of `geometry`: the request is refused otherwise, never cropped to a +/// smaller image than it asked for. `None` (the whole window) always fits. +fn check_region(token: u64, region: Option, geometry: &CaptureGeometry) -> Result<(), String> { + let Some(region) = region else { return Ok(()) }; + let [width, height] = geometry.size_points; + if region.min.x >= 0.0 && region.min.y >= 0.0 && region.max.x <= width && region.max.y <= height { + return Ok(()); + } + Err(format!("screenshot {token} failed: the region must lie inside the {width}×{height}-point window")) +} + +/// Finalise a request at a new geometry: recheck the per-image and aggregate limits (excluding +/// its old reservation) and that its region still fits, take the new reservation and restart settling. +fn revalidate_reservation(r: &mut PendingCapture, others: usize, geometry: CaptureGeometry, epoch: u64) -> Result<(), String> { + let expected = image_budget(&geometry)?; + aggregate_budget(others, expected)?; + check_region(r.token, r.region, &geometry)?; + r.reserved_bytes = expected; + r.geometry = geometry; + r.epoch = epoch; + r.issued_epoch = None; + r.settle_passes = 0; + Ok(()) +} + +fn finish(r: &mut PendingCapture, result: Result, String>) -> Finished { + if let Some(slot) = r.slot.take() { + slot.cancel(); + } + Finished { token: r.token, path: r.path.take(), region: r.region, geometry: r.geometry, reply: r.reply.take(), result } +} + +/// The returned image must be the issued viewport (within a pixel) or a uniform renderer fit +/// bounded by `max_texture_side`. A smaller same-aspect image is not accepted: it could be a stale +/// or downscaled surface. A different aspect ratio is a resize. +fn check_image(image: &ColorImage, geometry: &CaptureGeometry) -> Result<(), String> { + let Some([w, h]) = geometry.expected_pixels() else { + return Err("the captured geometry has no valid pixel size".into()); + }; + let [iw, ih] = image.size; + if iw == 0 || ih == 0 { + return Err("the image has a zero side".into()); + } + if iw > w.saturating_add(1) || ih > h.saturating_add(1) { + return Err(format!("the image is {iw}×{ih}, larger than the issued viewport {w}×{h}")); + } + let close = |a: usize, b: usize| a.abs_diff(b) <= 1; + if close(iw, w) && close(ih, h) { + return Ok(()); + } + let side = geometry.max_texture_side.max(1); + let fit = (side as f64 / w.max(h) as f64).min(1.0); + let fw = (w as f64 * fit).round() as usize; + let fh = (h as f64 * fit).round() as usize; + if fw >= 1 && fh >= 1 && close(iw, fw) && close(ih, fh) { + return Ok(()); + } + let expected_aspect = w as f32 / h as f32; + let actual_aspect = iw as f32 / ih as f32; + if !actual_aspect.is_finite() || (actual_aspect - expected_aspect).abs() > expected_aspect * 0.02 { + return Err(format!("the image is {iw}×{ih}, not the issued {w}×{h} aspect ratio")); + } + Err(format!("the image is {iw}×{ih}, neither the issued {w}×{h} viewport nor its {fw}×{fh} texture-side fit")) +} + +/// Whether two optional document identities are the same document in the same activation. +fn same_activation(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => a.same_document(b), + (None, None) => true, + _ => false, + } +} + +fn timeout_error(token: u64) -> String { + format!("screenshot {token} timed out: no frame was presented within {} s", DEADLINE.as_secs()) +} + +fn window_closed_error(token: u64) -> String { + format!("screenshot {token} failed: {WINDOW_CLOSED}") +} + +fn document_changed_error(token: u64) -> String { + format!("screenshot {token} failed: the document changed while the capture was queued") +} + +/// The settle delay for `animation_time`: a base that lets popup animations end plus the +/// animation time itself. +pub fn settle_ms(animation_time: f32) -> f64 { + f64::from(animation_time) * 2000.0 + BASE_SETTLE_MS +} + +/// Encode unmultiplied RGBA pixels as an 8-bit RGBA PNG (the `png` crate, default +/// compression); an encoder error is its message. +pub fn encode_png(width: usize, height: usize, rgba: &[u8]) -> Result, String> { + let (w, h) = (u32::try_from(width).map_err(|e| e.to_string())?, u32::try_from(height).map_err(|e| e.to_string())?); + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().map_err(|e| e.to_string())?; + writer.write_image_data(rgba).map_err(|e| e.to_string())?; + writer.finish().map_err(|e| e.to_string())?; + Ok(out) +} + +/// Writes a screenshot's PNG bytes to an automation path: the app's file authority, limited to its +/// authorized workspace. `Err` is the reply's error text. +pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a; + +/// A validated `ui.screenshot`: where the PNG goes and which part of the window it shows. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct ScreenshotParams { + /// File to write the PNG to, or `None` to inline it. + pub path: Option, + /// The part of the window to capture as `[x0, y0, x1, y1]` in points, finite and ordered; `None` captures the + /// whole window. + pub region: Option, +} + +impl ScreenshotParams { + /// `{path?, region?}`, no other fields. `path` is a string; `region` is `[x0, y0, x1, y1]` in points, four finite + /// numbers with `x0 < x1` and `y0 < y1`: ``"region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and + /// y0 < y1"`` otherwise. Whether it lies inside the window is checked at admission, against the window's geometry. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["path", "region"])?; + let p = Params(&p); + let path = p.str_field("path")?.map(str::to_owned); + let region = p.0.get("region").map(region_param).transpose()?; + Ok(ScreenshotParams { path, region }) + } +} + +/// `region`: `[x0, y0, x1, y1]`, finite and ordered. +fn region_param(region: &Value) -> Result { + const SHAPE: &str = "region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and y0 < y1"; + let number = |v: &Value| v.as_f64().map(|n| n as f32).filter(|n| n.is_finite()); + let corners = match region.as_array().map(Vec::as_slice) { + Some([x0, y0, x1, y1]) => number(x0).zip(number(y0)).zip(number(x1).zip(number(y1))), + _ => None, + }; + corners + .filter(|((x0, y0), (x1, y1))| x0 < x1 && y0 < y1) + .map(|((x0, y0), (x1, y1))| Rect::from_min_max(egui::pos2(x0, y0), egui::pos2(x1, y1))) + .ok_or_else(|| SHAPE.into()) +} + +/// The pixel columns and rows `[x0, y0, x1, y1)` of `region` in an image of `size` captured at `geometry`. The image +/// scale is `size / geometry.size_points`, never `pixels_per_point`: a renderer that fitted the surface to its +/// texture side returns a smaller image of the same layout. Edges round to the nearest pixel and are clamped to the +/// image; `None` when nothing of the region is left or the geometry has no area. +fn crop_pixels(region: Rect, geometry: &CaptureGeometry, size: [usize; 2]) -> Option<[usize; 4]> { + let [width, height] = geometry.size_points; + if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) { + return None; + } + let (sx, sy) = (size[0] as f32 / width, size[1] as f32 / height); + // `as usize` saturates: a negative or NaN edge is 0, an edge past the image is clamped below. + let px = |v: f32, scale: f32, max: usize| ((v * scale).round() as usize).min(max); + let [x0, x1] = [px(region.min.x, sx, size[0]), px(region.max.x, sx, size[0])]; + let [y0, y1] = [px(region.min.y, sy, size[1]), px(region.max.y, sy, size[1])]; + (x0 < x1 && y0 < y1).then_some([x0, y0, x1, y1]) +} + +/// The reply for a finished image, cropped to `region` (in points; `None` keeps the whole image) at the scale of the +/// image to `geometry`, the layout it was captured from: +/// - a region with no pixels left in the image: +/// `{"ok": false, "error": "screenshot {token} failed: the region has no pixels in the captured image"}`; +/// - a crop over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows): +/// `{"ok": false, "error": "screenshot {token} failed: the image exceeds the {MAX_IMAGE_BYTES / 1 MiB} MiB encode budget"}`; +/// - no `path`: `{"ok": true, "result": {"base64": , "mime": "image/png", "width", "height", +/// "pixels_per_point"}}`, with no size limit beyond the encode budget; +/// - a `path`: the PNG goes to `write(path, bytes)`, the app's file authority (limited to its +/// authorized workspace), and the reply is +/// `{"ok": true, "result": {"path", "width", "height", "pixels_per_point"}}`; +/// - an encode or write error `e`: `{"ok": false, "error": e}`. +/// +/// `width` and `height` are the crop's pixels; `pixels_per_point` is `geometry`'s, the window's scale. +/// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap. +pub fn screenshot_reply( + token: u64, + image: Arc, + region: Option, + geometry: CaptureGeometry, + path: Option<&str>, + write: &mut PngWriter<'_>, +) -> ControlResponse { + let [w, h] = image.size; + let crop = match region { + None => Some([0, 0, w, h]), + Some(region) => crop_pixels(region, &geometry, [w, h]), + }; + let Some([x0, y0, x1, y1]) = crop.filter(|[x0, y0, x1, y1]| x0 < x1 && y0 < y1) else { + return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the region has no pixels in the captured image")}); + }; + let (cw, ch) = (x1 - x0, y1 - y0); + let Some(bytes) = cw.checked_mul(ch).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else { + return serde_json::json!({ + "ok": false, + "error": format!("screenshot {token} failed: the image exceeds the {} MiB encode budget", MAX_IMAGE_BYTES / (1 << 20)), + }); + }; + let mut rgba = Vec::with_capacity(bytes); + for y in y0..y1 { + let row = y.checked_mul(w).and_then(|start| image.pixels.get(start + x0..start + x1)); + let Some(row) = row else { + return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the image has fewer pixels than its size")}); + }; + rgba.extend(row.iter().flat_map(|c| c.to_array())); + } + drop(image); + let png = match encode_png(cw, ch, &rgba) { + Ok(png) => png, + Err(e) => return serde_json::json!({"ok": false, "error": e}), + }; + let ppp = geometry.pixels_per_point; + let Some(path) = path else { + return serde_json::json!({ + "ok": true, + "result": { + "base64": base64::engine::general_purpose::STANDARD.encode(png), + "mime": "image/png", + "width": cw, + "height": ch, + "pixels_per_point": ppp, + }, + }); + }; + match write(path, &png) { + Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": cw, "height": ch, "pixels_per_point": ppp}}), + Err(e) => serde_json::json!({"ok": false, "error": e}), + } +} diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs new file mode 100644 index 0000000000..259d2f3cb2 --- /dev/null +++ b/crates/automation/src/security.rs @@ -0,0 +1,511 @@ +//! Tokens, the authentication handshake and the limits every transport applies. +//! +//! A connection authenticates within [`AUTH_DEADLINE`] ([`ServerHandshake`]): with the challenge +//! handshake, which never sends the token, or with the one-frame +//! `{"id": 1, "method": "auth", "params": {"token": "<64 hex>"}}`. Until then nothing else is +//! answered. A request line is at most +//! [`MAX_REQUEST_BYTES`]; a transport serves at most [`MAX_CONNECTIONS`] at once; a connection +//! 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. + +use std::fs::OpenOptions; +use std::io::{BufRead, Write}; +use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use hmac::{Hmac, Mac}; +use serde_json::{Value, json}; +use sha2::Sha256; + +/// The request that authenticates a connection: with the token itself, or with the client's +/// proof after [`CHALLENGE_METHOD`]. +pub const AUTH_METHOD: &str = "auth"; +/// The first frame of challenge authentication: it carries a client nonce, never the token. +pub const CHALLENGE_METHOD: &str = "auth.challenge"; +/// Longest request line, in bytes; a longer one gets an error reply and the connection closes. +pub const MAX_REQUEST_BYTES: usize = 1 << 20; +/// Connections served at once; the next one gets `connection limit reached` and is closed. +pub const MAX_CONNECTIONS: usize = 16; +/// Steps a `batch` request may carry. +pub const MAX_BATCH_STEPS: usize = 256; +/// Read and write timeout on a connection. +pub const IO_TIMEOUT: Duration = Duration::from_secs(30); +/// A connection that has not authenticated this long after connecting is closed, however much it +/// sent meanwhile. +pub const AUTH_DEADLINE: Duration = Duration::from_secs(10); +/// Token length in hex characters (32 random bytes). +pub const TOKEN_HEX_LEN: usize = 64; + +/// What the control channel refuses or cannot set up. `Display` is the text a user or agent +/// reads. PhotoCraft's `photocraft_automation::AutomationError` has the same two variants with the +/// same texts (`crates/automation/src/lib.rs:35`), so it wraps these one to one. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum AutomationError { + /// A bad token, a token conflict, a missing client token; the message as is. + #[error("{0}")] + BadRequest(String), + /// A token file that can't be read, created or trusted; `I/O: : `. + #[error("I/O: {0}")] + Io(String), +} + +/// How a bounded line read ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LineRead { + /// `line` holds one complete line (with its newline). + Line, + /// The stream ended before a newline; `line` holds what arrived. + Eof, + /// More than [`MAX_REQUEST_BYTES`] arrived without a newline; `line` holds the bytes read so + /// far, lossily decoded, and the rest of the line is still unread unless `line` ends with a + /// newline (see [`discard_rest_of_line`]). + TooLong, +} + +/// Read one line into `line` (cleared first), never buffering more than [`MAX_REQUEST_BYTES`] +/// plus one byte. A line within the limit that is not UTF-8 is an `InvalidData` error, and the +/// whole line has been consumed. +pub fn read_bounded_line(reader: &mut impl BufRead, line: &mut String) -> std::io::Result { + line.clear(); + let mut bytes = Vec::new(); + let n = std::io::Read::take(&mut *reader, (MAX_REQUEST_BYTES + 1) as u64).read_until(b'\n', &mut bytes)?; + if n == 0 { + Ok(LineRead::Eof) + } else if n > MAX_REQUEST_BYTES { + // A cut can split a multi-byte character; the length, not the text, decides. + line.push_str(&String::from_utf8_lossy(&bytes)); + Ok(LineRead::TooLong) + } else { + *line = String::from_utf8(bytes).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + Ok(LineRead::Line) + } +} + +/// After [`LineRead::TooLong`]: skip to the next newline so the connection can go on. +pub fn discard_rest_of_line(reader: &mut impl BufRead) -> std::io::Result<()> { + loop { + let buf = reader.fill_buf()?; + if buf.is_empty() { + return Ok(()); + } + if let Some(end) = buf.iter().position(|&b| b == b'\n') { + reader.consume(end + 1); + return Ok(()); + } + let n = buf.len(); + reader.consume(n); + } +} + +/// A fresh token: 32 bytes from the OS randomness source (`getrandom::fill`) as lower-case hex. +/// A failure is [`AutomationError::Io`] with `cannot generate control token: {e}` (PhotoCraft +/// uses its app-level `Other` variant for it). +pub fn generate_token() -> Result { + random_hex("control token") +} + +/// A fresh nonce for challenge authentication ([`CHALLENGE_METHOD`]), made as +/// [`generate_token`] makes a token. +pub fn generate_nonce() -> Result { + random_hex("authentication nonce") +} + +/// 32 bytes from the OS randomness source as lower-case hex. +fn random_hex(what: &str) -> Result { + let mut bytes = [0u8; TOKEN_HEX_LEN / 2]; + getrandom::fill(&mut bytes).map_err(|e| AutomationError::Io(format!("cannot generate {what}: {e}")))?; + Ok(hex(&bytes)) +} + +fn hex(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for &byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + out +} + +/// Whether `s` has the shape of a token or a nonce: exactly [`TOKEN_HEX_LEN`] hex digits. +pub fn is_hex256(s: &str) -> bool { + s.len() == TOKEN_HEX_LEN && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Exactly [`TOKEN_HEX_LEN`] ASCII hex digits, upper or lower case; otherwise +/// `BadRequest("control token must contain exactly 64 hexadecimal characters")`. +pub fn validate_token(token: &str) -> Result<(), AutomationError> { + if !is_hex256(token) { + return Err(AutomationError::BadRequest("control token must contain exactly 64 hexadecimal characters".into())); + } + Ok(()) +} + +/// Constant-time comparison (no early exit on a mismatching byte); false unless both are +/// [`TOKEN_HEX_LEN`] long. Only `A`–`Z` fold to lower case, so a client sending the token as it +/// was configured authenticates against the server's lower-cased copy, and a non-hex byte never +/// matches a hex digit. +pub fn token_matches(expected: &str, supplied: &str) -> bool { + if expected.len() != TOKEN_HEX_LEN || supplied.len() != TOKEN_HEX_LEN { + return false; + } + expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a.to_ascii_lowercase() ^ b.to_ascii_lowercase())) == 0 +} + +/// Which side of the challenge handshake a proof comes from. Each side's proof is keyed by the +/// token over both nonces under its own label, so one side's proof never passes for the other's. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProofRole { + /// The server's answer to `auth.challenge` (`serverProof`). + Server, + /// The client's `auth {proof}`. + Client, +} + +/// HMAC-SHA256 keyed by the lower-cased token over `

, +} + +impl FrameTrace { + /// Reads the environment variable `var` (off on wasm, which has no environment). + pub fn from_env(var: &str) -> Self { + #[cfg(not(target_arch = "wasm32"))] + if let Some(v) = std::env::var_os(var) { + return Self::from_value(&v.to_string_lossy()); + } + let _ = var; + Self::default() + } + + /// `v` trimmed: `""`, `"0"`, `"off"` or `"false"` is off; `"1"`, `"stderr"` or `"true"` prints + /// summaries; anything else is a CSV path. Always off on wasm (no clock there). + pub fn from_value(v: &str) -> Self { + let v = v.trim(); + let output = match v { + _ if cfg!(target_arch = "wasm32") => Output::Off, + "" | "0" | "off" | "false" => Output::Off, + "1" | "stderr" | "true" => Output::Stderr, + path => Output::Csv(path.into()), + }; + Self { output, ..Default::default() } + } + + /// Whether the trace records frames. + pub fn is_on(&self) -> bool { + !matches!(self.output, Output::Off) + } + + /// Turn summaries on or off (the control channel's `ui.set`); never sets a path. + pub fn set_on(&mut self, on: bool) { + let last = self.last.take(); + *self = Self { last, ..Self::from_value(if on { "1" } else { "off" }) }; + } + + /// Record `stages` when `in_gesture`; the first frame after a gesture ends summarises it, + /// with `backend` named in the summary. + pub fn frame(&mut self, stages: &FrameStages, in_gesture: bool, backend: impl FnOnce() -> String) { + if !self.is_on() { + return; + } + let interval = self.last_start.map_or(0.0, |t| stages.t - t); + self.last_start = Some(stages.t); + if in_gesture || stages.gesture_ms > 0.0 { + // The first frame of a gesture does not follow a gesture frame: its interval is idle time. + let interval = if self.rows.is_empty() { 0.0 } else { interval }; + self.rows.push(Row::from_stages(stages, interval)); + } else if !self.rows.is_empty() { + self.finish(backend()); + } + } + + fn finish(&mut self, backend: String) { + let rows = std::mem::take(&mut self.rows); + self.gestures += 1; + let col = |g: fn(&Row) -> Option| percentiles(rows.iter().filter_map(g).collect()); + let summary = Summary { + frames: rows.len(), + backend, + interval: col(|r| (r.interval > 0.0).then_some(r.interval)), + moves: col(|r| Some(r.moves as f64)), + gesture: col(|r| Some(r.gesture)), + canvas: col(|r| Some(r.canvas)), + ui: col(|r| Some(r.ui)), + // A frame's cpu_prev belongs to the frame before it, so pair it with that interval. + cpu: percentiles(rows.iter().skip(1).filter_map(|r| r.cpu_prev).collect()), + wait: percentiles(rows.windows(2).filter_map(|w| Some((w[1].interval - w[1].cpu_prev?).max(0.0))).collect()), + }; + eprintln!("{}", summary.line()); + #[cfg(not(target_arch = "wasm32"))] + if let Output::Csv(path) = &self.output + && let Err(e) = append_csv(path, self.gestures, &rows) + { + eprintln!("frame trace: can't write {}: {e}", path.display()); + } + self.last = Some(summary); + } +} + +/// `[p50, p95]` of `v`, nearest rank, rounded to 0.01; zeros when empty. +pub fn percentiles(mut v: Vec) -> [f64; 2] { + v.retain(|x| x.is_finite()); + if v.is_empty() { + return [0.0, 0.0]; + } + v.sort_by(f64::total_cmp); + let at = |p: f64| v.get(((p * (v.len() - 1) as f64).round() as usize).min(v.len() - 1)).copied().unwrap_or(0.0); + let r = |x: f64| (x * 100.0).round() / 100.0; + [r(at(0.5)), r(at(0.95))] +} + +/// The CSV text for `rows` of gesture number `gesture` (with the header when `header`). +fn csv(gesture: usize, rows: &[Row], header: bool) -> String { + let mut s = String::new(); + if header { + s.push_str("gesture,t_ms,interval_ms,moves,gesture_ms,canvas_ms,ui_ms,cpu_prev_ms\n"); + } + for r in rows { + let cpu = r.cpu_prev.map_or(String::new(), |c| format!("{c:.3}")); + let _ = writeln!(s, "{gesture},{:.3},{:.3},{},{:.3},{:.3},{:.3},{cpu}", r.t, r.interval, r.moves, r.gesture, r.canvas, r.ui); + } + s +} + +#[cfg(not(target_arch = "wasm32"))] +fn append_csv(path: &std::path::Path, gesture: usize, rows: &[Row]) -> std::io::Result<()> { + use std::io::Write as _; + let header = std::fs::metadata(path).map_or(true, |m| m.len() == 0); + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?; + f.write_all(csv(gesture, rows, header).as_bytes()) +} diff --git a/crates/automation/src/ui/actions/body.rs b/crates/automation/src/ui/actions/body.rs new file mode 100644 index 0000000000..a38f637be5 --- /dev/null +++ b/crates/automation/src/ui/actions/body.rs @@ -0,0 +1,400 @@ +//! The body above the footer: the empty notice, Button Mode's buttons or the tree, and the mapping +//! of the list's events to the panel's. + +use craft_behavior::{ColumnWidth, EditEvent, IconId, Mixed, Selection}; +use craft_theme::variant::Tone; +use craft_ui::buttons::Button; +use craft_ui::contract::{ + Bind, CollectionEvent, ColumnKey, ColumnSpec, ListDrag, OpenChange, Outcome as _, Pad, Props as _, ReorderMove, ReorderRule, Scroll, SelectMode, + Show as _, ShowCollection as _, ShowContainer as _, Sizing, SpaceAction, ToggleColumn, ToggleEdit, request_rename, +}; +use craft_ui::display::Text; +use craft_ui::layout_components::{Row, Stack}; +use craft_ui::list::{List, ListWords}; +use craft_ui::notices::{Notice, NoticeIcon, NoticeLayout}; +use craft_ui::primitives::{HAlign, IconSpec}; +use craft_ui::runtime::env::{Env, Label}; +use egui::{Id, Response, Ui}; + +use super::menu::OpenMenu; +use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session, StepCells}; +use super::rows::{ActionRows, DIALOG_COLUMN, INCLUDE_COLUMN, NAME_COLUMN, build_row, cells}; +use super::words::ActionsWords; +use crate::actions::{ActionList, moved_index}; + +/// What the pieces of the panel read: the app's side, the words and the list's id. +#[derive(Clone, Copy)] +pub(super) struct Body<'a> { + pub(super) list: &'a ActionList, + pub(super) host: Option<&'a dyn ActionsHost>, + pub(super) words: &'a ActionsWords, + pub(super) list_words: &'a ListWords, + pub(super) env: &'a Env, + /// The id the tree's list shows under, which its drags carry as `ListDrag::list`. + pub(super) list_id: Id, + /// Which step cells the rows show. + pub(super) step_cells: StepCells, +} + +/// Where a moved row goes. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ActionPlace { + /// An action dropped at list index `index` (after its removal), into `set` (`None`: loose). + #[non_exhaustive] + Action { + /// The index in [`ActionList::actions`] after the removal. + index: usize, + /// The set it lands in. + set: Option, + }, + /// A step dropped at position `index` of action `action`. + #[non_exhaustive] + Step { + /// The action it lands in. + action: usize, + /// The position after the removal. + index: usize, + }, +} + +impl ActionPlace { + /// An action dropped at list index `index` (after its removal), into `set` (`None`: loose). + pub fn action(index: usize, set: Option) -> Self { + Self::Action { index, set } + } + + /// A step dropped at position `index` of action `action`. + pub fn step(action: usize, index: usize) -> Self { + Self::Step { action, index } + } +} + +/// A row moved by a drag or by key. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct ActionMove { + /// The row that moved. + pub row: ActionSelection, + /// Where it lands. + pub place: ActionPlace, +} + +/// What the body returns. +pub(super) struct BodyOutput { + pub(super) events: Vec, + pub(super) response: Response, + /// The selected row and the range of sets the list ended on, for the caller to store after the container; `None` + /// when the body did not show the tree. + pub(super) selected: Option<(Option, Vec)>, +} + +/// The part of the panel above the footer: the empty notice, Button Mode's buttons or the tree. +pub(super) fn show_body(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, session: &mut Session, rename: Option) -> BodyOutput { + let Body { list, host, words, .. } = *body; + if list.actions().is_empty() && list.sets().is_empty() { + let icon = NoticeIcon::Custom(IconSpec::svg(craft_behavior::IconId::new("circle"))); + let out = Notice::new(Tone::Neutral, words.empty.clone()).layout(NoticeLayout::Centred).icon(icon).show(ui); + return BodyOutput { events: Vec::new(), response: out.response().clone(), selected: None }; + } + if state.settings.button_mode && host.and_then(|host| host.recording()).is_none() { + return show_buttons(ui, body); + } + show_tree(ui, body, state, session, rename) +} + +/// Button Mode's body: each action of `list` in display order as a full-width button in its colour, its name at the +/// reading start, set names between, inset like the names; a click, not a double click's second, reports `Play`. +fn show_buttons(ui: &mut Ui, body: &Body<'_>) -> BodyOutput { + let list = body.list; + let mut events = Vec::new(); + let order = list.display_order(); + let mut shown: Vec<(Option<&str>, Vec)> = vec![(None, order.iter().copied().filter(|&index| list.set_of(index).is_none()).collect())]; + for set in list.sets() { + shown.push((Some(set), order.iter().copied().filter(|&index| list.set_of(index) == Some(set)).collect())); + } + let shown_buttons = Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { + for (set, actions) in &shown { + if let Some(name) = set { + Row::new().pad(Pad::Control).show(ui, |ui, _| { + Text::new((*name).to_owned()).show(ui); + }); + } + for &index in actions { + let Some(action) = list.action(index) else { continue }; + let mut button = Button::new(action.name.clone()).sizing(Sizing::FillWidth).align(HAlign::Start); + if let Some(color) = action.color.label_color() { + button = button.tint(color.fill()); + } + let response = button.show(ui); + if response.clicks == 1 { + events.push(ActionsEvent::Play { action: index, from: 0 }); + } + } + } + }); + BodyOutput { events, response: shown_buttons.output, selected: None } +} + +/// The column of a toggle edit, when it names one. +fn toggle_column(edit: &EditEvent>) -> Option<&ColumnKey> { + match edit { + EditEvent::Update { value: cell, .. } | EditEvent::Set { after: cell, .. } | EditEvent::Commit { after: cell, .. } => Some(&cell.column), + EditEvent::Begin { before: Mixed::Same(cell), .. } | EditEvent::Cancel { before: Some(Mixed::Same(cell)), .. } => Some(&cell.column), + _ => None, + } +} + +/// The tree on a [`List`] in tree mode, and the events of what happened on it. +fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, session: &mut Session, rename: Option) -> BodyOutput { + let Body { list, host, words, list_id, .. } = *body; + let editable = !host.is_some_and(|host| host.playing()); + let recording = host.and_then(|host| host.recording()); + let rows = ActionRows::build(list, state, host); + let order = rows.keys(); + let items = if state.selected_sets.is_empty() { + state.selected.iter().cloned().collect() + } else { + state.selected_sets.iter().cloned().map(ActionSelection::Set).collect() + }; + let mut selection = Selection::new(items, state.selected.clone(), state.selected.clone()); + if let Some(index) = rename.filter(|_| editable) { + request_rename(ui.ctx(), list_id, &ActionSelection::Action(index)); + } + let mut columns = vec![ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable())]; + if body.step_cells == StepCells::IncludeAndDialog { + columns.push(ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note"))); + } + columns.push(ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0))); + let mut widget = List::new(words.name.clone()) + .id(list_id) + .tree(true) + .select(SelectMode::Multi) + .allow_empty(true) + .space(SpaceAction::ToggleCell) + .deletable(true) + .rename(true) + .rename_column(NAME_COLUMN) + .columns(columns) + .selection(Bind::bound(&mut selection)) + .can_rename(|key| editable && matches!(key, ActionSelection::Action(_))) + .drag_payload(|drag: &ListDrag| Some(drag.clone())); + if editable { + widget = widget.reorder(ReorderRule::new().into_groups()).accepts(|drag: &ListDrag, _over, insert| { + let moved_before = order[..insert.min(order.len())].iter().filter(|key| drag.keys.contains(key)).count(); + let mv = ReorderMove::new(drag.grabbed.clone(), drag.keys.clone(), insert.saturating_sub(moved_before), false); + place_of(list, &order, &mv, true).is_some() + }); + } + if let Some(key) = reveal_key(session, list, host, &order) { + widget = widget.reveal(key); + } + let shown: &ActionsPanelState = state; + let out = widget.show_items(ui, &rows, &mut |key, item| { + let mut row = build_row(body, shown, key).cells(item.cells()).state(item.row.clone()).depth(rows.depth_at(item.at)); + for cell in cells(body, key) { + row = row.toggle(cell); + } + if rows.is_group(item.at) { row.group(rows.is_open(item.at)) } else { row } + }); + + let mut events = Vec::new(); + let mut moves = Vec::new(); + for event in out.events { + match event { + CollectionEvent::Open(change) => apply_open(state, list, &change), + CollectionEvent::Activate(key) => match key { + ActionSelection::Action(action) if host.is_some() => events.push(ActionsEvent::Play { action, from: 0 }), + ActionSelection::Set(ref name) => { + let open = state.settings.collapsed_sets.contains(name); + apply_open(state, list, &OpenChange::new(key, open)); + } + _ => {} + }, + CollectionEvent::Toggle(edit) if editable => { + let sweep = if toggle_column(&edit) == Some(&INCLUDE_COLUMN) { &mut session.include } else { &mut session.dialog }; + events.extend(sweep.feed(&edit).map(ActionsEvent::Toggle)); + } + CollectionEvent::Rename(edit) if editable => { + if let EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } = edit + && let ActionSelection::Action(action) = after.key + { + let text = after.name.trim(); + if !text.is_empty() && list.action(action).is_some_and(|current| current.name != text) { + events.push(ActionsEvent::Rename { action, text: text.to_owned() }); + } + } + } + CollectionEvent::Reorder(EditEvent::Set { after, .. }) if editable => { + if let Some(place) = place_of(list, &order, &after, false) { + moves.push((after.key.clone(), place.clone())); + events.push(ActionsEvent::Reorder(ActionMove { row: after.key, place })); + } + } + CollectionEvent::Delete(keys) if editable => { + if state.selected_sets.is_empty() { + events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + } else if recording.is_none() { + events.push(ActionsEvent::DeleteSets(state.selected_sets.clone())); + } + } + CollectionEvent::ContextMenu(request) => session.menu = OpenMenu::opened(request, list, host), + _ => {} + } + } + let (mut selected, sets) = kept(list, &selection); + for (source, to) in &moves { + selected = selected.map(|selected| remapped(selected, source, to)); + } + BodyOutput { events, response: out.response, selected: Some((selected, sets)) } +} + +/// The selection the panel keeps after the list applied this pass's input: the lead row, and the range of sets in list +/// order when the lead and the range's other end (the anchor) are both set rows. The list's range runs over the shown +/// rows, so one across an expanded set holds that set's action rows too; only the set rows are kept. A lead that is an +/// action or step, or a set reached from one of those, is the whole selection. A range of fewer than two sets is none. +fn kept(list: &ActionList, selection: &Selection) -> (Option, Vec) { + let lead = selection.lead.clone().filter(|lead| selection.items.contains(lead)); + let range = matches!((&lead, &selection.anchor), (Some(ActionSelection::Set(_)), Some(ActionSelection::Set(_)))); + let sets: Vec = if range { + let chosen = |set: &str| selection.items.iter().any(|key| matches!(key, ActionSelection::Set(name) if name == set)); + list.sets().into_iter().filter(|set| chosen(set)).map(str::to_owned).collect() + } else { + Vec::new() + }; + (lead, if sets.len() > 1 { sets } else { Vec::new() }) +} + +/// The `Delete` event for `selected`: a step always; a set or an action not while recording. +pub(super) fn delete_event(selected: &ActionSelection, recording: bool) -> Option { + (!recording || matches!(selected, ActionSelection::Step(..))).then(|| ActionsEvent::Delete(selected.clone())) +} + +/// Opens or closes what `change` names in `state`: an action's steps, a set's actions, or with +/// `all` every one of them. +fn apply_open(state: &mut ActionsPanelState, list: &ActionList, change: &OpenChange) { + if change.all { + if change.open { + state.expanded.extend(list.actions().iter().map(|action| action.name.clone())); + state.settings.collapsed_sets.clear(); + } else { + state.expanded.clear(); + state.settings.collapsed_sets = list.sets().into_iter().map(str::to_owned).collect(); + } + return; + } + match &change.key { + ActionSelection::Action(index) => { + if let Some(action) = list.action(*index) { + if change.open { + state.expanded.insert(action.name.clone()); + } else { + state.expanded.remove(&action.name); + } + } + } + ActionSelection::Set(name) => { + state.settings.collapsed_sets.retain(|set| set != name); + if !change.open { + state.settings.collapsed_sets.push(name.clone()); + } + } + ActionSelection::Step(..) => {} + } +} + +/// The row to scroll into view while recording: the latest step, whenever the recording action or +/// its step count differs from the last pass; `None` otherwise. +fn reveal_key(session: &mut Session, list: &ActionList, host: Option<&dyn ActionsHost>, order: &[ActionSelection]) -> Option { + let Some(recording) = host.and_then(|host| host.recording()) else { + session.revealed = None; + return None; + }; + let total = list.step_count(recording) + host.map_or(0, |host| host.pending_steps(recording).len()); + if session.revealed == Some((recording, total)) { + return None; + } + session.revealed = Some((recording, total)); + let key = if total > 0 { ActionSelection::Step(recording, total - 1) } else { ActionSelection::Action(recording) }; + order.contains(&key).then_some(key) +} + +/// Where the move `mv` of the displayed rows `order` lands in the list, or `None` when the tree +/// does not take it (more than one row, a copy, or a place that is no action's or step's): +/// - an action lands before an action that is next, after the action that is before, as the first +/// of the set it is dropped into, or at the end of the set before a later set (where the drop +/// line is drawn); before the first set it is loose; +/// - a step lands in the action it is dropped into or beside, at the position among that action's +/// steps. +/// +/// `relaxed` ignores the group the list reports for the place, for the check while the pointer is +/// still moving, when the list has no group to report yet. +pub(super) fn place_of(list: &ActionList, order: &[ActionSelection], mv: &ReorderMove, relaxed: bool) -> Option { + if mv.copy || mv.keys.len() != 1 { + return None; + } + let moved = &mv.keys[0]; + let remaining: Vec<&ActionSelection> = order.iter().filter(|key| *key != moved).collect(); + let to = mv.to.min(remaining.len()); + let next = remaining.get(to).copied(); + let prev = to.checked_sub(1).map(|at| remaining[at]); + match moved { + ActionSelection::Action(from) => { + let len = list.actions().len(); + let parent_set = match &mv.parent { + Some(ActionSelection::Set(name)) => Some(name.as_str()), + Some(_) => return None, + None => None, + }; + let end_of = |set: &str| list.actions().iter().rposition(|action| action.set.as_deref() == Some(set)).map_or(len, |last| last + 1); + let (at, set) = match (prev, next) { + (Some(ActionSelection::Set(header)), _) if parent_set == Some(header.as_str()) => { + let first = list.actions().iter().position(|action| action.set.as_deref() == Some(header.as_str())); + (first.unwrap_or(len), Some(header.clone())) + } + (_, Some(ActionSelection::Action(over))) if relaxed || list.set_of(*over) == parent_set => { + (*over, list.set_of(*over).map(str::to_owned)) + } + (Some(ActionSelection::Action(over) | ActionSelection::Step(over, _)), _) => (over + 1, list.set_of(*over).map(str::to_owned)), + (Some(ActionSelection::Set(header)), _) => (end_of(header), Some(header.clone())), + (None, _) => (0, None), + }; + Some(ActionPlace::Action { index: at - usize::from(*from < at), set }) + } + ActionSelection::Step(from, step) => { + if *step >= list.step_count(*from) { + return None; + } + let action = match (&mv.parent, prev) { + (Some(ActionSelection::Action(action)), _) => *action, + (Some(_), _) => return None, + (None, Some(ActionSelection::Action(action) | ActionSelection::Step(action, _))) => *action, + (None, _) => return None, + }; + let held = list.step_count(action) - usize::from(action == *from); + let slot = remaining[..to].iter().filter(|key| matches!(key, ActionSelection::Step(owner, _) if *owner == action)).count(); + Some(ActionPlace::Step { action, index: slot.min(held) }) + } + ActionSelection::Set(_) => None, + } +} + +/// Where `selected` is after `source` moved to `to`: the moved row and the rows it passed follow +/// the list's own shifts. +fn remapped(selected: ActionSelection, source: &ActionSelection, to: &ActionPlace) -> ActionSelection { + match (source, to) { + (ActionSelection::Action(from), ActionPlace::Action { index, .. }) => match selected { + ActionSelection::Action(at) => ActionSelection::Action(moved_index(at, *from, *index)), + ActionSelection::Step(at, step) => ActionSelection::Step(moved_index(at, *from, *index), step), + set @ ActionSelection::Set(_) => set, + }, + (ActionSelection::Step(from, moved), ActionPlace::Step { action: into, index }) => match selected { + ActionSelection::Step(at, step) if at == *from && step == *moved => ActionSelection::Step(*into, *index), + ActionSelection::Step(at, step) if at == *from && from == into => ActionSelection::Step(at, moved_index(step, *moved, *index)), + ActionSelection::Step(at, step) if at == *from && step > *moved => ActionSelection::Step(at, step - 1), + ActionSelection::Step(at, step) if at == *into && step >= *index => ActionSelection::Step(at, step + 1), + other => other, + }, + _ => selected, + } +} diff --git a/crates/automation/src/ui/actions/footer.rs b/crates/automation/src/ui/actions/footer.rs new file mode 100644 index 0000000000..be4194f06e --- /dev/null +++ b/crates/automation/src/ui/actions/footer.rs @@ -0,0 +1,123 @@ +//! The Actions footer: Stop, Record, Play, New Set, New Action, Delete and the Button Mode toggle. + +use craft_behavior::IconId; +use craft_theme::variant::Tone; +use craft_ui::contract::ListDrag; +use craft_ui::primitives::IconSpec; +use craft_ui::sections::{FooterAction, FooterBar}; +use egui::Ui; + +use super::body::{Body, delete_event}; +use super::panel::{ActionSelection, ActionsEvent, ActionsPanelState}; +use crate::actions::ActionList; + +// The footer's buttons from its end edge. +const BUTTON_MODE: usize = 0; +const DELETE: usize = 1; +const NEW_ACTION: usize = 2; +const NEW_SET: usize = 3; +const PLAY: usize = 4; +const RECORD: usize = 5; +const STOP: usize = 6; + +/// The footer under the list, in this order from the start edge, each a Tab stop with its name and tooltip: +/// +/// | Button | Icon | Reports | Enabled | +/// |---|---|---|---| +/// | Stop playing/recording | `square` | `StopRecording` | while recording or playing | +/// | Begin recording | `circle`, pressed in the alert tone while recording | `BeginRecording { into: selected action }` | not playing; while recording it stays live and ignores the click | +/// | Play selection | `play` | `Play { action, from }`: the selected action from 0, a selected step's action from that step, else the first action; `PlaySet(name)` for a selected set | some action or a selected set, not recording | +/// | Create new set | `new_folder` | `NewSet` | not recording | +/// | Create new action | `plus` | `BeginRecording { into: None }`; a row of the list dropped on it reports `Duplicate(row)` | not recording; a dropped row is accepted on the same rule | +/// | Delete | `trash` | `Delete(selection)`; a row of the list dropped on it reports `Delete(row)` | a selection, and while recording only a step; a dropped row is accepted on the same rule | +/// | Button Mode | `toggle_right`, pressed | toggles `ActionsSettings::button_mode` in `state` | not recording | +pub(super) fn show_footer(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState) -> Vec { + let Body { list, host, words, list_id, .. } = *body; + let recording = host.and_then(|host| host.recording()); + let playing = host.is_some_and(|host| host.playing()); + let hosted = host.is_some(); + let idle = recording.is_none() && !playing; + let target = play_target(state.selected.as_ref(), list); + let play_set = match state.selected.as_ref() { + Some(ActionSelection::Set(name)) => Some(name.clone()), + _ => None, + }; + let delete = state.selected.as_ref().filter(|_| !playing).and_then(|selected| delete_event(selected, recording.is_some())); + let record_into = selected_action(state.selected.as_ref(), list); + let icon = |name: &'static str| IconSpec::svg(IconId::new(name)); + let mut record = FooterAction::new(icon("circle"), words.record.clone()).enabled(hosted && !playing).pressed(recording.is_some()); + if recording.is_some() { + record = record.tone(Tone::Bad); + } + let actions = [ + FooterAction::new(icon("toggle_right"), words.button_mode.clone()).enabled(idle).pressed(state.settings.button_mode), + FooterAction::new(icon("trash"), words.delete.clone()).enabled(delete.is_some()).takes_drops_disabled(true).accepts_drops( + move |drag: &ListDrag| !playing && drag.list == list_id && delete_event(&drag.grabbed, recording.is_some()).is_some(), + ), + FooterAction::new(icon("plus"), words.new_action.clone()) + .enabled(hosted && idle) + .accepts_drops(move |drag: &ListDrag| !playing && recording.is_none() && drag.list == list_id), + FooterAction::new(icon("new_folder"), words.new_set.clone()).enabled(idle), + FooterAction::new(icon("play"), words.play.clone()).enabled(hosted && idle && (target.is_some() || play_set.is_some())), + record, + FooterAction::new(icon("square"), words.stop.clone()).enabled(hosted && !idle), + ]; + let out = FooterBar::actions(actions).show_footer(ui); + // The footer runs twice per pass: the sizing pass measures it and must report nothing. + if ui.is_sizing_pass() { + return Vec::new(); + } + + let mut events = Vec::new(); + match out.picked { + Some(STOP) => events.push(ActionsEvent::StopRecording), + // Record stays live while recording: it shows the alert state and ignores the click. + Some(RECORD) if idle => events.push(ActionsEvent::BeginRecording { into: record_into }), + Some(PLAY) => { + if let Some(name) = play_set { + events.push(ActionsEvent::PlaySet(name)); + } else if let Some((action, from)) = target { + events.push(ActionsEvent::Play { action, from }); + } + } + Some(NEW_SET) => events.push(ActionsEvent::NewSet), + Some(NEW_ACTION) => events.push(ActionsEvent::BeginRecording { into: None }), + Some(DELETE) => events.extend(delete), + Some(BUTTON_MODE) => state.settings.button_mode = !state.settings.button_mode, + _ => {} + } + if let Some(dropped) = &out.dropped + && dropped.index == DELETE + && let Some(drag) = dropped.payload::>() + { + events.extend(delete_event(&drag.grabbed, recording.is_some())); + } + if let Some(dropped) = &out.dropped + && dropped.index == NEW_ACTION + && let Some(drag) = dropped.payload::>() + { + events.push(ActionsEvent::Duplicate(drag.grabbed.clone())); + } + events +} + +/// What Play plays: the selected action from its first step, a selected step's action from that +/// step, else the first action. `None` without actions and for a selected set (Play reports +/// `PlaySet` for it). +pub(super) fn play_target(selected: Option<&ActionSelection>, list: &ActionList) -> Option<(usize, usize)> { + let len = list.actions().len(); + match selected { + Some(ActionSelection::Set(_)) => None, + Some(&ActionSelection::Action(action)) if action < len => Some((action, 0)), + Some(&ActionSelection::Step(action, step)) if action < len => Some((action, step)), + _ => (len > 0).then_some((0, 0)), + } +} + +/// The action the selection is, or a selected step belongs to. +pub(super) fn selected_action(selected: Option<&ActionSelection>, list: &ActionList) -> Option { + match selected { + Some(&ActionSelection::Action(action) | &ActionSelection::Step(action, _)) if action < list.actions().len() => Some(action), + _ => None, + } +} diff --git a/crates/automation/src/ui/actions/menu.rs b/crates/automation/src/ui/actions/menu.rs new file mode 100644 index 0000000000..74add10436 --- /dev/null +++ b/crates/automation/src/ui/actions/menu.rs @@ -0,0 +1,409 @@ +//! The panel menu's commands and the row context menus. + +use craft_keymap::Platform; +use craft_ui::contract::{CommandSet, ContextMenuRequest, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::Divider; +use craft_ui::list::label_color_label; +use craft_ui::menu::{Menu, MenuItem, PanelRow}; +use craft_ui::runtime::commands::{CommandRef, CommandState}; +use craft_ui::runtime::env::Label; +use egui::{Response, Ui}; + +use super::body::{Body, delete_event}; +use super::footer::{play_target, selected_action}; +use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session, ShortcutChoice}; +use crate::actions::{ActionColor, ActionList}; + +/// What the app knows that the menu's states depend on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct ActionsMenuFacts { + /// An action is recording. + pub recording: bool, + /// A path is selected in the document. + pub path_selected: bool, + /// Playback is waiting (Step by Step, Pause For). + pub waiting: bool, + /// Allow Tool Recording is on. + pub tool_recording: bool, +} + +impl ActionsMenuFacts { + /// No fact set. + pub fn new() -> Self { + Self::default() + } + + /// An action is recording. + pub fn recording(mut self, recording: bool) -> Self { + self.recording = recording; + self + } + + /// A path is selected in the document. + pub fn path_selected(mut self, path_selected: bool) -> Self { + self.path_selected = path_selected; + self + } + + /// Playback is waiting. + pub fn waiting(mut self, waiting: bool) -> Self { + self.waiting = waiting; + self + } + + /// Allow Tool Recording is on. + pub fn tool_recording(mut self, tool_recording: bool) -> Self { + self.tool_recording = tool_recording; + self + } +} + +/// The commands of the Actions panel: its panel-menu rows. They are the app's commands: the app +/// gives each its state with [`state`](ActionsPanelCommands::state) and runs the chosen one with +/// [`run`](ActionsPanelCommands::run). +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "actionsPanel")] +#[non_exhaustive] +pub enum ActionsPanelCommands { + /// Ask for a name, then record a new action. + #[command(label = "New Action…")] + NewAction, + /// Ask for a name, then create a set. + #[command(label = "New Set…")] + NewSet, + /// The options of the selected action's set. + #[command(label = "Set Options…")] + SetOptions, + /// Play the selection. + #[command(label = "Play")] + Play, + /// Record into the selected action. + #[command(label = "Start Recording")] + StartRecording, + /// Stop recording. + #[command(label = "Stop Recording")] + StopRecording, + /// Delete the selection. + #[command(label = "Delete")] + Delete, + /// Insert a stop after the selection. + #[command(label = "Insert Stop…")] + InsertStop, + /// Run an action over many files. + #[command(label = "Batch…")] + Batch, + /// Remove every action and set. + #[command(label = "Clear All Actions")] + ClearAll, + /// Put back the app's starting sets, in place of the list or added to it. + #[command(label = "Reset Actions…")] + Reset, + /// Load actions from a file. + #[command(label = "Load Actions…")] + Load, + /// Replace every action with the actions of a file. + #[command(label = "Replace Actions…")] + Replace, + /// Save every action to a file. + #[command(label = "Save Actions…")] + Save, + /// Show each action as a button. + #[command(label = "Button Mode")] + ButtonMode, + /// Duplicate the selected action, step or set. + #[command(label = "Duplicate")] + Duplicate, + /// Replace the selected step with a new recording. + #[command(label = "Record Again")] + RecordAgain, + /// Insert a menu item as a step after the selection. + #[command(label = "Insert Menu Item…")] + InsertMenuItem, + /// Insert a path as a step after the selection. + #[command(label = "Insert Path")] + InsertPath, + /// The playback options. + #[command(label = "Playback Options…")] + PlaybackOptions, + /// Whether tools are recorded as steps. + #[command(label = "Allow Tool Recording", kind = "toggle")] + ToolRecording, +} + +/// What a panel-menu command asks of the app, from [`ActionsPanelCommands::run`]. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ActionsMenuAction { + /// The command is one of the panel's events. + Event(ActionsEvent), + /// Button Mode toggled in the state: persist the [`ActionsSettings`](super::ActionsSettings). + SettingsChanged, +} + +/// The set the selection is in: the selected set, or the selected action's (or step's) set. +fn current_set(state: &ActionsPanelState, list: &ActionList) -> Option { + match state.selected.as_ref()? { + ActionSelection::Set(name) => Some(name.clone()), + ActionSelection::Action(index) | ActionSelection::Step(index, _) => list.set_of(*index).map(str::to_owned), + } +} + +impl ActionsPanelCommands { + /// The state of the command for the app's command input: New Action… and New Set… not while + /// recording, Set Options… needs a current set, Play needs an action or a selected set, Batch… + /// a selected or first action, Delete follows the footer's Delete, Duplicate a deletable + /// selection or a set (not while recording), Record Again a selected step (not while + /// recording), Insert Menu Item… and Insert Stop… a selected action or step, Insert Path the + /// same with a path selected, Save an action or a selected set, Clear All an action or a set and + /// Reset and Replace always, all three not while recording or waiting, Playback Options… not while + /// waiting, Allow Tool Recording is checked with the fact, Start Recording is off while + /// recording and Stop Recording only on while it runs, and Button Mode is checked with the + /// state's setting and off while recording. + pub fn state(self, panel: &ActionsPanelState, list: &ActionList, facts: ActionsMenuFacts) -> CommandState { + let recording = facts.recording; + let any = !list.actions().is_empty(); + let on_row = matches!(panel.selected, Some(ActionSelection::Action(_) | ActionSelection::Step(..))); + let set_selected = matches!(&panel.selected, Some(ActionSelection::Set(name)) if list.sets().contains(&name.as_str())); + let state = CommandState::new(); + // The whole-list commands wait while a recording or a paused playback holds an action. + let library_idle = !recording && !facts.waiting; + match self { + ActionsPanelCommands::NewAction | ActionsPanelCommands::NewSet | ActionsPanelCommands::StartRecording => state.enabled(!recording), + ActionsPanelCommands::SetOptions => state.enabled(current_set(panel, list).is_some()), + ActionsPanelCommands::Play => state.enabled((any || set_selected) && !recording), + ActionsPanelCommands::StopRecording => state.enabled(recording), + ActionsPanelCommands::Delete => { + state.enabled(panel.selected.as_ref().is_some_and(|selected| delete_event(selected, recording).is_some())) + } + ActionsPanelCommands::InsertStop => state.enabled(on_row), + ActionsPanelCommands::Batch => state.enabled(play_target(panel.selected.as_ref(), list).is_some()), + ActionsPanelCommands::Save => state.enabled(any || set_selected), + ActionsPanelCommands::Load => state, + ActionsPanelCommands::ClearAll => state.enabled(library_idle && (any || !list.sets().is_empty())), + ActionsPanelCommands::Reset | ActionsPanelCommands::Replace => state.enabled(library_idle), + ActionsPanelCommands::ButtonMode => state.enabled(!recording).checked(panel.settings.button_mode), + ActionsPanelCommands::Duplicate => { + let deletable = panel.selected.as_ref().is_some_and(|selected| delete_event(selected, false).is_some()); + state.enabled(!recording && (deletable || set_selected)) + } + ActionsPanelCommands::RecordAgain => state.enabled(!recording && matches!(panel.selected, Some(ActionSelection::Step(..)))), + ActionsPanelCommands::InsertMenuItem => state.enabled(on_row), + ActionsPanelCommands::InsertPath => state.enabled(on_row && facts.path_selected), + ActionsPanelCommands::PlaybackOptions => state.enabled(!facts.waiting), + ActionsPanelCommands::ToolRecording => state.checked(facts.tool_recording), + } + } + + /// Runs the command: Button Mode toggles it in `panel` and returns + /// [`ActionsMenuAction::SettingsChanged`]; every other command returns its event (New Action… + /// is [`ActionsEvent::NewAction`]; Play plays the selection as the footer's Play does; Delete + /// is refused during a recording as the footer's is). `None` when the command has nothing to + /// do in this state. `facts` is what [`state`](Self::state) was given. + pub fn run(self, panel: &mut ActionsPanelState, list: &ActionList, facts: ActionsMenuFacts) -> Option { + let recording = facts.recording; + let selected = panel.selected.as_ref(); + let event = match self { + ActionsPanelCommands::NewAction => ActionsEvent::NewAction, + ActionsPanelCommands::NewSet => ActionsEvent::NewSet, + ActionsPanelCommands::SetOptions => ActionsEvent::SetOptions(current_set(panel, list)?), + ActionsPanelCommands::Play => { + if let Some(ActionSelection::Set(name)) = selected { + ActionsEvent::PlaySet(name.clone()) + } else { + let (action, from) = play_target(selected, list)?; + ActionsEvent::Play { action, from } + } + } + ActionsPanelCommands::StartRecording => ActionsEvent::BeginRecording { into: selected_action(selected, list) }, + ActionsPanelCommands::StopRecording => ActionsEvent::StopRecording, + ActionsPanelCommands::Delete => delete_event(selected?, recording)?, + ActionsPanelCommands::InsertStop => selected_action(selected, list).map(|_| ActionsEvent::InsertStop)?, + ActionsPanelCommands::Batch => ActionsEvent::Batch(play_target(selected, list)?.0), + ActionsPanelCommands::Load => ActionsEvent::Load, + ActionsPanelCommands::ClearAll => ActionsEvent::ClearAll, + ActionsPanelCommands::Reset => ActionsEvent::Reset, + ActionsPanelCommands::Replace => ActionsEvent::Replace, + ActionsPanelCommands::Save => ActionsEvent::Save { set: None }, + ActionsPanelCommands::ButtonMode => { + panel.settings.button_mode = !panel.settings.button_mode; + return Some(ActionsMenuAction::SettingsChanged); + } + ActionsPanelCommands::Duplicate if recording => return None, + ActionsPanelCommands::Duplicate => ActionsEvent::Duplicate(selected?.clone()), + ActionsPanelCommands::RecordAgain => { + let &ActionSelection::Step(action, step) = selected? else { return None }; + ActionsEvent::RecordAgain { action, step } + } + ActionsPanelCommands::InsertMenuItem => selected_action(selected, list).map(|_| ActionsEvent::InsertMenuItem)?, + ActionsPanelCommands::InsertPath => selected_action(selected, list).map(|_| ActionsEvent::InsertPath)?, + ActionsPanelCommands::PlaybackOptions => ActionsEvent::PlaybackOptions, + ActionsPanelCommands::ToolRecording => ActionsEvent::ToolRecording(!facts.tool_recording), + }; + Some(ActionsMenuAction::Event(event)) + } +} + +/// The rows of the Actions panel's menu, for the dock's `PanelMenu`, in Photoshop's groups: New +/// Action…, New Set…, Set Options…, Duplicate, Delete | Play, Start Recording (Stop Recording +/// while `facts.recording`), Record Again | Insert Menu Item…, Insert Stop…, Insert Path, Batch… | +/// Playback Options…, Allow Tool Recording, Button Mode | Clear All Actions, Reset Actions…, Load +/// Actions…, Replace Actions…, Save Actions…. A row `offered` +/// refuses is left out, and a group left empty loses its separator. +pub fn panel_rows(facts: ActionsMenuFacts, offered: &dyn Fn(ActionsPanelCommands) -> bool) -> Vec { + use ActionsPanelCommands as C; + let record = if facts.recording { C::StopRecording } else { C::StartRecording }; + let groups: [&[C]; 5] = [ + &[C::NewAction, C::NewSet, C::SetOptions, C::Duplicate, C::Delete], + &[C::Play, record, C::RecordAgain], + &[C::InsertMenuItem, C::InsertStop, C::InsertPath, C::Batch], + &[C::PlaybackOptions, C::ToolRecording, C::ButtonMode], + &[C::ClearAll, C::Reset, C::Load, C::Replace, C::Save], + ]; + let mut rows = Vec::new(); + for group in groups { + let shown: Vec = group.iter().copied().filter(|&command| offered(command)).collect(); + if shown.is_empty() { + continue; + } + if !rows.is_empty() { + rows.push(PanelRow::Separator); + } + rows.extend(shown.into_iter().map(|command| PanelRow::Command(CommandRef::from(command)))); + } + rows +} + +/// The shortcut as the context menu has made it so far. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct PendingShortcut { + /// 0 for none, else 1..=15. + key: u8, + shift: bool, + command: bool, +} + +impl PendingShortcut { + fn choice(self) -> Option { + (self.key > 0).then_some(ShortcutChoice { key: self.key, shift: self.shift, command: self.command }) + } +} + +/// The menu a context request opened, kept until the next request. +#[derive(Clone, Debug)] +pub(super) enum OpenMenu { + /// A set's menu. + Set(String), + /// An action's menu, with the shortcut as the menu has made it from the host's. + Action { index: usize, shortcut: PendingShortcut }, +} + +impl OpenMenu { + /// The menu for `request`, starting from the host's shortcut; `None` for a step or an action + /// the list no longer has. + pub(super) fn opened(request: ContextMenuRequest, list: &ActionList, host: Option<&dyn ActionsHost>) -> Option { + match request.key { + ActionSelection::Set(name) => Some(OpenMenu::Set(name)), + ActionSelection::Action(index) => { + let current = host.and_then(|host| host.shortcut(list.action(index)?)); + let shortcut = PendingShortcut { + key: current.map_or(0, |choice| choice.key), + shift: current.is_some_and(|choice| choice.shift), + command: current.is_some_and(|choice| choice.command), + }; + Some(OpenMenu::Action { index, shortcut }) + } + ActionSelection::Step(..) => None, + } + } +} + +/// Shows the menu the last request chose, hanging from `opener` (the list), and reports what its +/// rows ran. Rows that start or change something are off while an action plays or records, as the +/// footer's are; Delete follows the footer's Delete. +/// - On an action: Play and Record; Duplicate and Delete; Action Options… and Batch…. Then +/// Keyboard Shortcuts (a caption), None and F1 to F15 as radio rows, then Shift and Command (Ctrl +/// off macOS) check rows, enabled only with a key; the check rows keep the menu open so both can +/// be ticked, and each tick is reported as it is made with the shortcut as it stands. Last Color: +/// a submenu of None, Red, Orange, Yellow, Green, Blue, Violet and Gray with the current one +/// marked. +/// - On a set: New Action…, New Set…, Duplicate Set and Delete Set; Set Options…; Save Set…. +pub(super) fn show_menu(ui: &mut Ui, body: &Body<'_>, opener: &Response, session: &mut Session) -> Vec { + let Body { list, host, words, list_words, .. } = *body; + let recording = host.is_some_and(|host| host.recording().is_some()); + let playing = host.is_some_and(|host| host.playing()); + let idle = !recording && !playing; + let hosted = host.is_some(); + let deletable = |row: &ActionSelection| delete_event(row, recording).filter(|_| !playing); + let mut events = Vec::new(); + match session.menu.as_mut() { + None => {} + Some(OpenMenu::Set(name)) => { + let set = ActionSelection::Set(name.clone()); + Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| { + let events = &mut events; + event_row(ui, events, &words.menu_new_action, (hosted && idle).then_some(ActionsEvent::NewAction)); + event_row(ui, events, &words.menu_new_set, idle.then_some(ActionsEvent::NewSet)); + event_row(ui, events, &words.duplicate_set, idle.then(|| ActionsEvent::Duplicate(set.clone()))); + event_row(ui, events, &words.delete_set, deletable(&set)); + Divider::horizontal().show(ui); + event_row(ui, events, &words.set_options, Some(ActionsEvent::SetOptions(name.clone()))); + Divider::horizontal().show(ui); + event_row(ui, events, &words.save_set, Some(ActionsEvent::save(Some(name.clone())))); + }); + } + Some(OpenMenu::Action { index, shortcut }) => { + let (action, current) = (*index, list.action(*index).map(|held| held.color).unwrap_or_default()); + let selection = ActionSelection::Action(action); + Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| { + event_row(ui, &mut events, &words.menu_play, (hosted && idle).then(|| ActionsEvent::play(action, 0))); + event_row(ui, &mut events, &words.menu_record, (hosted && idle).then(|| ActionsEvent::begin_recording(Some(action)))); + Divider::horizontal().show(ui); + event_row(ui, &mut events, &words.duplicate, idle.then(|| ActionsEvent::Duplicate(selection.clone()))); + event_row(ui, &mut events, &words.delete, deletable(&selection)); + Divider::horizontal().show(ui); + event_row(ui, &mut events, &words.action_options, Some(ActionsEvent::ActionOptions(action))); + event_row(ui, &mut events, &words.batch, Some(ActionsEvent::Batch(action))); + Divider::horizontal().show(ui); + MenuItem::new(words.keyboard_shortcuts.clone()).enabled(false).show(ui); + if MenuItem::new(words.none.clone()).radio_mark(shortcut.key == 0).show(ui).ran { + shortcut.key = 0; + events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); + } + for key in 1..=15u8 { + if MenuItem::new(format!("F{key}")).radio_mark(shortcut.key == key).show(ui).ran { + shortcut.key = key; + events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); + } + } + let has_key = shortcut.key > 0; + if MenuItem::new(words.shift.clone()).check(shortcut.shift).keep_open(true).enabled(has_key).show(ui).ran { + shortcut.shift = !shortcut.shift; + events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); + } + let modifier = if Platform::current().is_mac() { &words.command } else { &words.ctrl }; + if MenuItem::new(modifier.clone()).check(shortcut.command).keep_open(true).enabled(has_key).show(ui).ran { + shortcut.command = !shortcut.command; + events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); + } + Divider::horizontal().show(ui); + Menu::submenu_row(ui, words.color.clone(), |ui, _| { + for each in ActionColor::ALL { + let name = label_color_label(each.label_color(), list_words); + if MenuItem::new(name).radio_mark(each == current).show(ui).ran { + events.push(ActionsEvent::SetColor { action, color: each }); + } + } + }); + }); + } + } + events +} + +/// A row of a row menu, enabled while it has an event, which it reports when it runs. +fn event_row(ui: &mut Ui, events: &mut Vec, label: &Label, event: Option) { + if MenuItem::new(label.clone()).enabled(event.is_some()).show(ui).ran { + events.extend(event); + } +} diff --git a/crates/automation/src/ui/actions/mock.rs b/crates/automation/src/ui/actions/mock.rs new file mode 100644 index 0000000000..c708b664e8 --- /dev/null +++ b/crates/automation/src/ui/actions/mock.rs @@ -0,0 +1,83 @@ +//! `FakeActionsHost` and sample lists for stories and tests. + +use std::collections::BTreeMap; + +use serde_json::Value; + +use super::{ActionsHost, ShortcutChoice}; +use crate::actions::{Action, ActionList, ActionStep, ActionsFile}; + +/// The app's side for stories and tests: step labels by command id (a command without one shows as +/// `command_prefix` and the id), the recording and its pending steps, the playing flag and +/// shortcuts by action name. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct FakeActionsHost { + /// Step labels by command id. + pub step_labels: BTreeMap, + /// Put before the id of a command without a label. + pub command_prefix: String, + /// The action being recorded into. + pub recording: Option, + /// The steps recorded since the recording started. + pub pending: Vec, + /// An action is playing. + pub playing: bool, + /// Shortcuts by action name. + pub shortcuts: BTreeMap, +} + +impl FakeActionsHost { + /// A host whose labels for commands without one start with `prefix`. + pub fn prefixed(prefix: impl Into) -> Self { + Self { command_prefix: prefix.into(), ..Self::default() } + } +} + +impl ActionsHost for FakeActionsHost { + fn step_label(&self, step: &ActionStep) -> String { + self.step_labels.get(&step.command).cloned().unwrap_or_else(|| format!("{}{}", self.command_prefix, step.command)) + } + + fn shortcut(&self, action: &Action) -> Option { + self.shortcuts.get(&action.name).copied() + } + + fn recording(&self) -> Option { + self.recording + } + + fn pending_steps(&self, action: usize) -> &[ActionStep] { + if self.recording == Some(action) { &self.pending } else { &[] } + } + + fn playing(&self) -> bool { + self.playing + } +} + +/// A step of the command `command` with no parameters. +pub fn step(command: &str) -> ActionStep { + ActionStep::new(command, Value::Null) +} + +/// The action `name` in `set` (`None`: loose) with a step for each of `commands`. +pub fn action(name: &str, set: Option<&str>, commands: &[&str]) -> Action { + let mut action = Action::new(name, commands.iter().map(|command| step(command)).collect()); + action.set = set.map(str::to_owned); + action +} + +/// The list of `actions`. +pub fn list_of(actions: Vec) -> ActionList { + ActionList::from_file(ActionsFile::new(actions, Vec::new())) +} + +/// Sharpen (levels, curves, blur) and Vignette (mask, blur) loose; Glow (glow) in the set Effects. +pub fn sample_list() -> ActionList { + list_of(vec![ + action("Sharpen", None, &["levels", "curves", "blur"]), + action("Vignette", None, &["mask", "blur"]), + action("Glow", Some("Effects"), &["glow"]), + ]) +} diff --git a/crates/automation/src/ui/actions/mod.rs b/crates/automation/src/ui/actions/mod.rs new file mode 100644 index 0000000000..1c9e113e08 --- /dev/null +++ b/crates/automation/src/ui/actions/mod.rs @@ -0,0 +1,31 @@ +//! The Actions panel (F13.06): sets, actions and steps as a tree, the include and dialog cells, +//! rename, drag to move, Button Mode, the footer and the menus. It runs nothing; it reports +//! events. Builds on every target. +//! +//! | Part | Names | +//! |---|---| +//! | The panel | [`ActionsPanel`], [`ActionsPanelOutput`], [`ActionsEvent`], [`ActionMove`], [`ActionPlace`], [`ActionSelection`], [`ShortcutChoice`] | +//! | The app's side | [`ActionsHost`], [`ActionsPanelCommands`], [`ActionsMenuFacts`] and [`panel_rows`] (the panel menu), [`ActionsMenuAction`], [`LibraryPrompt`] (Clear All, Reset, Replace) | +//! | State | [`ActionsPanelState`], [`ActionsSettings`] (persisted) | +//! | Columns and words | [`INCLUDE_COLUMN`], [`DIALOG_COLUMN`], [`ActionsWords`] | + +mod body; +mod footer; +mod menu; +#[cfg(feature = "screen-testing")] +pub mod mock; +pub(crate) mod panel; +mod prompt; +mod rows; +#[cfg(feature = "suite")] +pub(crate) mod stories; +mod words; + +pub use body::{ActionMove, ActionPlace}; +pub use menu::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands, panel_rows}; +pub use panel::{ + ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice, StepCells, +}; +pub use prompt::LibraryPrompt; +pub use rows::{DIALOG_COLUMN, INCLUDE_COLUMN}; +pub use words::ActionsWords; diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs new file mode 100644 index 0000000000..ecdef774e6 --- /dev/null +++ b/crates/automation/src/ui/actions/panel.rs @@ -0,0 +1,479 @@ +//! `ActionsPanel`: the whole panel, its state, output and events. + +use std::cell::RefCell; +use std::collections::BTreeSet; + +use craft_keymap::{Chord, Key, Mods, Platform}; +use craft_ui::contract::{NoValue, Outcome, Props as _, ShowContainer as _, SweepApply}; +use craft_ui::layout_components::Stack; +use craft_ui::list::ListWords; +use craft_ui::runtime::env::Env; +use craft_ui::runtime::memory::Remember as _; +use egui::{Response, Ui}; + +use super::body::{Body, show_body}; +use super::footer::show_footer; +use super::menu::{OpenMenu, show_menu}; +use super::words::ActionsWords; +use crate::actions::{Action, ActionColor, ActionList, ActionStep}; + +use super::body::ActionMove; + +/// What the panel asks of the app while it draws: words and state the list does not hold. +pub trait ActionsHost { + /// A step's label in the tree ("Levels", "Play Action “Sharpen”"), from the app's command + /// catalogue. + fn step_label(&self, step: &ActionStep) -> String; + + /// The action's keyboard shortcut, if it has one (the app's `actions.play:` + /// override). None by default. + fn shortcut(&self, action: &Action) -> Option { + let _ = action; + None + } + + /// The action being recorded into, if a recording runs. None by default. + fn recording(&self) -> Option { + None + } + + /// The steps recorded into `action` but not yet appended to it (the journal since the + /// recording started), shown after its steps. None by default. + fn pending_steps(&self, action: usize) -> &[ActionStep] { + let _ = action; + &[] + } + + /// An action is playing: the panel takes no edits (renames, moves, toggles) while it plays. + /// False by default. + fn playing(&self) -> bool { + false + } +} + +impl ActionsSettings { + /// Settings with Button Mode `button_mode` and `collapsed_sets` shown collapsed. + pub fn new(button_mode: bool, collapsed_sets: Vec) -> Self { + Self { button_mode, collapsed_sets } + } +} + +/// The Actions panel's persisted section: Button Mode and the collapsed sets. +/// Selection and expansion are not persisted. +#[derive( + Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] +#[serde(default, rename_all = "camelCase")] +#[non_exhaustive] +pub struct ActionsSettings { + /// Button Mode: each action is a coloured button that plays it. + pub button_mode: bool, + /// The sets shown collapsed. + pub collapsed_sets: Vec, +} + +/// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at +/// a time) and the list's key. +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] +#[non_exhaustive] +pub enum ActionSelection { + /// The set header of this name. + Set(String), + /// The action at this index. + Action(usize), + /// Step `.1` of action `.0` (pending steps of a recording follow the action's own). + Step(usize, usize), +} + +/// What the panel keeps between passes. The app holds it beside the [`ActionList`]; only +/// `settings` is persisted. +/// +/// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder) +/// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the +/// app clears `selected` (the panel cannot tell which rows the delete removed). +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] +#[non_exhaustive] +pub struct ActionsPanelState { + /// The persisted section. + pub settings: ActionsSettings, + /// The selected row (one at most). + pub selected: Option, + /// The expanded actions, by name (names are unique, so expansion survives moves). + pub expanded: BTreeSet, + /// The sets a shift-click selected, from the current set to the clicked one, in the set order; empty when there is + /// no range. + pub selected_sets: Vec, +} + +/// Which step cells the rows show. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum StepCells { + /// The include cell and the dialog cell. + #[default] + IncludeAndDialog, + /// The include cell only: the dialog column is left out of the cells and the list's columns. + Include, +} + +/// A function-key shortcut chosen in the context menu (Photoshop's Action Options). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct ShortcutChoice { + /// F1 to F15: 1..=15. + pub key: u8, + /// Shift is part of the shortcut. + pub shift: bool, + /// Command (macOS) or Ctrl (elsewhere) is part of it. + pub command: bool, +} + +impl ShortcutChoice { + /// Function key `key` (1 to 15) with the given modifiers. + pub const fn new(key: u8, shift: bool, command: bool) -> Self { + Self { key, shift, command } + } + + /// The shortcut as a row shows it, in the platform's chord text: "F2" and "⇧⌘F3" on macOS, + /// "Ctrl+Shift+F3" elsewhere. + pub fn text(&self) -> String { + self.chord().display(Platform::current()) + } + + /// The shortcut as a keymap chord; a key outside 1..=15 is taken as F12. + fn chord(&self) -> Chord { + let key = match self.key { + 1 => Key::F1, + 2 => Key::F2, + 3 => Key::F3, + 4 => Key::F4, + 5 => Key::F5, + 6 => Key::F6, + 7 => Key::F7, + 8 => Key::F8, + 9 => Key::F9, + 10 => Key::F10, + 11 => Key::F11, + 13 => Key::F13, + 14 => Key::F14, + 15 => Key::F15, + _ => Key::F12, + }; + Chord::new(Mods { cmd: self.command, shift: self.shift, ..Mods::NONE }, key) + } +} + +/// What the user did, in order. Each is one app command (PhotoCraft's `actions.*`); edits that +/// need no app logic are applied by the app with the matching [`ActionList`] call. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ActionsEvent { + /// Play `action` from step `from` (0 for the whole action). + #[non_exhaustive] + Play { + /// The action. + action: usize, + /// The first step. + from: usize, + }, + /// Start recording into `into`, or into a new action when `None` (New Action…, Create new + /// action). + #[non_exhaustive] + BeginRecording { + /// The action to record into. + into: Option, + }, + /// Stop recording or playing. + StopRecording, + /// New Action… from the panel menu: the app asks for a name, then records. + NewAction, + /// New Set… or Create new set: the app asks for a name ([`ActionList::new_set`]). + NewSet, + /// Set Options… for this set. + SetOptions(String), + /// Delete this row ([`ActionList::delete_action`], [`ActionList::delete_step`]; a set deletes + /// its actions, the app confirms). + Delete(ActionSelection), + /// An in-place rename ended with `text` ([`ActionList::rename`]). + #[non_exhaustive] + Rename { + /// The action. + action: usize, + /// The new name, as typed. + text: String, + }, + /// A row was dragged or moved by key to a place: apply it with [`ActionList::move_action`] and + /// [`ActionList::assign_set`] for an action, [`ActionList::move_step`] for a step. + Reorder(ActionMove), + /// A press or sweep on the include or dialog column, as the step to apply to a cell + /// ([`SweepStep`](craft_ui::contract::SweepStep)). `Flip` and `Restore` set the cell to the step's value as the + /// pointer crosses it or Escape cancels the sweep; `ShowOnly` (Alt on the first press of the include column) turns + /// every other include cell off, or on again when it is the only one on; `UndoShowOnly` puts the include cells back + /// as they were before it. The host groups one sweep as one undo step. The cell's column + /// [`INCLUDE_COLUMN`](super::INCLUDE_COLUMN) of a step row is + /// [`ActionList::set_step`], of an action row [`ActionList::set_all`]; + /// [`DIALOG_COLUMN`](super::DIALOG_COLUMN) of a step row is [`ActionList::set_dialog`]. + Toggle(craft_ui::contract::SweepStep), + /// The context menu's Color ([`ActionList::set_color`]). + #[non_exhaustive] + SetColor { + /// The action. + action: usize, + /// The colour. + color: ActionColor, + }, + /// The context menu's Keyboard Shortcuts: a key with its modifiers, or `None` to remove it. + #[non_exhaustive] + AssignShortcut { + /// The action. + action: usize, + /// The shortcut. + choice: Option, + }, + /// Insert Stop… after the selection (the app's dialog). + InsertStop, + /// Batch… with this action (the app's dialog). + Batch(usize), + /// Action Options… from an action's menu: the app's dialog for this action's name, set, function key and colour. + ActionOptions(usize), + /// Load Actions… (the app's file dialog). + Load, + /// Clear All Actions: the app asks with [`LibraryPrompt::ClearAll`](super::LibraryPrompt) and + /// answers OK with [`ActionList::clear_all`]. + ClearAll, + /// Reset Actions…: the app asks with [`LibraryPrompt::Reset`](super::LibraryPrompt), whose + /// Append keeps the list ([`ActionList::reset`]). + Reset, + /// Replace Actions…: the app picks a file, then asks with + /// [`LibraryPrompt::Replace`](super::LibraryPrompt) ([`ActionList::replace_all`]). + Replace, + /// Save Actions…, or Save Set… for one set. + #[non_exhaustive] + Save { + /// The set; `None` for every action. + set: Option, + }, + /// Duplicate this row ([`ActionList::duplicate_action`], [`ActionList::duplicate_step`], + /// [`ActionList::duplicate_set`]): from the menu row or a row dropped on New Action. + Duplicate(ActionSelection), + /// Delete with a range of sets selected: the range, in one event, so the app asks one question. + DeleteSets(Vec), + /// Record Again: replace step `step` of `action` with a new recording + /// ([`ActionList::replace_step`]). + #[non_exhaustive] + RecordAgain { + /// The action. + action: usize, + /// The step. + step: usize, + }, + /// Insert Menu Item… after the selection (the app's dialog). + InsertMenuItem, + /// Insert Path after the selection. + InsertPath, + /// Playback Options… (the app's dialog). + PlaybackOptions, + /// Allow Tool Recording was switched to this value. + ToolRecording(bool), + /// Play every action of the set in order (a selected set; an empty set plays nothing). + PlaySet(String), +} + +impl ActionsEvent { + /// Play `action` from step `from`. + pub fn play(action: usize, from: usize) -> Self { + Self::Play { action, from } + } + + /// Start recording into `into`, or into a new action when `None`. + pub fn begin_recording(into: Option) -> Self { + Self::BeginRecording { into } + } + + /// An in-place rename of `action` ended with `text`. + pub fn rename(action: usize, text: impl Into) -> Self { + Self::Rename { action, text: text.into() } + } + + /// The context menu's Color for `action`. + pub fn set_color(action: usize, color: ActionColor) -> Self { + Self::SetColor { action, color } + } + + /// The context menu's Keyboard Shortcuts for `action`: `choice`, or `None` to remove it. + pub fn assign_shortcut(action: usize, choice: Option) -> Self { + Self::AssignShortcut { action, choice } + } + + /// Save Actions… (`None`) or Save Set… for `set`. + pub fn save(set: Option) -> Self { + Self::Save { set } + } +} + +/// What [`ActionsPanel::show`] returns. +#[derive(Debug)] +#[must_use = "handle the events and save the settings when `settings_changed`"] +#[non_exhaustive] +pub struct ActionsPanelOutput { + /// The panel's area. + pub response: Response, + /// What the user did this pass, in order. + pub events: Vec, + /// The persisted [`ActionsSettings`] changed this pass (Button Mode, a set opened or + /// closed): the app saves them. + pub settings_changed: bool, +} + +impl Outcome for ActionsPanelOutput { + type Value = NoValue; + + fn response(&self) -> &Response { + &self.response + } +} + +/// What the panel keeps between passes, in its root slot. +#[derive(Clone)] +pub(super) struct Session { + /// The menu the last context request chose. + pub(super) menu: Option, + /// The recording action and its row count when the list was last scrolled to the latest step. + pub(super) revealed: Option<(usize, usize)>, + /// The readers of the include and dialog sweeps: Alt on the first press of an include sweep shows only that + /// cell (Photoshop); the dialog column ignores Alt. + pub(super) include: SweepApply, + pub(super) dialog: SweepApply, +} + +impl Default for Session { + fn default() -> Self { + Session { menu: None, revealed: None, include: SweepApply::show_only(), dialog: SweepApply::new() } + } +} + +/// The Actions panel (Photoshop's Window › Actions): sets, actions and steps as a tree, the +/// include and dialog cells, in-place rename, drag to move, Button Mode, the footer and the +/// context menus. It runs nothing and changes nothing: it reads the [`ActionList`] and reports +/// [`ActionsEvent`]s. +/// +/// ```ignore +/// let out = ActionsPanel::new(&mut ui_state.actions, &app.actions).host(&app_host).show(ui); +/// for event in out.events { +/// match event { +/// ActionsEvent::Play { action, from, .. } => app.play(action, from), +/// ActionsEvent::BeginRecording { into, .. } => app.record(into), +/// ActionsEvent::Rename { action, text, .. } => { app.actions.rename(action, &text, |_, _, _| {})?; } +/// _ => app.run_action_event(event), +/// } +/// } +/// ``` +/// +/// - **Rows**: a [`List`](craft_ui::list::List) in tree mode over the room above the footer: +/// loose actions first, then each set (a header with a folder icon and its action count; empty +/// sets show their header), each action (a play glyph, its name, at the end its shortcut and +/// step count, "2/3 steps" when some are off; the recording action a dot, open, its latest step +/// scrolled into view) and an open action's steps (the host's labels, dimmed when off), the +/// pending steps of a recording after them. The include and dialog cells are the list's toggle +/// columns before the label; an action with no steps has no include cell. +/// - **Pointer**: a click selects a row; a click on the disclosure toggles it (Alt opens or closes +/// all); a double click on an action's name renames it, elsewhere on an action it plays it. The +/// cells sweep down their column as one gesture. A drag moves an action (into or out of a set) +/// or a step (within or between actions), or drops it on the footer's Delete. Right-click on an +/// action or a set selects it and opens its menu: on an action Play, Record, Duplicate, Delete, +/// Action Options…, Batch…, Keyboard Shortcuts and Color; on a set New Action…, New Set…, +/// Duplicate Set, Delete Set, Set Options… and Save Set…. +/// - **Keys**: the rows are one Tab stop: arrows move, Left and Right close and open, Enter plays +/// an action or toggles a set, Space toggles the include cell, F2 renames, Delete deletes the +/// selection (not an action while recording), Cmd/Ctrl+] and [ move the row, Shift to the ends. The footer +/// buttons are Tab stops after the list. Edits are refused while [`ActionsHost::playing`]. +/// - **Button Mode**: each action is a full-width button in its colour with its name at the reading start, set names +/// between; a click plays it once. Button Mode is off while recording. +/// - **Enabled**: `enabled(false)` disables the rows, the cells, the buttons and the footer. +/// - **Empty**: a centred notice with the Record glyph. +#[must_use = "show the panel with `show`"] +#[derive(craft_ui::contract::Pattern)] +pub struct ActionsPanel<'a> { + state: &'a mut ActionsPanelState, + list: &'a ActionList, + host: Option<&'a dyn ActionsHost>, + rename: Option, + enabled: bool, + step_cells: StepCells, +} + +impl<'a> ActionsPanel<'a> { + /// A panel over `list` with `state`. + pub fn new(state: &'a mut ActionsPanelState, list: &'a ActionList) -> Self { + Self { state, list, host: None, rename: None, enabled: true, step_cells: StepCells::default() } + } + + /// The app's side; without one, steps show their command ids and nothing records or plays. + pub fn host(mut self, host: &'a dyn ActionsHost) -> Self { + self.host = Some(host); + self + } + + /// Opens the in-place rename of `action` this pass (the app's Rename command). Call it in the + /// pass that handles the command. + pub fn start_rename(mut self, action: usize) -> Self { + self.rename = Some(action); + self + } + + /// Which step cells the rows show. + pub fn step_cells(mut self, cells: StepCells) -> Self { + self.step_cells = cells; + self + } + + /// Whether the panel takes input (default true). + pub fn enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Draws the tree (or the buttons) and the footer, and reports this pass's events in order: + /// the list's, the cells', the context menu's, the footer's. + pub fn show(self, ui: &mut Ui) -> ActionsPanelOutput { + let ActionsPanel { state, list, host, rename, enabled, step_cells } = self; + let env = Env::of(ui); + let words = env.words::(); + let list_words = env.words::(); + let list_id = ui.scope_id().with("actions-rows"); + let settings_before = state.settings.clone(); + let events = RefCell::new(Vec::new()); + let state = RefCell::new(state); + let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id, step_cells }; + + let shown = Stack::new() + .fill() + .enabled(enabled) + .footer(|ui, _| { + let mut state = state.borrow_mut(); + events.borrow_mut().extend(show_footer(ui, &body, &mut state)); + }) + .show(ui, |ui, stack| { + let mut state = state.borrow_mut(); + let session = stack.memory::(); + let out = show_body(ui, &body, &mut state, session, rename); + let menu = show_menu(ui, &body, &out.response, session); + let mut reported = out.events; + reported.extend(menu); + (reported, out.selected) + }); + // Only the real run's result comes back, so the body's events are reported once; the footer's follow them. + let mut reported = Vec::new(); + if let Some((body_events, selected)) = shown.inner { + reported = body_events; + if let Some((row, sets)) = selected { + let mut state = state.borrow_mut(); + state.selected = row; + state.selected_sets = sets; + } + } + reported.extend(events.into_inner()); + let settings_changed = state.borrow().settings != settings_before; + ActionsPanelOutput { response: shown.output, events: reported, settings_changed } + } +} diff --git a/crates/automation/src/ui/actions/prompt.rs b/crates/automation/src/ui/actions/prompt.rs new file mode 100644 index 0000000000..bcb7d98d1f --- /dev/null +++ b/crates/automation/src/ui/actions/prompt.rs @@ -0,0 +1,55 @@ +//! [`LibraryPrompt`]: the question before Clear All Actions, Reset Actions… and Replace Actions…. + +use craft_ui::dialog::{PromptChoice, StandardPrompt}; +use craft_ui::runtime::words::CommonWords; + +use super::words::ActionsWords; + +/// Which whole-list command a [`StandardPrompt`] from [`prompt`](LibraryPrompt::prompt) asks +/// about. The prompt carries it as its tag, so the answer says which command it confirms +/// (`PromptAnswer::tag::()`). +/// +/// | Command | Question | Answers | +/// |---|---|---| +/// | Clear All | "Clear all actions?" | OK (`Proceed`), Cancel | +/// | Reset | "Replace the current actions?" | OK (`Proceed`: in place of the list), Append (`Alternate`: added to it), Cancel | +/// | Replace | "Replace all actions with {count} actions from {file}?" | OK (`Proceed`), Cancel | +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum LibraryPrompt { + /// Clear All Actions. + ClearAll, + /// Reset Actions…. + Reset, + /// Replace Actions… with the file the app read. + #[non_exhaustive] + Replace { + /// How many actions the file holds. + count: usize, + /// The file's display name. + file: String, + }, +} + +impl LibraryPrompt { + /// Replace Actions… with `count` actions from the file named `file`. + pub fn replace(count: usize, file: impl Into) -> Self { + LibraryPrompt::Replace { count, file: file.into() } + } + + /// The question for the app's dialog host, tagged with `self`. + pub fn prompt(&self, words: &ActionsWords, common: &CommonWords) -> StandardPrompt { + let (title, message) = match self { + LibraryPrompt::ClearAll => (words.clear_all_title.clone(), words.clear_all_question.clone()), + LibraryPrompt::Reset => (words.reset_title.clone(), words.reset_question.clone()), + LibraryPrompt::Replace { count, file } => { + (words.replace_title.clone(), words.replace_question.fill(&[("count", count.to_string().as_str()), ("file", file.as_str())]).into()) + } + }; + let mut prompt = StandardPrompt::custom(message).title(title).button(PromptChoice::Proceed, common.ok.clone()); + if *self == LibraryPrompt::Reset { + prompt = prompt.button(PromptChoice::Alternate, words.append.clone()); + } + prompt.button(PromptChoice::Cancel, common.cancel.clone()).tag(self.clone()) + } +} diff --git a/crates/automation/src/ui/actions/rows.rs b/crates/automation/src/ui/actions/rows.rs new file mode 100644 index 0000000000..41f1af45cc --- /dev/null +++ b/crates/automation/src/ui/actions/rows.rs @@ -0,0 +1,268 @@ +//! The rows of the tree: the display order over the list, and one row's `ListRow`. + +use std::borrow::Cow; + +use craft_behavior::{ColumnKey, DisplayOrder, IconId, ItemSource}; +use craft_theme::ControlSize; +use craft_theme::variant::Tone; +use craft_ui::contract::Props as _; +use craft_ui::list::{ListRow, RowInk, ToggleCell, ToggleFace, ToggleState}; +use craft_ui::primitives::IconSpec; +use craft_ui::runtime::env::Label; + +use super::body::Body; +use super::panel::{ActionSelection, ActionsHost, ActionsPanelState, StepCells}; +use crate::actions::{ActionInclude, ActionList}; + +/// The include column: a toggle on action rows (every step) and step rows. +pub const INCLUDE_COLUMN: ColumnKey = ColumnKey::new("include"); +/// The dialog column: a toggle on step rows. +pub const DIALOG_COLUMN: ColumnKey = ColumnKey::new("dialog"); +/// The column that holds the disclosure, the icon, the name and the trailing items. +pub(super) const NAME_COLUMN: ColumnKey = ColumnKey::new("name"); + +/// One displayed row. +struct Shown { + key: ActionSelection, + depth: usize, + group: bool, + open: bool, +} + +/// The rows the tree shows this pass, in order, with their depths: loose actions, then each set +/// header and (unless collapsed) its actions; an open action's steps and its pending steps after +/// it. Built once per pass from the list, the state and the host. Every action and every set is a +/// group, so it has a disclosure even with nothing inside, as PhotoCraft's does. The recording +/// action and its set are open whatever the state says. +pub(super) struct ActionRows<'a> { + rows: Vec, + list: &'a ActionList, + host: Option<&'a dyn ActionsHost>, +} + +/// Whether the set `name` shows its actions: not collapsed, or holding the action being recorded. +fn set_open(list: &ActionList, state: &ActionsPanelState, host: Option<&dyn ActionsHost>, name: &str) -> bool { + let recording = host.and_then(|host| host.recording()); + !state.settings.collapsed_sets.iter().any(|set| set == name) || recording.is_some_and(|action| list.set_of(action) == Some(name)) +} + +/// Whether the action `index` shows its steps: expanded, or being recorded. +fn action_open(list: &ActionList, state: &ActionsPanelState, host: Option<&dyn ActionsHost>, index: usize) -> bool { + host.and_then(|host| host.recording()) == Some(index) || list.action(index).is_some_and(|action| state.expanded.contains(&action.name)) +} + +impl<'a> ActionRows<'a> { + pub(super) fn build(list: &'a ActionList, state: &ActionsPanelState, host: Option<&'a dyn ActionsHost>) -> Self { + let mut out = Self { rows: Vec::new(), list, host }; + let order = list.display_order(); + for &index in order.iter().filter(|&&index| list.set_of(index).is_none()) { + out.push_action(state, index, 0); + } + for set in list.sets() { + let open = set_open(list, state, host, set); + out.rows.push(Shown { key: ActionSelection::Set(set.to_owned()), depth: 0, group: true, open }); + if open { + for &index in order.iter().filter(|&&index| list.set_of(index) == Some(set)) { + out.push_action(state, index, 1); + } + } + } + out + } + + fn push_action(&mut self, state: &ActionsPanelState, index: usize, depth: usize) { + let open = action_open(self.list, state, self.host, index); + self.rows.push(Shown { key: ActionSelection::Action(index), depth, group: true, open }); + if open { + let shown = self.list.step_count(index) + self.host.map_or(0, |host| host.pending_steps(index).len()); + for step in 0..shown { + self.rows.push(Shown { key: ActionSelection::Step(index, step), depth: depth + 1, group: false, open: false }); + } + } + } + + /// The keys in display order. + pub(super) fn keys(&self) -> Vec { + self.rows.iter().map(|row| row.key.clone()).collect() + } + + /// Whether the row at `at` has a disclosure that is open. + pub(super) fn is_open(&self, at: usize) -> bool { + self.rows.get(at).is_some_and(|row| row.open) + } + + pub(super) fn depth_at(&self, at: usize) -> usize { + self.rows.get(at).map_or(0, |row| row.depth) + } + + pub(super) fn is_group(&self, at: usize) -> bool { + self.rows.get(at).is_some_and(|row| row.group) + } + + /// Whether the row at `at` is a step the action holds (not a pending one). + fn recorded_step(&self, at: usize) -> Option<(usize, usize)> { + match self.rows.get(at)?.key { + ActionSelection::Step(action, step) if step < self.list.action(action)?.steps.len() => Some((action, step)), + _ => None, + } + } +} + +impl DisplayOrder for ActionRows<'_> { + fn len(&self) -> usize { + self.rows.len() + } + + fn key(&self, at: usize) -> ActionSelection { + self.rows[at].key.clone() + } + + fn depth(&self, at: usize) -> usize { + self.depth_at(at) + } + + fn has_children(&self, at: usize) -> bool { + self.is_group(at) + } + + fn open(&self, at: usize) -> bool { + self.is_open(at) + } + + fn text(&self, at: usize) -> Option> { + match &self.rows.get(at)?.key { + ActionSelection::Set(name) => Some(Cow::Borrowed(name.as_str())), + ActionSelection::Action(index) => self.list.action(*index).map(|action| Cow::Borrowed(action.name.as_str())), + ActionSelection::Step(..) => None, + } + } +} + +impl ItemSource for ActionRows<'_> { + fn toggled(&self, at: usize, column: &ColumnKey) -> bool { + let Some(row) = self.rows.get(at) else { return false }; + match (&row.key, column) { + (ActionSelection::Action(index), column) if *column == INCLUDE_COLUMN => { + self.list.action(*index).is_some_and(|action| action.include() == ActionInclude::All) + } + (ActionSelection::Set(name), column) if *column == INCLUDE_COLUMN => matches!(set_include(self.list, name), Some(ToggleState::On)), + _ => match self.recorded_step(at) { + Some((action, step)) if *column == INCLUDE_COLUMN => self.list.action(action).is_some_and(|held| held.step_enabled(step)), + Some((action, step)) if *column == DIALOG_COLUMN => self.list.action(action).is_some_and(|held| held.dialogs.contains(&step)), + _ => false, + }, + } + } + + fn toggle_enabled(&self, at: usize, column: &ColumnKey) -> bool { + let Some(row) = self.rows.get(at) else { return false }; + match &row.key { + ActionSelection::Action(index) => *column == INCLUDE_COLUMN && self.list.action(*index).is_some_and(|action| !action.steps.is_empty()), + ActionSelection::Step(..) => self.recorded_step(at).is_some(), + ActionSelection::Set(name) => *column == INCLUDE_COLUMN && set_include(self.list, name).is_some(), + } + } +} + +/// The include mark of the set `name` over its actions that have steps: on when every one is fully included, off when +/// none is, mixed otherwise; `None` when no action of the set has a step. +fn set_include(list: &ActionList, name: &str) -> Option { + let mut marks = + list.actions().iter().filter(|action| action.set.as_deref() == Some(name) && !action.steps.is_empty()).map(|action| action.include()); + let first = marks.next()?; + Some(if marks.all(|mark| mark == first) { include_state(first) } else { ToggleState::Mixed }) +} + +fn include_state(include: ActionInclude) -> ToggleState { + match include { + ActionInclude::All => ToggleState::On, + ActionInclude::Partial => ToggleState::Mixed, + ActionInclude::None => ToggleState::Off, + } +} + +/// The `ListRow` of `key`: +/// - a set: its folder icon, open or closed, its name and "{n} actions" at the end; +/// - an action: the play glyph, its name, the include cell unless it has no steps, the trailing +/// text (the shortcut and the step count, or "2/3 steps" when some are off), and while it is +/// recorded into a dot that names the recording; +/// - a step: the host's label, dimmed when switched off, the include and dialog cells, a small control high. +pub(super) fn build_row(body: &Body<'_>, state: &ActionsPanelState, key: &ActionSelection) -> ListRow<'static> { + let Body { list, host, words, env, .. } = *body; + let digits = |n: usize| env.format().integer(n as u64); + match key { + ActionSelection::Set(name) => { + let count = list.actions().iter().filter(|action| action.set.as_deref() == Some(name.as_str())).count(); + let open = set_open(list, state, host, name); + let icon = IconId::new(if open { "folder_open" } else { "folder" }); + ListRow::new(name.clone()).icon(IconSpec::svg(icon)).optional(words.action_count.text(count as u64, &digits(count))) + } + ActionSelection::Action(index) => { + let Some(action) = list.action(*index) else { return ListRow::new(Label::Empty) }; + let mut row = ListRow::new(action.name.clone()).icon(IconSpec::svg(IconId::new("play"))); + let steps = list.step_count(*index); + let mut text = words.steps.text(steps as u64, &digits(steps)); + if action.include() == ActionInclude::Partial { + let enabled = action.enabled_steps().count(); + text = words.partial_steps.fill(&[("enabled", &digits(enabled)), ("steps", &text)]); + } + if let Some(shortcut) = host.and_then(|host| host.shortcut(action)).map(|choice| choice.text()) { + text = words.shortcut_steps.fill(&[("shortcut", &shortcut), ("steps", &text)]); + } + if host.and_then(|host| host.recording()) == Some(*index) { + let name = words.recording_suffix.fill(&[("name", &action.name)]); + row = row.accessible_name(name).trailing_icon(IconSpec::svg(IconId::new("circle")), words.recording.clone()).trailing_tone(Tone::Bad); + } + row.optional(text) + } + ActionSelection::Step(index, step) => { + let Some(action) = list.action(*index) else { return ListRow::new(Label::Empty) }; + match action.steps.get(*step) { + Some(recorded) => { + let label = host.map_or_else(|| recorded.command.clone(), |host| host.step_label(recorded)); + let ink = if action.step_enabled(*step) { RowInk::Normal } else { RowInk::Dimmed }; + ListRow::new(label).ink(ink).size(ControlSize::Sm) + } + None => { + let pending = host.and_then(|host| host.pending_steps(*index).get(*step - action.steps.len())); + let label = + pending.map_or_else(String::new, |pending| host.map_or_else(|| pending.command.clone(), |host| host.step_label(pending))); + ListRow::new(label).size(ControlSize::Sm) + } + } + } + } +} + +/// The toggle cells of a row: the include cell of an action or set with steps and of a recorded step, the +/// dialog cell of a recorded step unless the panel leaves the dialog column out. +pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { + let Body { list, words, step_cells, .. } = *body; + let include = |state: ToggleState| ToggleCell::check(INCLUDE_COLUMN, state, words.include.clone()).tooltip(words.include_tooltip.clone()); + match key { + ActionSelection::Action(index) => match list.action(*index) { + Some(action) if !action.steps.is_empty() => vec![include(include_state(action.include()))], + _ => Vec::new(), + }, + ActionSelection::Step(index, step) => match list.action(*index) { + Some(action) if *step < action.steps.len() => { + let note = IconId::new("note"); + let mut dialog = ToggleCell::new( + DIALOG_COLUMN, + ToggleFace::icons(note.clone(), note), + ToggleState::of(action.dialogs.contains(step)), + words.dialog.clone(), + ) + .tooltip(words.dialog_tooltip.clone()); + dialog.check_box = true; + let mut cells = vec![include(ToggleState::of(action.step_enabled(*step)))]; + if step_cells == StepCells::IncludeAndDialog { + cells.push(dialog); + } + cells + } + _ => Vec::new(), + }, + ActionSelection::Set(name) => set_include(list, name).map_or_else(Vec::new, |state| vec![include(state)]), + } +} diff --git a/crates/automation/src/ui/actions/stories.rs b/crates/automation/src/ui/actions/stories.rs new file mode 100644 index 0000000000..b5f7ebd939 --- /dev/null +++ b/crates/automation/src/ui/actions/stories.rs @@ -0,0 +1,77 @@ +//! Stories of `ActionsPanel`: a tree with a set open and one action selected; a recording row; +//! Button Mode; the empty list. + +use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; +use egui::Ui; + +use super::mock::{FakeActionsHost, action, list_of, sample_list, step}; +use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice, StepCells}; +use crate::actions::{ActionColor, ActionList}; + +/// The sample list with Sharpen open and selected, one step off, and a shortcut on it. +#[story(ActionsPanel<'static>, covers = [Default], drive = Drive::Never)] +fn actions_panel_tree(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut sharpen = action("Sharpen", None, &["levels", "curves", "blur"]); + sharpen.disabled.insert(1); + let list = list_of(vec![sharpen, action("Vignette", Some("Effects"), &["mask", "blur"]), action("Glow", Some("Effects"), &["glow"])]); + let mut state = ActionsPanelState::default(); + state.expanded.insert("Sharpen".to_owned()); + state.selected = Some(ActionSelection::Action(0)); + let mut host = FakeActionsHost::default(); + host.shortcuts.insert("Sharpen".to_owned(), ShortcutChoice { key: 2, shift: false, command: false }); + ActionsPanel::new(&mut state, &list).host(&host).show(ui).into() +} + +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_recording(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let list = sample_list(); + let mut state = ActionsPanelState { selected: Some(ActionSelection::Action(0)), ..ActionsPanelState::default() }; + let host = FakeActionsHost { recording: Some(0), pending: vec![step("unsharp"), step("hue")], ..FakeActionsHost::default() }; + ActionsPanel::new(&mut state, &list).host(&host).show(ui).into() +} + +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_button_mode(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut list = ActionList::new(); + for (name, color) in ["None", "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Gray"].into_iter().zip(ActionColor::ALL) { + if let Ok(index) = list.new_action(name, None) { + let _ = list.set_color(index, color); + } + } + let mut state = ActionsPanelState::default(); + state.settings.button_mode = true; + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() +} + +/// The include variant: step rows without the dialog cell, and set rows with an include cell, one of them mixed. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_include_cells(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut blur = action("Blur", Some("Effects"), &["blur", "mask"]); + blur.disabled.insert(1); + let list = list_of(vec![blur, action("Glow", Some("Effects"), &["glow"]), action("Levels", Some("Basics"), &["levels", "curves"])]); + let mut state = ActionsPanelState::default(); + state.expanded.insert("Blur".to_owned()); + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).step_cells(StepCells::Include).show(ui).into() +} + +/// A range of three sets selected, as a Shift-click from the first to the last leaves it. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_set_range(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let list = list_of(vec![ + action("Blur", Some("Effects"), &["blur"]), + action("Levels", Some("Basics"), &["levels"]), + action("Glow", Some("Finish"), &["glow"]), + ]); + let mut state = ActionsPanelState { + selected: Some(ActionSelection::Set("Finish".to_owned())), + selected_sets: ["Effects", "Basics", "Finish"].map(str::to_owned).to_vec(), + ..ActionsPanelState::default() + }; + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() +} + +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_empty(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut state = ActionsPanelState::default(); + ActionsPanel::new(&mut state, &ActionList::new()).host(&FakeActionsHost::default()).show(ui).into() +} diff --git a/crates/automation/src/ui/actions/words.rs b/crates/automation/src/ui/actions/words.rs new file mode 100644 index 0000000000..c2f9ecc2ab --- /dev/null +++ b/crates/automation/src/ui/actions/words.rs @@ -0,0 +1,74 @@ +//! `ActionsWords`: every user-visible word of the Actions panel (`actions.*`). + +craft_ui::words! { + /// The Actions panel's words, English by default (Photoshop's and PhotoCraft's). Patterns with + /// `{row}`, `{name}`, `{shortcut}`, `{enabled}` and `{steps}` are whole phrases, so a language puts + /// the value where its grammar wants it. Step labels are the host's + /// ([`ActionsHost::step_label`](super::ActionsHost::step_label)). + #[non_exhaustive] + pub struct ActionsWords { + /// The tree's accessible name. + name: "actions.name" = "Actions"; + /// The empty list's text. + empty: "actions.empty" = "Record a sequence of edits, then play it on any document."; + /// A recording action's accessible name. + recording_suffix: template "actions.recordingSuffix" = "{name}, recording"; + /// The recording dot's name. + recording: "actions.recording" = "Recording"; + /// The include cell's accessible name: `{row}` is the row's label. + include: "actions.include" = "Include in playback: {row}"; + include_tooltip: "actions.includeTooltip" = "Include in playback"; + /// The dialog cell's accessible name: `{row}` is the row's label. + dialog: "actions.dialog" = "Show dialog during playback: {row}"; + dialog_tooltip: "actions.dialogTooltip" = "Show dialog during playback"; + /// An action row's trailing text with some steps off: the counted steps and how many are on. + partial_steps: template "actions.partialSteps" = "{enabled}/{steps}"; + /// An action row's trailing text with a shortcut. + shortcut_steps: template "actions.shortcutSteps" = "{shortcut} · {steps}"; + /// "{n} step" / "{n} steps": an action row's step count. + steps: count "actions.steps" = "{n} step" | "{n} steps"; + /// "{n} action" / "{n} actions": a set header's count. + action_count: count "actions.actions" = "{n} action" | "{n} actions"; + stop: "actions.stop" = "Stop playing/recording"; + record: "actions.record" = "Begin recording"; + play: "actions.play" = "Play selection"; + new_set: "actions.newSet" = "Create new set"; + new_action: "actions.newAction" = "Create new action"; + delete: "actions.delete" = "Delete"; + button_mode: "actions.buttonMode" = "Button Mode"; + /// The panel menu's submenu-free title of the row menu. + row_menu: "actions.rowMenu" = "Action"; + save_set: "actions.saveSet" = "Save Set…"; + menu_new_action: "actions.menuNewAction" = "New Action…"; + menu_new_set: "actions.menuNewSet" = "New Set…"; + duplicate_set: "actions.duplicateSet" = "Duplicate Set"; + delete_set: "actions.deleteSet" = "Delete Set"; + set_options: "actions.setOptions" = "Set Options…"; + menu_play: "actions.menuPlay" = "Play"; + menu_record: "actions.menuRecord" = "Record"; + duplicate: "actions.duplicate" = "Duplicate"; + action_options: "actions.actionOptions" = "Action Options…"; + batch: "actions.batch" = "Batch…"; + keyboard_shortcuts: "actions.keyboardShortcuts" = "Keyboard Shortcuts"; + /// The shortcut menu's "no shortcut" row. + none: "actions.none" = "None"; + shift: "actions.shift" = "Shift"; + /// The modifier check row on macOS. + command: "actions.command" = "Command"; + /// The modifier check row elsewhere. + ctrl: "actions.ctrl" = "Ctrl"; + color: "actions.color" = "Color"; + /// The title of the Clear All Actions question. + clear_all_title: "actions.clearAllTitle" = "Clear All Actions"; + clear_all_question: "actions.clearAllQuestion" = "Clear all actions?"; + /// The title of the Reset Actions question. + reset_title: "actions.resetTitle" = "Reset Actions"; + reset_question: "actions.resetQuestion" = "Replace the current actions?"; + /// Reset's answer that keeps the current actions and adds the starting sets. + append: "actions.append" = "Append"; + /// The title of the Replace Actions question. + replace_title: "actions.replaceTitle" = "Replace Actions"; + /// `{count}` is the number of actions in the file, `{file}` its name. + replace_question: template "actions.replaceQuestion" = "Replace all actions with {count} actions from {file}?"; + } +} diff --git a/crates/automation/src/ui/agents/mod.rs b/crates/automation/src/ui/agents/mod.rs new file mode 100644 index 0000000000..a22425b5f5 --- /dev/null +++ b/crates/automation/src/ui/agents/mod.rs @@ -0,0 +1,174 @@ +//! `AgentsPage`: the Agents page of Preferences, over the agent settings in the Preferences draft. + +#[cfg(feature = "suite")] +pub(crate) mod stories; +mod words; + +pub use words::AgentsWords; + +use craft_behavior::NumberCodec; +use craft_host::{PickId, PickRequest}; +use craft_theme::variant::Tone; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, Entry, FieldLayout, NoValue, Outcome, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::{Shade, Text}; +use craft_ui::form::{Field, Help}; +use craft_ui::layout_components::Stack; +use craft_ui::notices::{Notice, NoticeLayout}; +use craft_ui::patterns::preferences::{PathSetting, SettingsDraft}; +use craft_ui::pickers::Select; +use craft_ui::runtime::env::{Env, Label}; +use craft_ui::text::NumberField; +use egui::{Response, Ui}; + +use crate::agents::{AgentLinkStatus, AgentSettings, WhenAppClosed}; + +/// The purpose the folder picks are filed under. +const PICK_PURPOSE: &str = "agents"; + +/// What the page reported this pass. +#[derive(Debug)] +#[non_exhaustive] +pub struct AgentsPageOutput { + /// The page's response. + pub response: Response, + /// The draft changed this pass (the window's Apply becomes enabled). + pub changed: bool, + /// A folder row's Browse filed this pick through the host's file service; its answer lands in the draft. + pub browsing: Option, +} + +impl Outcome for AgentsPageOutput { + type Value = NoValue; + + fn response(&self) -> &Response { + &self.response + } +} + +/// The Agents page of Preferences, drawn whole by the app as a custom page (`SettingsDocument::custom_page`) over the +/// [`AgentSettings`] saved under `page` (`"integrations"`): the keys `.controlPort`, `.readRoot`, +/// `.writeRoot`, `.whenAppClosed` and `.allowAgentControl`. Each edit writes only its own key into +/// the draft, so Apply writes just that setting. +/// +/// With the suite's `AI-MCP` flag, top to bottom: the line naming the ArtCraft Launcher's switch (the page has none of +/// its own), the link's status (the launch options manage it; its problem as an error; the port agents connect on; or +/// off), Control Port with its help, the two folders agents may open from and save to (typed, or picked with Browse… +/// through the host's file service, [`PathSetting`]), and what the app's CLI does while the app is closed. Without the +/// flag: Allow Agent Control and Control Port, the settings the app had before the switch. Labels name the app by the +/// host's app name. +#[must_use = "show the page with `show`"] +#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)] +pub struct AgentsPage<'a> { + page: &'a str, + draft: &'a mut SettingsDraft, + status: &'a AgentLinkStatus, + /// The suite's `AI-MCP` flag is on: the launcher's switch decides, and the page shows the folders and the closed-app + /// choice. + #[prop] + mcp_flag: bool, +} + +impl<'a> AgentsPage<'a> { + /// The page over the settings under `page` in the Preferences `draft`, showing the link's `status`. + pub fn new(page: &'a str, draft: &'a mut SettingsDraft, status: &'a AgentLinkStatus) -> Self { + AgentsPage { page, draft, status, mcp_flag: false } + } + + /// Shows the page. + pub fn show(self, ui: &mut Ui) -> AgentsPageOutput { + let AgentsPage { page, draft, status, mcp_flag } = self; + let env = Env::of(ui); + let words = env.words::(); + let units = env.units(); + let app = env.view().host().map_or("", |host| host.app().name); + let key = |name: &str| format!("{page}.{name}"); + let defaults = AgentSettings::default(); + let mut changed = false; + let mut browsing = None; + let shown = Stack::new().show(ui, |ui, _| { + if mcp_flag { + Text::new(words.intro.clone()).shade(Shade::Muted).show(ui); + status_line(ui, &words, status, app); + } else { + let allow_key = key("allowAgentControl"); + let allowed = draft.get(&allow_key).unwrap_or(defaults.allow_agent_control); + let mut next = None; + Field::new(words.allow_agent_control.clone()).id_salt("allow").layout(FieldLayout::After).show(ui, |ui, _| { + next = Checkbox::new(Bind::given(allowed)).show(ui).events.landed().cloned(); + }); + if let Some(next) = next.filter(|next| *next != allowed) { + draft.set(&allow_key, &next); + changed = true; + } + } + + let port_key = key("controlPort"); + let port = draft.get::(&port_key).unwrap_or(i64::from(defaults.control_port)); + let mut next = None; + let mut field = Field::new(words.control_port.clone()).id_salt("port"); + if mcp_flag { + field = field.help(Help::Text(words.port_hint.clone())); + } + field.show(ui, |ui, _| { + let number = NumberField::new(words.control_port.clone(), Bind::given(Some(port as f64))) + .codec(NumberCodec::new(units.reader(None), 0)) + .range(0.0..=f64::from(u16::MAX)) + .step(1.0); + next = number.show(ui).edit.events.landed().cloned().flatten(); + }); + if let Some(next) = next.map(|v| v.round() as i64).filter(|next| *next != port) { + draft.set(&port_key, &next); + changed = true; + } + if !mcp_flag { + return; + } + + for (name, label) in [("readRoot", &words.read_root), ("writeRoot", &words.write_root)] { + let folder_key = key(name); + let out = + PathSetting::new(label.clone(), &folder_key, draft, PickRequest::folder(PICK_PURPOSE)).placeholder(words.none.clone()).show(ui); + changed |= out.changed; + browsing = browsing.or(out.browsing); + } + + let closed_key = key("whenAppClosed"); + let current = draft.get::(&closed_key).and_then(|name| WhenAppClosed::parse(&name)).unwrap_or(defaults.when_app_closed); + let choices: Vec> = WhenAppClosed::ALL + .into_iter() + .map(|choice| { + let label: Label = match choice { + WhenAppClosed::Launch => words.launch.fill(&[("app", app)]).into(), + WhenAppClosed::Headless => words.headless.clone(), + WhenAppClosed::Error => words.ask.fill(&[("app", app)]).into(), + }; + Entry::new(choice, label) + }) + .collect(); + let label: Label = words.when_closed.fill(&[("app", app)]).into(); + let mut picked = None; + Field::new(label.clone()).id_salt("closed").show(ui, |ui, _| { + picked = Select::new(label.clone(), Bind::given(current), &choices).id_salt("closed").show(ui).value().copied(); + }); + if let Some(picked) = picked.filter(|picked| *picked != current) { + draft.set(&closed_key, &picked.name()); + changed = true; + } + }); + AgentsPageOutput { response: shown.output, changed, browsing } + } +} + +/// One line on where the link stands: the launch options manage it, its problem, the port agents connect on, or off. +fn status_line(ui: &mut Ui, words: &AgentsWords, status: &AgentLinkStatus, app: &str) { + if status.launch_flags { + Text::new(words.managed.clone()).shade(Shade::Muted).show(ui); + } else if let Some(problem) = &status.problem { + Notice::new(Tone::Bad, Label::from(words.problem(problem, app))).layout(NoticeLayout::Inline).show(ui); + } else if let Some(port) = status.port { + Text::new(words.listening.fill(&[("port", &port.to_string())])).show(ui); + } else { + Text::new(words.off.clone()).shade(Shade::Faint).show(ui); + } +} diff --git a/crates/automation/src/ui/agents/stories.rs b/crates/automation/src/ui/agents/stories.rs new file mode 100644 index 0000000000..6316bf6ec6 --- /dev/null +++ b/crates/automation/src/ui/agents/stories.rs @@ -0,0 +1,42 @@ +//! Stories of the Agents page. + +use super::AgentsPage; +use crate::agents::{AgentLinkStatus, LinkProblem}; +use craft_ui::patterns::preferences::SettingsDraft; +use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; +use egui::Ui; + +fn draft() -> SettingsDraft { + let mut draft = SettingsDraft::default(); + draft.set("integrations.controlPort", &0_i64); + draft.set("integrations.readRoot", &"/photos/agents"); + draft +} + +fn status(port: Option, problem: Option) -> AgentLinkStatus { + AgentLinkStatus { port, launch_flags: false, problem } +} + +#[story(AgentsPage<'static>, covers = [Default], drive = Drive::Never)] +fn agents_page_listening(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let status = status(Some(4321), None); + AgentsPage::new("integrations", data.value("listening", draft()), &status).mcp_flag(true).show(ui).into() +} + +#[story(AgentsPage<'static>, covers = [], drive = Drive::Never)] +fn agents_page_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let status = status(None, None); + AgentsPage::new("integrations", data.value("off", draft()), &status).mcp_flag(true).show(ui).into() +} + +#[story(AgentsPage<'static>, covers = [], drive = Drive::Never)] +fn agents_page_problem(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let status = status(None, Some(LinkProblem::Listen { port: 7878, error: "Address already in use".into() })); + AgentsPage::new("integrations", data.value("problem", draft()), &status).mcp_flag(true).show(ui).into() +} + +#[story(AgentsPage<'static>, covers = [], drive = Drive::Never)] +fn agents_page_without_the_flag(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let status = status(None, None); + AgentsPage::new("integrations", data.value("legacy", draft()), &status).show(ui).into() +} diff --git a/crates/automation/src/ui/agents/words.rs b/crates/automation/src/ui/agents/words.rs new file mode 100644 index 0000000000..a3dc4e3e5a --- /dev/null +++ b/crates/automation/src/ui/agents/words.rs @@ -0,0 +1,52 @@ +//! `AgentsWords`: every user-visible word of the Agents page (`agents.*`). + +use crate::agents::LinkProblem; + +craft_ui::words! { + /// The Agents page's words, English by default. `{app}` is the app's name, `{port}` a port number and `{error}` the + /// system's reason. + #[non_exhaustive] + pub struct AgentsWords { + /// The line over the page: where the switch is. + intro: "agents.intro" = "AI apps such as Claude can open, edit and save documents in this window while ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps is on. Only programs on this computer can connect."; + /// The status while the launch options run the control server. + managed: "agents.managed" = "Managed by the launch options (--control)."; + /// The status while agents can connect. + listening: template "agents.listening" = "Agents can connect on 127.0.0.1:{port}."; + /// The status while agents can't connect and nothing went wrong. + off: "agents.off" = "Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents."; + control_port: "agents.controlPort" = "Control Port"; + /// Help under the Control Port field. + port_hint: "agents.portHint" = "0 picks a free port; AI apps find it by themselves"; + read_root: "agents.readRoot" = "Folder agents can open from"; + write_root: "agents.writeRoot" = "Folder agents can save to"; + /// An empty folder field. + none: "agents.none" = "None"; + when_closed: template "agents.whenClosed" = "When {app} is closed"; + launch: template "agents.launch" = "Open {app}"; + headless: "agents.headless" = "Work without a window"; + ask: template "agents.ask" = "Ask to open {app}"; + allow_agent_control: "agents.allowAgentControl" = "Allow Agent Control"; + not_allowed: "agents.notAllowed" = "Agents can't connect: Allow Agent Control is off in the preferences file."; + no_settings_folder: template "agents.noSettingsFolder" = "Agents can't connect: {app} has no settings folder (no home folder)."; + token_file: template "agents.tokenFile" = "Agents can't connect: the token file could not be written: {error}"; + listen: template "agents.listen" = "Couldn't listen on 127.0.0.1:{port}: {error}"; + port_out_of_range: template "agents.portOutOfRange" = "Agents can't connect: the control port {port} is outside 0 to 65535."; + publish: template "agents.publish" = "Couldn't publish the agent connection: {error}"; + } +} + +impl AgentsWords { + /// The sentence for `problem`; `app` is the app's name. The app's own note is shown as it wrote it. + pub fn problem(&self, problem: &LinkProblem, app: &str) -> String { + match problem { + LinkProblem::NotAllowed => self.not_allowed.as_str().to_owned(), + LinkProblem::NoSettingsFolder => self.no_settings_folder.fill(&[("app", app)]), + LinkProblem::TokenFile(error) => self.token_file.fill(&[("error", error)]), + LinkProblem::Listen { port, error } => self.listen.fill(&[("port", &port.to_string()), ("error", error)]), + LinkProblem::PortOutOfRange(port) => self.port_out_of_range.fill(&[("port", &port.to_string())]), + LinkProblem::Publish(error) => self.publish.fill(&[("error", error)]), + LinkProblem::App(note) => note.clone(), + } + } +} diff --git a/crates/automation/src/ui/mod.rs b/crates/automation/src/ui/mod.rs new file mode 100644 index 0000000000..dc3cbb575e --- /dev/null +++ b/crates/automation/src/ui/mod.rs @@ -0,0 +1,8 @@ +//! The automation widgets. Every target. +//! +//! - [`actions`]: the Actions panel. +//! - [`agents`]: the Agents page of Preferences (desktop, feature `agents`). + +pub mod actions; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub mod agents; diff --git a/crates/automation/src/window.rs b/crates/automation/src/window.rs new file mode 100644 index 0000000000..ae5af54dae --- /dev/null +++ b/crates/automation/src/window.rs @@ -0,0 +1,25 @@ +//! `ui.window`: window commands through the framework's one window-command path. + +use craft_ui::runtime::windows::{WindowAction, WindowHost}; +use egui::ViewportId; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// `ui.window {maximized: bool}` sends `WindowAction::SetMaximized` through `WindowHost::act` and returns `Ok({})`, or +/// `Err` when `act` returns false (no window commands, as on wasm). `None` for any other method. It keeps no state. +pub fn window_method(host: &WindowHost, viewport: ViewportId, method: &str, params: &Value) -> Option> { + if method != "ui.window" { + return None; + } + Some(run(host, viewport, params)) +} + +fn run(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let params = Params(params).only(None, &["maximized"])?; + let maximized = Params(¶ms).bool_field("maximized")?.ok_or("missing `maximized`")?; + if !host.act(viewport, WindowAction::SetMaximized(maximized)) { + return Err("this platform has no window commands".to_owned()); + } + Ok(json!({})) +} diff --git a/crates/automation/tests/it/access.rs b/crates/automation/tests/it/access.rs new file mode 100644 index 0000000000..96d050d5a3 --- /dev/null +++ b/crates/automation/tests/it/access.rs @@ -0,0 +1,268 @@ +//! Named controls through the protocol (`control` targets, `ui.find`), `ui.inspect` over the window's kept access +//! tree, and `ui.click` and `ui.focus` on a node it names: tree order and filters, what an open modal hides, a click, +//! a context menu and a focus reaching their widget, and the targets refused before anything is queued. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use craft_automation::access::{AMBIGUOUS, NO_CONTROL, NO_TREE, NodeTarget, access_method, inspect, resolve}; +use craft_automation::synthetic::input_method; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::dialog::Dialog; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::runtime::egui::access::Declared; +use craft_ui::runtime::egui::injected::hook_without_pass; +use craft_ui::runtime::windows::WindowHost; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Pos2, ViewportId}; +use serde_json::{Value, json}; + +/// Two buttons and a text field named "Name", with the clicks each button got and where the pointer was. +struct Rig { + fx: Fixture, + host: WindowHost, + clicks: Rc<[Cell; 2]>, + pointer: Rc>>, +} + +impl Rig { + fn new(names: [&'static str; 2]) -> Self { + let clicks: Rc<[Cell; 2]> = Rc::default(); + let pointer = Rc::new(Cell::new(None)); + let text = RefCell::new(String::new()); + let (seen, at) = (clicks.clone(), pointer.clone()); + let fx = Fixture::new(move |ui| { + for (n, name) in names.iter().enumerate() { + if clicked(&Button::new(*name).show(ui)) { + seen[n].set(seen[n].get() + 1); + } + } + TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui); + at.set(ui.input(|input| input.pointer.latest_pos())); + }); + let host = WindowHost::of(fx.ctx()); + Self { fx, host, clicks, pointer } + } + + /// The same, after the host kept its first access tree. + fn kept(names: [&'static str; 2]) -> Self { + let mut rig = Self::new(names); + rig.host.keep_access_trees(); + rig.fx.idle(2); + rig + } + + /// Sends `method`; when it is accepted, runs frames until the host has processed the input. + fn send(&mut self, method: &str, params: Value) -> Result<(), String> { + input_method(method, ¶ms, &self.host, ViewportId::ROOT, &|_, _| None).expect("an input method")?; + for _ in 0..32 { + self.fx.frame(Vec::new()); + if self.host.injected_idle() { + break; + } + } + assert!(self.host.injected_idle(), "{method} was processed"); + self.fx.frame(Vec::new()); + Ok(()) + } + + fn find(&self, params: Value) -> Result { + access_method("ui.find", ¶ms, &self.host, ViewportId::ROOT).expect("an access method") + } + + fn counts(&self) -> [u32; 2] { + [self.clicks[0].get(), self.clicks[1].get()] + } +} + +/// A click `{control: {name}}` presses that button and no other, also for a text field named by its label, and +/// `ui.find` reports where the control is. +#[trial] +fn a_click_on_a_named_control_lands_on_it() { + let mut rig = Rig::kept(["Save", "Cancel"]); + rig.send("ui.click", json!({"control": {"name": "Save"}})).expect("valid"); + assert_eq!(rig.counts(), [1, 0]); + rig.send("ui.click", json!({"control": {"name": "Cancel:"}})).expect("valid"); + assert_eq!(rig.counts(), [1, 1], "a trailing colon of the name is ignored"); + + let field = rig.find(json!({"name": "Name"})).expect("the field is found"); + assert_eq!(field["enabled"], json!(true)); + assert_eq!(field["focused"], json!(false)); + let rect: Vec = field["rect"].as_array().expect("a rect").iter().map(|v| v.as_f64().expect("a number")).collect(); + rig.send("ui.click", json!({"control": {"name": "Name"}})).expect("valid"); + let at = rig.pointer.get().expect("the pointer arrived"); + let (x, y) = (f64::from(at.x), f64::from(at.y)); + assert!(x >= rect[0] && x <= rect[0] + rect[2] && y >= rect[1] && y <= rect[1] + rect[3], "{at:?} lies in {rect:?}"); + assert_eq!(rig.find(json!({"name": "Name"})).expect("found")["focused"], json!(true), "the click focused the field"); +} + +/// A name two controls share needs an `index`; an unknown name matches none; neither queues anything. Before the +/// first kept pass there is no tree to look in. +#[trial] +fn an_ambiguous_or_missing_name_queues_nothing() { + let mut early = Rig::new(["Go", "Go"]); + assert_eq!(early.send("ui.click", json!({"control": {"name": "Go"}})), Err(NO_TREE.to_owned())); + assert_eq!(early.find(json!({"name": "Go"})), Err(NO_TREE.to_owned())); + + let mut rig = Rig::kept(["Go", "Go"]); + let ambiguous = rig.send("ui.click", json!({"control": {"name": "Go"}})).expect_err("two match"); + assert!(ambiguous.starts_with(AMBIGUOUS), "{ambiguous}"); + let missing = rig.send("ui.click", json!({"control": {"name": "Stop"}})).expect_err("none matches"); + assert!(missing.starts_with(NO_CONTROL), "{missing}"); + assert!(rig.host.injected_idle(), "nothing was queued"); + assert_eq!(rig.counts(), [0, 0]); + + rig.send("ui.click", json!({"control": {"name": "Go", "index": 1}})).expect("valid"); + assert_eq!(rig.counts(), [0, 1], "index 1 is the second in reading order"); +} + +/// The listed widgets of `params`, from the window's kept tree. +fn listed(host: &WindowHost, params: Value) -> Value { + inspect(host, ViewportId::ROOT, ¶ms).expect("an inspect reply") +} + +/// The labels of a reply's widgets, in its order. +fn labels(reply: &Value) -> Vec { + reply["widgets"].as_array().into_iter().flatten().filter_map(|w| w["label"].as_str().map(str::to_owned)).collect() +} + +/// The widget of a reply labelled `label`. +fn widget<'a>(reply: &'a Value, label: &str) -> &'a Value { + reply["widgets"].as_array().into_iter().flatten().find(|w| w["label"] == label).unwrap_or_else(|| panic!("{label} is listed: {reply}")) +} + +/// Where `label` sits in `order`. +fn place(order: &[String], label: &str) -> usize { + order.iter().position(|l| l == label).unwrap_or_else(|| panic!("{label} is listed in {order:?}")) +} + +/// Every reported node is listed once in tree order with its state, the root left out; `query`, `role` and `focused` +/// keep a subset, `limit` cuts the list but not the count; a node behind an open modal is neither listed nor +/// resolved, and the modal's own buttons are. +#[trial] +fn inspect_lists_reported_nodes_in_tree_order_with_their_filters() { + let open = Rc::new(Cell::new(false)); + let (shown, name) = (open.clone(), Rc::new(RefCell::new(String::from("Draft")))); + let mut fx = Fixture::new(move |ui| { + Button::new("Open").show(ui); + Button::new("Save").show(ui); + Button::new("Archive").enabled(false).show(ui); + TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui); + let mut now = shown.get(); + Dialog::new("Options").opened(Bind::bound(&mut now)).buttons([FooterButton::new("Apply", DialogRole::Accept)]).show(ui, |_, _| {}); + shown.set(now); + }); + let host = WindowHost::of(fx.ctx()); + host.keep_access_tree(); + fx.settle(); + + let all = listed(&host, json!({})); + let order = labels(&all); + assert!(place(&order, "Open") < place(&order, "Save") && place(&order, "Save") < place(&order, "Archive"), "tree order: {order:?}"); + let widgets = all["widgets"].as_array().expect("a widget list"); + assert_eq!(all["count"].as_u64(), Some(widgets.len() as u64), "{all}"); + assert_eq!(all["truncated"], false); + assert!(widgets.iter().all(|w| w["depth"].as_u64().is_some_and(|depth| depth >= 1)), "the root is not listed: {all}"); + let ids: Vec<&str> = widgets.iter().filter_map(|w| w["id"].as_str()).collect(); + assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "each node once: {ids:?}"); + let (save, archive) = (widget(&all, "Save"), widget(&all, "Archive")); + assert!(save["enabled"] == true && save["clickable"] == true, "{save}"); + assert!(archive["enabled"] == false, "{archive}"); + let rect = |w: &Value| w["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::>()).expect("a rect"); + assert!(rect(widget(&all, "Open"))[3] <= rect(save)[1] + 0.5, "Open lies above Save"); + + let queried = listed(&host, json!({"query": "SAV"})); + assert!(labels(&queried).contains(&"Save".to_owned()) && !labels(&queried).contains(&"Open".to_owned()), "{queried}"); + let buttons = listed(&host, json!({"role": "button"})); + assert!(["Open", "Save", "Archive"].iter().all(|label| labels(&buttons).contains(&(*label).to_owned())), "{buttons}"); + assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["role"].as_str().is_some_and(|role| role.eq_ignore_ascii_case("button")))); + let fields = listed(&host, json!({"role": "textinput"})); + assert_eq!(fields["count"], 1, "the one text field, its role matched ignoring case: {fields}"); + assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != fields["widgets"][0]["id"]), "the field is no button"); + + let (focused, unfocused) = (listed(&host, json!({"focused": true})), listed(&host, json!({"focused": false}))); + assert_eq!(focused["count"].as_u64().unwrap_or(0) + unfocused["count"].as_u64().unwrap_or(0), all["count"].as_u64().unwrap_or(0)); + assert!(focused["widgets"].as_array().into_iter().flatten().all(|w| w["focused"] == true), "{focused}"); + + let first = listed(&host, json!({"limit": 1})); + assert_eq!(first["widgets"].as_array().map(Vec::len), Some(1)); + assert_eq!((first["count"].clone(), first["truncated"].clone()), (all["count"].clone(), json!(true))); + assert_eq!(first["widgets"][0], all["widgets"][0], "the limit keeps the first in tree order"); + assert!(inspect(&host, ViewportId::ROOT, &json!({"nodes": true})).is_err(), "an unknown field is refused"); + + open.set(true); + fx.idle(30); + let tree = host.access_tree_view(ViewportId::ROOT).expect("the kept tree"); + let behind = listed(&host, json!({})); + assert!(!labels(&behind).contains(&"Open".to_owned()), "a node behind the modal is not listed: {behind}"); + assert!(labels(&behind).contains(&"Apply".to_owned()), "the modal's own button is: {behind}"); + assert!(resolve(&tree, &NodeTarget::Label("Open".into()), Declared::Click).is_err(), "nor is it resolved"); + assert!(resolve(&tree, &NodeTarget::Label("apply".into()), Declared::Click).is_ok(), "a label matches ignoring case"); +} + +/// A click by label activates its button once; a secondary click opens the node's context menu; a focus by the id +/// `ui.inspect` lists moves the key focus there. A missing, ambiguous, disabled or undeclared target is refused and +/// queues nothing. +#[trial] +fn click_and_focus_by_label_or_id_reach_the_widget_and_refuse_what_they_cannot_name() { + let saves = Rc::new(Cell::new(0)); + let (counted, name) = (saves.clone(), Rc::new(RefCell::new(String::new()))); + let mut fx = Fixture::new(move |ui| { + if Button::new("Save").show(ui).clicked() { + counted.set(counted.get() + 1); + } + let layer = Button::new("Layer").show(ui); + Menu::context("Layer menu", &layer).show(ui, |ui, _| { + MenuItem::new("Delete layer").show(ui); + }); + Button::new("Copy").id_salt("first copy").show(ui); + Button::new("Copy").id_salt("second copy").show(ui); + Button::new("Archive").enabled(false).show(ui); + TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui); + }); + let (host, ctx) = (WindowHost::of(fx.ctx()), fx.ctx().clone()); + host.keep_access_tree(); + fx.settle(); + let none = |_: usize, _: Pos2| None; + let send = |fx: &mut Fixture, method: &str, params: Value| { + input_method(method, ¶ms, &host, ViewportId::ROOT, &none).expect("an input method").expect("a target it can name"); + fx.run_injected().settle(); + }; + + send(&mut fx, "ui.click", json!({"label": "save"})); + assert_eq!(saves.get(), 1, "the click by label activated Save once"); + + let field = listed(&host, json!({"role": "TextInput"}))["widgets"][0]["id"].clone(); + assert!(field.is_string(), "the text field is listed with its id"); + let before = listed(&host, json!({"focused": true})); + assert!(before["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != field), "the field has no focus yet: {before}"); + send(&mut fx, "ui.focus", json!({"id": field})); + let focused = listed(&host, json!({"focused": true})); + assert_eq!(focused["widgets"].as_array().map(|w| w.iter().map(|w| w["id"].clone()).collect::>()), Some(vec![field]), "{focused}"); + + // Refused while no popup is open, so each is refused for what it names, not for a covered window. + let refused = [ + ("ui.click", json!({"label": "Nothing here"})), + ("ui.click", json!({"id": "1"})), + ("ui.click", json!({"label": "copy"})), + ("ui.click", json!({"label": "Archive"})), + ("ui.click", json!({"label": "Save", "button": "secondary"})), + ("ui.focus", json!({"label": "Nothing here"})), + ]; + for (method, params) in refused { + let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &none); + assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}"); + assert!(host.injected_idle(), "{method} {params} left nothing waiting"); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing"); + } + fx.settle(); + assert_eq!(saves.get(), 1, "no refused request clicked"); + + assert_eq!(listed(&host, json!({"query": "Delete layer"}))["count"], 0, "the menu starts closed"); + send(&mut fx, "ui.click", json!({"label": "Layer", "button": "secondary"})); + assert!(listed(&host, json!({"query": "Delete layer"}))["count"].as_u64().is_some_and(|n| n >= 1), "the context menu opened"); + assert_eq!(saves.get(), 1, "nothing else was clicked"); +} diff --git a/crates/automation/tests/it/actions.rs b/crates/automation/tests/it/actions.rs new file mode 100644 index 0000000000..8046137005 --- /dev/null +++ b/crates/automation/tests/it/actions.rs @@ -0,0 +1,349 @@ +//! `ActionsPanel`: where a dragged row lands. + +use std::cell::RefCell; +use std::rc::Rc; + +use craft_automation::actions::ActionList; +use craft_automation::ui::actions::mock::{FakeActionsHost, action, list_of}; +use craft_automation::ui::actions::{ + ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN, StepCells, +}; +use craft_ui::testing::{Fixture, Target, pointer, trial}; +use egui::{Key, Modifiers, Pos2, Ui, Vec2}; + +/// The app around the panel: what it holds and what the panel reported. +struct App { + state: ActionsPanelState, + list: ActionList, + host: FakeActionsHost, + events: Vec, +} + +type Shared = Rc>; + +/// The room of the panel: wide enough for a row's parts and inside the 800 by 600 screen of a fixture. +const PANEL: Vec2 = Vec2::new(520.0, 520.0); + +/// A pointer move that starts a drag. +const DRAG_STEP: Vec2 = Vec2::new(0.0, 8.0); + +fn app(list: ActionList) -> App { + App { state: ActionsPanelState::default(), list, host: FakeActionsHost::prefixed("Run "), events: Vec::new() } +} + +fn show(ui: &mut Ui, app: &mut App, cells: StepCells) { + let App { state, list, host, events } = app; + let out = ActionsPanel::new(state, list).host(&*host).step_cells(cells).show(ui); + events.extend(out.events); +} + +fn rig(app: App) -> (Fixture, Shared) { + rig_cells(app, StepCells::default()) +} + +fn rig_cells(app: App, cells: StepCells) -> (Fixture, Shared) { + let shared = Rc::new(RefCell::new(app)); + let shown = Rc::clone(&shared); + let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut(), cells)); + fixture.room(PANEL); + fixture.settle(); + (fixture, shared) +} + +fn take(shared: &Shared) -> Vec { + std::mem::take(&mut shared.borrow_mut().events) +} + +/// The node named `label`. +fn node(fixture: &Fixture, label: &str) -> Target { + fixture.by_label(label).unwrap_or_else(|| { + let names: Vec<_> = fixture.tree().keys().into_iter().filter_map(|key| fixture.tree().name_of(key)).collect(); + panic!("no node named {label:?}; the tree has {names:?}") + }) +} + +/// The point `share` of the way down `target`, in the middle of its width. +fn at(target: &Target, share: f32) -> Pos2 { + Pos2::new(target.rect.center().x, target.rect.top() + target.rect.height() * share) +} + +/// Press at `from`, move past the drag threshold and on to `to`, release there. +fn drag_to(fixture: &mut Fixture, from: Pos2, to: Pos2) { + fixture.idle(6); + fixture.frame(vec![pointer::moved(from)]); + fixture.frame(vec![pointer::press(from)]); + fixture.frame(vec![pointer::moved(from + DRAG_STEP)]); + fixture.frame(vec![pointer::moved(to)]); + fixture.frame(vec![pointer::moved(to)]); + fixture.frame(vec![pointer::release(to)]); + fixture.idle(2); +} + +/// The moves the panel reported: the dragged row and where it goes. +fn moves(events: &[ActionsEvent]) -> Vec<(ActionSelection, ActionPlace)> { + events + .iter() + .filter_map(|event| match event { + ActionsEvent::Reorder(ActionMove { row, place, .. }) => Some((row.clone(), place.clone())), + _ => None, + }) + .collect() +} + +/// Loose "Loose", then the sets "Alpha" (one action) and "Beta" (one action). +fn two_sets() -> ActionList { + list_of(vec![action("Loose", None, &["a"]), action("First", Some("Alpha"), &["b"]), action("Second", Some("Beta"), &["c"])]) +} + +/// A drop before a later set goes to the end of the set before it; before the first set it is loose. +#[trial] +fn actions_panel_drop_before_a_later_set_lands_at_the_end_of_the_previous_set() { + let (mut fixture, shared) = rig(app(two_sets())); + let (from, to) = (node(&fixture, "Loose").center(), at(&node(&fixture, "Beta"), 0.1)); + drag_to(&mut fixture, from, to); + assert_eq!( + moves(&take(&shared)), + [(ActionSelection::Action(0), ActionPlace::action(1, Some("Alpha".into())))], + "the drop line sits under Alpha's last action" + ); + + let (from, to) = (node(&fixture, "Second").center(), at(&node(&fixture, "Alpha"), 0.1)); + drag_to(&mut fixture, from, to); + assert_eq!( + moves(&take(&shared)), + [(ActionSelection::Action(2), ActionPlace::action(1, None))], + "before the first set the action is loose, after the last loose one" + ); +} + +/// Space on the focused row flips its Include check. +#[trial] +fn actions_panel_space_flips_the_include_check_of_the_focused_row() { + let (mut fixture, shared) = rig(app(two_sets())); + let row = node(&fixture, "Loose").center(); + fixture.frame(vec![pointer::moved(row)]); + fixture.frame(vec![pointer::press(row)]); + fixture.frame(vec![pointer::release(row)]); + fixture.idle(2); + take(&shared); + fixture.key(Key::Space, Modifiers::NONE).idle(2); + let flipped = take(&shared).into_iter().any(|event| { + matches!(event, ActionsEvent::Toggle(craft_ui::contract::SweepStep::Flip(edit)) + if edit.key == ActionSelection::Action(0) && edit.column == INCLUDE_COLUMN) + }); + assert!(flipped, "Space flips the row's include cell"); +} + +/// A step row is a small control high, shorter than its action's row; a set row is a plain row as high as an action's. +#[trial] +fn actions_panel_step_rows_are_shorter_than_action_rows() { + let mut shown = app(two_sets()); + shown.state.expanded.insert("Loose".into()); + let (fixture, _) = rig(shown); + let (action, step, set) = (node(&fixture, "Loose").rect, node(&fixture, "Run a").rect, node(&fixture, "Alpha").rect); + assert!(step.height() < action.height(), "the step row ({step:?}) is shorter than the action row ({action:?})"); + assert_eq!(set.height(), action.height(), "a set row is as high as an action row"); +} + +/// A click at `pos`, with the pointer moved there first. +fn click(fixture: &mut Fixture, pos: Pos2) { + fixture.frame(vec![pointer::moved(pos)]); + fixture.frame(vec![pointer::press(pos)]); + fixture.frame(vec![pointer::release(pos)]); + fixture.idle(2); +} + +/// In Button Mode every action is a button as wide as the others and the body; a click plays its action once. +#[trial] +fn actions_panel_button_mode_buttons_span_the_body_and_a_click_plays_once() { + let mut shown = app(two_sets()); + shown.state.settings.button_mode = true; + let (mut fixture, shared) = rig(shown); + let buttons: Vec = ["Loose", "First", "Second"].iter().map(|name| node(&fixture, name)).collect(); + let width = buttons[0].rect.width(); + assert!(buttons.iter().all(|button| button.rect.width() == width), "the buttons share one width: {buttons:?}"); + assert!(width > PANEL.x / 2.0, "a button spans the body, not its name ({width})"); + click(&mut fixture, buttons[1].center()); + let plays: Vec<_> = take(&shared).into_iter().filter(|event| matches!(event, ActionsEvent::Play { .. })).collect(); + assert!(matches!(plays.as_slice(), [ActionsEvent::Play { action: 1, from: 0 }]), "one Play of First: {plays:?}"); +} + +/// The sets a panel reported duplicating. +fn duplicates(events: &[ActionsEvent]) -> Vec { + events + .iter() + .filter_map(|event| match event { + ActionsEvent::Duplicate(row) => Some(row.clone()), + _ => None, + }) + .collect() +} + +/// Drags the row labelled `label` onto the footer's Create new action. +fn drag_onto_new_action(fixture: &mut Fixture, label: &str) { + let (from, to) = (node(fixture, label).center(), node(fixture, "Create new action").center()); + drag_to(fixture, from, to); +} + +/// An action row and a step row of the panel's own list dropped on Create new action each report one +/// Duplicate of that row; nothing is taken while recording or playing. +#[trial] +fn a_row_dropped_on_new_action_reports_duplicate() { + let mut shown = app(two_sets()); + shown.state.expanded.insert("Loose".into()); + let (mut fixture, shared) = rig(shown); + drag_onto_new_action(&mut fixture, "Loose"); + assert_eq!(duplicates(&take(&shared)), [ActionSelection::Action(0)]); + drag_onto_new_action(&mut fixture, "Run a"); + assert_eq!(duplicates(&take(&shared)), [ActionSelection::Step(0, 0)]); + + let mut playing = app(two_sets()); + playing.host.playing = true; + let (mut fixture, shared) = rig(playing); + drag_onto_new_action(&mut fixture, "Loose"); + assert_eq!(duplicates(&take(&shared)), [], "no drop is taken while playing"); + + let mut recording = app(two_sets()); + recording.host.recording = Some(1); + let (mut fixture, shared) = rig(recording); + drag_onto_new_action(&mut fixture, "Loose"); + assert_eq!(duplicates(&take(&shared)), [], "no drop is taken while recording"); +} + +/// A disabled panel reports nothing for a click on a row or a footer button. +#[trial] +fn actions_panel_disabled_reports_nothing() { + let shared = Rc::new(RefCell::new(app(two_sets()))); + let shown = Rc::clone(&shared); + let mut fixture = Fixture::new(move |ui| { + let App { state, list, host, events } = &mut *shown.borrow_mut(); + events.extend(ActionsPanel::new(state, list).host(&*host).enabled(false).show(ui).events); + }); + fixture.room(PANEL); + fixture.settle(); + for name in ["Loose", "Create new set"] { + let at = node(&fixture, name).center(); + click(&mut fixture, at); + } + assert_eq!(take(&shared), [], "a disabled panel reports no event"); + assert_eq!(shared.borrow().state.selected, None, "a click selects no row"); +} + +/// The panel menu's last group is Clear All Actions, Reset Actions…, Load Actions…, Replace Actions…, Save Actions…; +/// the three whole-list commands are off while recording, Clear All also with nothing to clear, and each reports +/// its event. +#[trial] +fn actions_panel_menu_offers_the_library_commands() { + use craft_automation::ui::actions::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands as C, panel_rows}; + use craft_ui::menu::PanelRow; + use craft_ui::runtime::commands::CommandRef; + let rows = panel_rows(ActionsMenuFacts::new(), &|_| true); + let last: Vec = rows.iter().rev().take_while(|row| !matches!(row, PanelRow::Separator)).map(|row| format!("{row:?}")).collect(); + let expected: Vec = + [C::Save, C::Replace, C::Load, C::Reset, C::ClearAll].into_iter().map(|c| format!("{:?}", PanelRow::Command(CommandRef::from(c)))).collect(); + assert_eq!(last, expected); + + let mut panel = ActionsPanelState::default(); + let list = list_of(vec![action("A", None, &["image.invert"])]); + let idle = ActionsMenuFacts::new(); + let recording = ActionsMenuFacts::new().recording(true); + for command in [C::ClearAll, C::Reset, C::Replace] { + assert!(command.state(&panel, &list, idle).is_enabled() && !command.state(&panel, &list, recording).is_enabled()); + } + assert!(!C::ClearAll.state(&panel, &ActionList::new(), idle).is_enabled()); + let events: Vec<_> = [C::ClearAll, C::Reset, C::Replace].into_iter().map(|c| c.run(&mut panel, &list, idle)).collect(); + assert_eq!(events, [ActionsEvent::ClearAll, ActionsEvent::Reset, ActionsEvent::Replace].map(|event| Some(ActionsMenuAction::Event(event)))); +} + +/// A step row has an include and a dialog cell, or with `StepCells::Include` the include cell only; a set row with steps +/// has an include cell whose press reports a toggle of the set, and a set without steps has none. +#[trial] +fn a_set_row_has_an_include_cell_and_the_include_variant_has_no_dialog_column() { + let mut shown = app(two_sets()); + shown.state.expanded.insert("First".into()); + let (fixture, _) = rig(shown); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "a step row has its include cell"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_some(), "and its dialog cell"); + + let mut list = two_sets(); + list.new_set("Hollow").unwrap(); + let mut shown = app(list); + shown.state.expanded.insert("First".into()); + let (mut fixture, shared) = rig_cells(shown, StepCells::Include); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "the include cell stays"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_none(), "the dialog cell is left out"); + assert!(fixture.by_label("Include in playback: Hollow").is_none(), "a set with no steps has no include cell"); + + let cell = node(&fixture, "Include in playback: Alpha"); + click(&mut fixture, cell.center()); + let toggled = take(&shared).into_iter().any(|event| { + matches!(event, ActionsEvent::Toggle(craft_ui::contract::SweepStep::Flip(edit)) + if edit.key == ActionSelection::Set("Alpha".into()) && edit.column == INCLUDE_COLUMN) + }); + assert!(toggled, "a press on a set's include cell reports a toggle of the set"); +} + +/// Shift on a later set row selects the sets between, across an expanded set's action rows; Delete reports the range in +/// one event; a click on an action clears the range. +#[trial] +fn shift_clicking_a_set_selects_the_range_and_delete_reports_it_once() { + let list = list_of(vec![ + action("Loose", None, &["a"]), + action("First", Some("Alpha"), &["b"]), + action("Second", Some("Beta"), &["c"]), + action("Third", Some("Gamma"), &["d"]), + ]); + let (mut fixture, shared) = rig(app(list)); + let (first, last) = (node(&fixture, "Alpha").center(), node(&fixture, "Gamma").center()); + click(&mut fixture, first); + fixture.hold(Modifiers::SHIFT); + click(&mut fixture, last); + fixture.hold(Modifiers::NONE); + let names = ["Alpha", "Beta", "Gamma"].map(str::to_owned).to_vec(); + assert_eq!(shared.borrow().state.selected_sets, names, "the sets between, in list order, not the actions among them"); + + take(&shared); + fixture.key(Key::Delete, Modifiers::NONE).idle(2); + let events = take(&shared); + let deletes: Vec<_> = events.iter().filter(|event| matches!(event, ActionsEvent::Delete(_) | ActionsEvent::DeleteSets(_))).collect(); + assert_eq!(deletes, [&ActionsEvent::DeleteSets(names)], "one event for the range"); + + let row = node(&fixture, "First").center(); + click(&mut fixture, row); + assert!(shared.borrow().state.selected_sets.is_empty(), "a click on an action ends the range"); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1))); +} + +/// A right-click at `pos`, with the pointer moved there first. +fn right_click(fixture: &mut Fixture, pos: Pos2) { + fixture.frame(vec![pointer::moved(pos)]); + fixture.frame(vec![pointer::secondary(pos, true)]); + fixture.frame(vec![pointer::secondary(pos, false)]); + fixture.idle(2); +} + +/// What the row `item` of the menu a right-click on `row` opens reports. +fn menu_ran(fixture: &mut Fixture, shared: &Shared, row: &str, item: &str) -> Vec { + let at = node(fixture, row).center(); + right_click(fixture, at); + let at = node(fixture, item).center(); + click(fixture, at); + take(shared) +} + +/// A right-click on an action or a set selects it and opens its menu, whose rows report their event for that row; +/// Play reports nothing while an action plays. +#[trial] +fn a_rows_menu_selects_the_row_and_reports_its_rows_for_it() { + let (mut fixture, shared) = rig(app(two_sets())); + assert_eq!(menu_ran(&mut fixture, &shared, "First", "Action Options…"), [ActionsEvent::ActionOptions(1)]); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1)), "the right-click selects the action"); + assert_eq!(menu_ran(&mut fixture, &shared, "Second", "Duplicate"), [ActionsEvent::Duplicate(ActionSelection::Action(2))]); + assert_eq!(menu_ran(&mut fixture, &shared, "Alpha", "Delete Set"), [ActionsEvent::Delete(ActionSelection::Set("Alpha".into()))]); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Set("Alpha".into())), "the right-click selects the set"); + + let mut playing = app(two_sets()); + playing.host.playing = true; + let (mut fixture, shared) = rig(playing); + assert_eq!(menu_ran(&mut fixture, &shared, "First", "Play"), [], "Play is off while an action plays"); +} diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs new file mode 100644 index 0000000000..7ca7bb5f0c --- /dev/null +++ b/crates/automation/tests/it/agents.rs @@ -0,0 +1,426 @@ +//! Agents in the open window: the launcher's switch, the connection file, the link host and the +//! Agents page. + +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use craft_automation::agents::AgentLinkStatus; +use craft_automation::agents::{ + AgentLink, AgentSettings, AgentSwitch, CONNECTION_FILE, Connection, LinkProblem, PROBE_TIMEOUT, TOKEN_FILE, agents_allowed, probe, + read_connection, remove_connection, remove_stale_connection, write_connection, +}; +use craft_automation::server; +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; +use egui::Context; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +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; + } + std::thread::sleep(Duration::from_millis(5)); + } + true +} + +/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. +#[trial] +fn with_the_flag_only_the_launchers_switch_lets_agents_in() { + assert!(agents_allowed(false, false, true), "without the flag, the app's earlier consent"); + assert!(!agents_allowed(false, true, false), "the launcher's list means nothing without the flag"); + assert!(agents_allowed(true, true, false)); + assert!(!agents_allowed(true, false, true), "no second switch in the app"); + assert!(AgentSwitch::fixed(true, true).allows(false)); + 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. +#[trial] +fn the_switch_wakes_once_per_change() { + let launcher = Arc::new(AtomicBool::new(false)); + let probes = Arc::new(AtomicUsize::new(0)); + let wakes = Arc::new(AtomicUsize::new(0)); + let probe = { + let (launcher, probes) = (launcher.clone(), probes.clone()); + move || { + probes.fetch_add(1, Ordering::Relaxed); + launcher.load(Ordering::Relaxed) + } + }; + let wake = { + let wakes = wakes.clone(); + move || { + wakes.fetch_add(1, Ordering::Relaxed); + } + }; + let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let clone = switch.clone(); + assert!(!switch.launcher()); + + launcher.store(true, Ordering::Relaxed); + assert!(wait_for(|| 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)); + launcher.store(false, Ordering::Relaxed); + assert!(wait_for(|| !switch.launcher())); + assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); + + drop(switch); + 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"); +} + +/// A published connection reads back in its documented shape, and only the process that wrote it removes it. +#[trial] +fn a_published_connection_reads_back_and_only_its_writer_removes_it() { + let dir = temp_dir("conn"); + let dir = dir.path(); + assert_eq!(read_connection(dir).unwrap(), None, "no file"); + let c = Connection::new(7878, dir.join(TOKEN_FILE), "MyApp 1.2.3"); + write_connection(dir, &c).unwrap(); + assert_eq!(read_connection(dir).unwrap(), Some(c.clone())); + assert_eq!(c.addr(), "127.0.0.1:7878"); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join(CONNECTION_FILE)).unwrap()).unwrap(); + let mut keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["app", "pid", "port", "tokenFile", "version"]); + assert_eq!((v["version"].as_u64(), v["port"].as_u64(), v["app"].as_str()), (Some(1), Some(7878), Some("MyApp 1.2.3"))); + + remove_connection(dir, c.pid.wrapping_add(1)); + assert!(dir.join(CONNECTION_FILE).is_file(), "another process's file stays"); + remove_connection(dir, c.pid); + assert!(!dir.join(CONNECTION_FILE).exists()); +} + +/// A damaged, foreign or port-0 file reads as none; a directory in its place is an error and is left alone; a file +/// nobody listens on is removed as stale and a live one kept. +#[trial] +fn a_damaged_foreign_or_stale_connection_file_counts_as_none() { + let dir = temp_dir("bad-conn"); + let dir = dir.path(); + for text in [ + &b""[..], + b"{not json", + b"[]", + br#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, + br#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#, + b"\xff\xfe not utf-8", + ] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(dir).unwrap(), None, "{}", String::from_utf8_lossy(text)); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + } + + std::fs::create_dir(dir.join(CONNECTION_FILE)).unwrap(); + assert!(read_connection(dir).is_err()); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_dir(), "anything but a regular file is left alone"); + std::fs::remove_dir(dir.join(CONNECTION_FILE)).unwrap(); + + let live = TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = live.local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(live_port, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_file(), "something listens on {live_port}"); + drop(live); + let closed = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); +} + +fn host() -> WindowHost { + WindowHost::of(&Context::default()) +} + +fn on(port: u32) -> AgentSettings { + let mut s = AgentSettings::default(); + s.control_port = port; + s +} + +/// A port nothing listens on: bound, then closed. +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +/// Off publishes nothing; on publishes the bound port and this process, and something answers there; a folder-only +/// change keeps the port and gives no new channel; off removes the file and frees the port. +#[trial] +fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() { + let dir = temp_dir("link"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "MyApp 1.0"); + let off = link.sync(None, &host); + assert!(off.requests.is_none() && !off.stopped && !off.changed); + assert_eq!(read_connection(dir.path()).unwrap(), None); + + let started = link.sync(Some(&on(0)), &host); + assert!(started.requests.is_some() && started.changed); + let port = link.status().port.expect("listening"); + let c = read_connection(dir.path()).unwrap().expect("published"); + assert_eq!((c.port, c.pid, c.app.as_str()), (port, std::process::id(), "MyApp 1.0")); + assert!(probe(port, PROBE_TIMEOUT)); + let token = std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(); + + let mut folders = on(0); + folders.read_root = "/in".into(); + let kept = link.sync(Some(&folders), &host); + assert!(kept.requests.is_none() && !kept.stopped && kept.changed, "a folder change keeps the server"); + assert_eq!(link.status().port, Some(port)); + assert_eq!(std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(), token); + + let stopped = link.sync(None, &host); + assert!(stopped.stopped && stopped.changed); + assert_eq!(link.status().port, None); + assert!(!dir.path().join(CONNECTION_FILE).exists()); + TcpListener::bind(("127.0.0.1", port)).expect("the port is free"); +} + +/// A new port restarts the server with the same token; a taken port is named, publishes nothing, and is tried again +/// without a setting change until it is free. +#[trial] +fn a_new_port_restarts_with_the_same_token_and_a_taken_port_is_retried() { + let dir = temp_dir("link-port"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + assert!(link.sync(Some(&on(0)), &host).requests.is_some()); + let token = std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(); + + let wanted = free_port(); + let moved = link.sync(Some(&on(u32::from(wanted))), &host); + assert!(moved.stopped && moved.requests.is_some()); + assert_eq!(link.status().port, Some(wanted)); + assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, wanted); + assert_eq!(std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(), token, "the token is kept across restarts"); + + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let taken_port = taken.local_addr().unwrap().port(); + let failed = link.sync(Some(&on(u32::from(taken_port))), &host); + assert!(failed.stopped && failed.requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { port, .. }) if port == taken_port), "{:?}", link.status()); + assert_eq!(link.status().port, None); + assert_eq!(read_connection(dir.path()).unwrap(), None, "nothing listens without a file, and no file without a listener"); + + // Still taken: the retry fails the same way and changes nothing. + let again = link.sync(Some(&on(u32::from(taken_port))), &host); + assert!(again.requests.is_none() && !again.changed); + drop(taken); + let retried = link.sync(Some(&on(u32::from(taken_port))), &host); + assert!(retried.requests.is_some() && retried.changed, "freeing the port is enough"); + assert_eq!(link.status().port, Some(taken_port)); + assert_eq!(link.status().problem, None); + assert_eq!(std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(), token); + + // A port setting outside 0..=65535 is a problem, not a random port. + let out = link.sync(Some(&on(70_000)), &host); + assert!(out.requests.is_none()); + assert_eq!(link.status().problem, Some(LinkProblem::PortOutOfRange(70_000))); + assert_eq!(link.status().port, None); + assert_eq!(read_connection(dir.path()).unwrap(), None, "the listener stopped and no file is left"); +} + +/// Ten syncs with the same settings start one server. +#[trial] +fn an_unchanged_sync_starts_nothing() { + let dir = temp_dir("link-same"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + let updates: Vec<_> = (0..10).map(|_| link.sync(Some(&on(0)), &host)).collect(); + assert_eq!(updates.iter().filter(|u| u.requests.is_some()).count(), 1); + assert_eq!(updates.iter().filter(|u| u.changed).count(), 1); + assert!(updates.iter().all(|u| !u.stopped)); + assert!(link.status().port.is_some()); +} + +/// Allow Agent Control off, no settings folder and an unusable token file each keep agents out: no channel, no file, +/// and the port is free. +#[trial] +fn allow_agent_control_off_and_no_settings_folder_keep_agents_out() { + let host = host(); + let dir = temp_dir("link-off"); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host).requests.is_some()); + let port = link.status().port.expect("listening"); + let mut off = on(0); + off.allow_agent_control = false; + let refused = link.sync(Some(&off), &host); + assert!(refused.stopped && refused.requests.is_none()); + assert_eq!(link.status().problem, Some(LinkProblem::NotAllowed)); + assert!(!dir.path().join(CONNECTION_FILE).exists()); + TcpListener::bind(("127.0.0.1", port)).expect("the port is free"); + + let mut homeless = AgentLink::new(None, "x"); + assert!(homeless.sync(Some(&on(0)), &host).requests.is_none()); + assert_eq!(homeless.status().problem, Some(LinkProblem::NoSettingsFolder)); + + let bad = temp_dir("link-token"); + std::fs::create_dir(bad.path().join(TOKEN_FILE)).unwrap(); + let wanted = free_port(); + let mut link = AgentLink::new(Some(bad.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + assert!(!bad.path().join(CONNECTION_FILE).exists()); + TcpListener::bind(("127.0.0.1", wanted)).expect("nothing listens"); + let status = serde_json::to_value(link.status()).unwrap(); + assert!(status["error"].as_str().unwrap().starts_with("Agents can't connect: the token file"), "{status}"); +} + +/// A token file that can't be written (here the settings folder is a file) keeps agents out: the problem is reported, +/// nothing is published and the port is let go. +#[trial] +fn a_token_file_that_cannot_be_written_keeps_agents_out() { + let dir = temp_dir("link-token-folder"); + let settings = dir.path().join("not-a-folder"); + std::fs::write(&settings, b"").unwrap(); + let port = free_port(); + let mut link = AgentLink::new(Some(settings), "x"); + assert!(link.sync(Some(&on(u32::from(port))), &host()).requests.is_none()); + assert_eq!(link.status().port, None); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); +} + +/// Dropping the link stops its server and removes its connection file. +#[trial] +fn dropping_the_link_removes_its_connection_file() { + let dir = temp_dir("link-drop"); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host()).requests.is_some()); + let port = link.status().port.expect("listening"); + drop(link); + assert!(!dir.path().join(CONNECTION_FILE).exists()); + TcpListener::bind(("127.0.0.1", port)).expect("the port is free"); +} + +/// A server the launch options started is reported with its port, and the settings change nothing. +#[trial] +fn from_launch_reports_the_launch_flags() { + let (_requests, server) = server::listen(0, "0".repeat(64), host()).expect("started"); + let port = server.addr.port(); + let mut link = AgentLink::from_launch(server); + assert_eq!((link.status().port, link.status().launch_flags), (Some(port), true)); + let update = link.sync(None, &host()); + assert!(!update.stopped && !update.changed && update.requests.is_none()); + assert_eq!(link.status().port, Some(port)); + assert_eq!(serde_json::to_value(link.status()).unwrap(), serde_json::json!({"port": port, "launchFlags": true, "error": null})); +} + +/// The page over a draft, in a fixture whose host is named `"Studio"` and answers picks when the test says. +struct Page { + fixture: Fixture, + draft: Rc>, + files: Arc, + browsing: Rc>>, +} + +fn page(mcp_flag: bool, status: AgentLinkStatus) -> Page { + let files = Arc::new(ScriptedFiles::held()); + let draft = Rc::new(RefCell::new(SettingsDraft::default())); + let browsing = Rc::new(Cell::new(None)); + let (held, issued) = (Rc::clone(&draft), Rc::clone(&browsing)); + let mut fixture = Fixture::new(move |ui| { + let out = AgentsPage::new("integrations", &mut held.borrow_mut(), &status).mcp_flag(mcp_flag).show(ui); + if out.browsing.is_some() { + issued.set(out.browsing); + } + }); + fixture.host(Arc::new(Host::builder(AppInfo { id: "studio", name: "Studio", version: "1.0" }).files(files.clone()).build())); + fixture.settle(); + Page { fixture, draft, files, browsing } +} + +fn shows(fixture: &Fixture, text: &str) -> bool { + fixture.by_label(text).is_some() +} + +/// With the flag the page names the launcher's switch, has no switch of its own, and says where the link stands. +#[trial] +fn with_the_flag_the_page_points_to_the_launcher() { + let intro_part = "ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps"; + let off = page(true, AgentLinkStatus::default()); + let intro = off + .fixture + .tree() + .keys() + .into_iter() + .filter_map(|node| off.fixture.tree().name_of(node).map(str::to_owned)) + .find(|name| name.contains(intro_part)); + assert!(intro.is_some(), "the intro names the launcher's switch"); + assert!(shows(&off.fixture, "Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents.")); + assert!(shows(&off.fixture, "Folder agents can open from") && shows(&off.fixture, "Folder agents can save to")); + assert!(!shows(&off.fixture, "Allow Agent Control"), "no switch of its own"); + assert!(!shows(&off.fixture, "Let AI agents connect (MCP)")); + + let on = page(true, AgentLinkStatus { port: Some(4321), ..AgentLinkStatus::default() }); + assert!(shows(&on.fixture, "Agents can connect on 127.0.0.1:4321.")); +} + +/// Without the flag only the settings the app had before the switch show. +#[trial] +fn without_the_flag_only_the_earlier_settings_show() { + let legacy = page(false, AgentLinkStatus::default()); + assert!(shows(&legacy.fixture, "Allow Agent Control") && shows(&legacy.fixture, "Control Port")); + assert!(!shows(&legacy.fixture, "Folder agents can open from")); + assert!(!shows(&legacy.fixture, "Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents.")); +} + +/// Browse on the open-from folder asks the host for a folder; the answer lands in that key of the draft only. +#[trial] +fn browse_puts_the_chosen_folder_in_the_draft() { + let mut page = page(true, AgentLinkStatus::default()); + let browse: Vec<_> = + page.fixture.by_role(Role::BUTTON).into_iter().filter(|button| page.fixture.tree().name_of(button.node) == Some("Browse…")).collect(); + assert_eq!(browse.len(), 2, "one Browse per folder"); + page.fixture.click(&browse[0]); + page.fixture.settle(); + let id = page.browsing.get().expect("Browse filed a pick"); + assert!(page.files.answer_to(id, Picked::Paths(vec![PathBuf::from("/work/in")])), "the pick is open"); + page.fixture.idle(3); + let draft = page.draft.borrow(); + assert_eq!(draft.get::("integrations.readRoot").as_deref(), Some("/work/in")); + assert_eq!(draft.get::("integrations.writeRoot"), None, "the other folder is untouched"); +} + +/// The closed-app choice names the host's app, and a pick writes its saved name. +#[trial] +fn the_closed_app_choice_names_the_app() { + let mut page = page(true, AgentLinkStatus::default()); + assert!(shows(&page.fixture, "When Studio is closed")); + let field = page.fixture.by_role(Role::COMBO_BOX).first().copied().expect("the choice shows"); + assert_eq!(page.fixture.tree().value_of(field.node), Some("Open Studio")); + page.fixture.click(&field); + page.fixture.idle(3); + assert!(shows(&page.fixture, "Ask to open Studio")); + let headless = page.fixture.by_label("Work without a window").expect("the menu lists the choices"); + page.fixture.click(&headless); + page.fixture.idle(3); + assert_eq!(page.draft.borrow().get::("integrations.whenAppClosed").as_deref(), Some("headless")); +} diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs new file mode 100644 index 0000000000..913d02d16a --- /dev/null +++ b/crates/automation/tests/it/control.rs @@ -0,0 +1,494 @@ +//! `ControlChannel` deadlines and the loopback server's limits: connections, request size, authentication. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::mpsc::{Receiver, channel}; +use std::time::Duration; + +use craft_automation::client::ControlClient; +use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; +use craft_automation::protocol::MAX_RESPONSE_BYTES; +use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; +use craft_automation::server; +use craft_ui::runtime::motion; +use craft_ui::runtime::windows::WindowHost; +use craft_ui::testing::trial; +use egui::Context; +use serde_json::{Value, json}; + +/// An expired queued request is replied `expired_error` and never dispatched; a dispatched one that times out gets +/// `timeout_error`. +#[trial] +fn deadlines_distinguish_expired_from_timed_out() { + let (tx, rx) = channel(); + let mut channel = ControlChannel::new(rx); + + let (mut stale, stale_reply) = ControlRequest::new("ui.inspect", json!({})); + stale.deadline = Some(motion::now() - Duration::from_secs(1)); + let stale_dispatch = stale.dispatch.clone(); + let (live, _live_reply) = ControlRequest::new("ui.key", json!({})); + let live_dispatch = live.dispatch.clone(); + tx.send(stale).expect("sent"); + tx.send(live).expect("sent"); + + let next = channel.next_request().expect("the live request is dispatched"); + assert_eq!(next.method, "ui.key"); + assert!(channel.next_request().is_none()); + assert_eq!(stale_reply.try_recv().expect("a reply"), json!({"ok": false, "error": expired_error()})); + assert_eq!(stale_dispatch.give_up(), expired_error()); + assert_eq!(live_dispatch.give_up(), timeout_error()); + assert!(timeout_error().starts_with("timeout:") && expired_error().starts_with("timeout:")); + + // A request the transport abandoned before the UI thread claimed it is not run. + let (abandoned, abandoned_reply) = ControlRequest::new("ui.click", json!({})); + let _ = abandoned.dispatch.give_up(); + tx.send(abandoned).expect("sent"); + assert!(channel.next_request().is_none()); + assert_eq!(abandoned_reply.try_recv().expect("a reply")["error"], json!(expired_error())); +} + +/// A request sent without a deadline runs even when nobody waits for its reply any more: a fire-and-forget step +/// (a key press, a release) still happens. +#[trial] +fn a_request_without_a_deadline_is_dispatched_after_its_reply_receiver_is_dropped() { + let (tx, rx) = channel(); + let mut channel = ControlChannel::new(rx); + + let (request, reply) = ControlRequest::new("ui.key", json!({"key": "Escape"})); + assert!(request.deadline.is_none(), "a new request has no deadline"); + drop(reply); + tx.send(request).expect("sent"); + + let next = channel.next_request().expect("the deadline-free request is dispatched"); + assert_eq!(next.method, "ui.key"); + assert_eq!(next.params, json!({"key": "Escape"})); + assert!(channel.next_request().is_none(), "the request runs once"); +} + +/// A job's reply goes to the requests waiting on that job only, as the app built it (an error with partial results +/// keeps both); the other job's waiter keeps waiting. +#[trial] +fn a_finished_job_answers_only_its_own_waiters() { + let (_tx, rx) = channel(); + let mut channel = ControlChannel::new(rx); + let (first, first_reply) = ControlRequest::new("engine.execute", json!({})); + let (second, second_reply) = ControlRequest::new("engine.execute", json!({})); + channel.settle(first, Reply::AfterJob(1), None, 0.0); + channel.settle(second, Reply::AfterJob(2), None, 0.0); + + let partial = json!({"ok": false, "error": "cancelled", "result": {"files": ["done.png"]}}); + channel.job_finished(1, &partial); + assert_eq!(first_reply.try_recv().expect("job 1 replied"), partial); + assert!(second_reply.try_recv().is_err(), "job 2 still runs"); + assert_eq!(channel.waiting(), 1); + + channel.job_finished(2, &result_reply(Ok(json!(7)))); + assert_eq!(second_reply.try_recv().expect("job 2 replied"), json!({"ok": true, "result": 7})); +} + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +fn read_json(reader: &mut impl BufRead) -> Option { + let mut line = String::new(); + (reader.read_line(&mut line).ok()? > 0).then(|| serde_json::from_str(&line).expect("a JSON line")) +} + +fn host() -> WindowHost { + WindowHost::of(&Context::default()) +} + +/// A connection that keeps sending without authenticating is closed at the deadline, whatever it sends, and nothing it +/// sent is dispatched. +#[trial] +fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { + // A short deadline, so the test does not wait out the real one. + let deadline = Duration::from_millis(400); + let listener = TcpListener::bind("127.0.0.1:0").expect("bound"); + let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started"); + // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout. + let mut stream = TcpStream::connect(server.addr).expect("connected"); + let started = motion::now(); + let mut closed = false; + for i in 0..1000 { + let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " }; + if stream.write_all(byte).is_err() { + closed = true; + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + let served = started.elapsed(); + assert!(closed, "the trickle did not keep the connection open"); + assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}"); + assert!(rx.try_recv().is_err(), "nothing was dispatched"); +} + +/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +fn is_closed(reader: &mut impl BufRead) -> bool { + let mut line = String::new(); + matches!(reader.read_line(&mut line), Ok(0)) +} + +/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of +/// the open ones ends, its place serves a new connection. +#[trial] +fn connections_past_the_limit_are_refused_with_the_reason() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let connect = || { + let stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let reader = BufReader::new(stream.try_clone().expect("cloned")); + (stream, reader) + }; + // Unauthenticated, so each holds its place until it closes or the authentication deadline passes. + let mut open: Vec = (0..MAX_CONNECTIONS).map(|_| connect().0).collect(); + + let (_extra, mut reader) = connect(); + let refused = read_json(&mut reader).expect("a refusal"); + assert_eq!(refused, json!({"id": null, "ok": false, "error": "connection limit reached"})); + assert!(is_closed(&mut reader), "the refused connection is closed"); + + drop(open.pop()); + // The server frees the place when it reads the close; a new connection is served once it has. + let started = motion::now(); + let served = loop { + let (mut stream, mut reader) = connect(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + let reply = read_json(&mut reader).expect("a reply"); + if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) { + break reply; + } + assert_eq!(reply["error"], "connection limit reached", "{reply}"); + std::thread::sleep(Duration::from_millis(20)); + }; + assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); + assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop(open); +} + +/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the +/// connection closes at once, without waiting for the deadline and without dispatching anything: a client cannot keep +/// guessing on one connection. +#[trial] +fn a_refused_first_frame_closes_the_connection() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let wrong = "f".repeat(TOKEN.len()); + for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))] + { + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{first}").expect("written"); + assert_eq!(read_json(&mut reader).expect("a refusal"), json!({"id": id, "ok": false, "error": "authentication required"}), "{first}"); + // The server may already have closed while this is written. + let _ = writeln!(stream, "{}", json!({"id": 5, "method": "auth", "params": {"token": TOKEN}})); + assert!(is_closed(&mut reader), "{first}: the connection is closed, the second guess unanswered"); + } + assert!(rx.try_recv().is_err(), "nothing was dispatched"); +} + +/// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line +/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. +#[trial] +fn a_browser_post_never_reaches_the_app() { + // Far longer than the trial, so the close comes from the refusal, not the deadline. + let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) + .expect("started"); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + let body = format!("{}\n{}\n", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}}), json!({"id": 2, "method": "test.ping"})); + write!(stream, "POST / HTTP/1.1\r\n").expect("written"); + let refused = read_json(&mut reader).expect("a reply to the request line"); + assert_eq!(refused["ok"], false, "{refused}"); + assert_eq!(refused["error"], "authentication required", "{refused}"); + // The rest of what the browser sends; the server may already have closed. + let _ = write!(stream, "Host: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", body.len()); + let _ = stream.flush(); + let mut rest = String::new(); + let closed = match reader.read_line(&mut rest) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + }; + assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); + assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); +} + +/// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. +#[trial] +fn an_over_long_request_is_refused_and_closes_the_connection() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true); + // The server may close while this is still being written. + let _ = stream.write_all(&vec![b'x'; MAX_REQUEST_BYTES + 16]); + let reply = read_json(&mut reader).expect("a reply"); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().expect("an error").starts_with("request exceeds"), "{reply}"); + assert!(read_json(&mut reader).is_none(), "the connection is closed"); + assert!(rx.try_recv().is_err()); +} + +/// Answers the next request, which must be `test.ping`, with `pong`. +fn answer_one_ping(rx: Receiver) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + assert_eq!(req.method, "test.ping"); + let pong: ControlResponse = json!({"ok": true, "result": "pong"}); + req.reply.send(pong).expect("replied"); + }) +} + +/// Authenticates with the one-frame token, sends `test.ping` and returns its reply. +fn ping(addr: SocketAddr) -> Value { + let mut stream = TcpStream::connect(addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true); + writeln!(stream, "{}", json!({"id": 2, "method": "test.ping"})).expect("written"); + read_json(&mut reader).expect("a reply") +} + +/// A server on port 0 reports the port it bound, serves, and after it is dropped the port binds again at once; dropping +/// one server leaves another one serving. +#[trial] +fn a_listening_server_stops_when_dropped_and_frees_its_port() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (other_rx, other) = server::listen(0, TOKEN.into(), host()).expect("started"); + let addr = server.addr; + assert_ne!(addr.port(), 0); + let handler = answer_one_ping(rx); + assert_eq!(ping(addr), json!({"id": 2, "ok": true, "result": "pong"})); + handler.join().expect("handler ran"); + + drop(server); + TcpListener::bind(addr).expect("the port is free once the server is dropped"); + + let handler = answer_one_ping(other_rx); + assert_eq!(ping(other.addr), json!({"id": 2, "ok": true, "result": "pong"})); + handler.join().expect("handler ran"); +} + +/// A connection that authenticates with the challenge handshake learns the server holds the token, never sends it, +/// and then has its requests dispatched. +#[trial] +fn a_challenge_authenticated_connection_is_served() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let handler = answer_one_ping(rx); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + let client_nonce = generate_nonce().expect("a nonce"); + writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).expect("written"); + let challenge = read_json(&mut reader).expect("a reply"); + let server_nonce = challenge["result"]["serverNonce"].as_str().expect("a server nonce").to_owned(); + let server_proof = challenge["result"]["serverProof"].as_str().expect("a server proof"); + assert!(proof_matches(TOKEN, ProofRole::Server, &client_nonce, &server_nonce, server_proof), "{challenge}"); + let proof = handshake_proof(TOKEN, ProofRole::Client, &client_nonce, &server_nonce).expect("a proof"); + writeln!(stream, "{}", json!({"id": 2, "method": "auth", "params": {"proof": proof}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["result"]["authenticated"], true); + writeln!(stream, "{}", json!({"id": 3, "method": "test.ping"})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply"), json!({"id": 3, "ok": true, "result": "pong"})); + handler.join().expect("handler ran"); +} + +/// Sends one state of a states file and saves its capture as `