Compare commits

..
Author SHA1 Message Date
skylartaylor e9c97bdb50 fix(nightly): the review's data-safety, probe and fixture findings
* The write probe used `std::fs::write` on a fixed name, which truncated and then
  deleted whatever regular file already sat there; it now creates a fresh name with
  `create_new`, takes the next when one is taken, and removes only its own file.
* The plugin preset Save wrote with `std::fs::write` through a link at the plugin's
  folder or at the preset file, so a Nightly profile could write outside itself.
  `save_preset` refuses a folder or file that is not a real entry and stages the
  body in the same folder, renaming it over the name (a rename replaces a link).
* The Linux check looked for stable folders at `$xdg/config` and `$xdg/data` while
  it sets `$xdg/c` and `$xdg/d`, so it could pass with stable state created.
* `package-tar-test.sh` assumed an x86_64 archive name; it derives the label the
  same way `package.sh` does.
* The Windows signing fixture derived a fake `...gaaaaaaaaaaaa` identity and set no
  build sha or date, so source validation threw before the mocked compiler; it now
  derives all three from the checkout, as the other ports' fixtures do.
* `build_channel`'s tests are now compiled into the app's test build (`#[cfg(test)]
  mod build_channel;`), as in the sibling ports, instead of never running.
2026-11-25 01:41:15 +01:00
skylartaylor e7322ec4df nightly: enforce the signing guard and read the whole push mapping
- `nightly_compile_gui` calls `nightly_refuse_signing_env` before cargo, so an exported signing key
  cannot reach the compiler or a dependency build script.
- The candidate-workflow check reads the whole `push:` mapping by indentation, so a `paths` filter
  after a blank line is still rejected; a negative fixture covers that layout.
2026-11-25 00:59:29 +01:00
skylartaylor e194e2b71b Nightly: fix the Batch 2A review findings
- Cargo.lock: record winsafe in the soundcraft package, so every --locked
  leg (nightly and stable) resolves again.
- rustfmt over config, main, nightly_session, process_identity and
  profile_root, the five files the repo's fmt gate rejected.
- Drop the duplicated #[test] left in profile_root's tests.
- pt-BR: add "Report a problem" and "Updated by ArtCraft Launcher.", so
  the ui-egui catalog test passes.
- Nightly has no in-app updater: the UI runtime carries the launch's
  service gate, and check, tick, show and start_pending_update return
  before touching craft-update. The Check for Updates entry is not built,
  and the command answers that ArtCraft Launcher owns updates.
- Keep Stable's window title byte for byte in both menu-bar states and
  substitute only the channel's name; pin all four combinations.
- Collapse the FLATPAK_ID fence into one let-chain (collapsible_if).

Also: the README Nightly version row shows the prefix the binary prints,
the Linux Flatpak refusal check requires exit status 2 instead of passing
on any failure, the tar test's shebang is /usr/bin/env bash, and
ATTRIBUTION.md lists the Nightly icons.
2026-11-25 00:12:29 +01:00
skylartayloranddylanmtaylor 835cc9c6b5 Nightly: every Linux format launches with the flavor's profile
On top of dylanmtaylor's Linux packaging (#1740): the deb/rpm wrapper, the Arch launcher, the
Flatpak wrapper, the AppImage AppRun and a new launcher inside both tarballs exec the GUI with
`--launch-profile nightly-v1 --profile-root <dir> --`, passing a Launcher protocol or a --version
query through untouched, so nothing writes stable's settings folder and an unpacked tar is
isolated too. The FHS tar ships `soundcraft` beside `soundcraft-bin`, the Nightly metainfo drops
the MIME type its package no longer installs, nightly-common.sh passes the build channel and
checks both version forms against the prepared identity, the Nightly Flatpak's own app id is the
one Flatpak the profile fence accepts, and the archive and launcher suites run in packaging-lint.

Co-authored-by: dylanmtaylor <dylanmtaylor@users.noreply.github.com>
2026-11-24 23:12:29 +01:00
skylartaylor 80c5d82638 nightly: add the isolated SoundCraft Nightly flavor and its Windows and macOS packaging
On top of @dylanmtaylor's Linux Nightly work (#1740), the app-side flavor and the other two
platforms:

- build.rs/build_channel: SOUNDCRAFT_BUILD_CHANNEL=nightly-v1 sets cfg(soundcraft_nightly_v1),
  requires the exact feed identity (SOUNDCRAFT_VERSION, or the packaging scripts'
  SOUNDCRAFT_OVERRIDE_VERSION for the same value), and embeds the Nightly icon,
  ProductName "SoundCraft Nightly" and that version as ProductVersion.
- launch_profile: the Launcher's `--launch-profile nightly-v1 --profile-root <abs> -- <files>`
  protocol, and its `--version` form answered before any root, logger, window or dialog.
- profile_root: the Nightly root is fenced against every stable data root, install folder,
  portable install, an inherited SOUNDCRAFT_CONFIG_DIR and a Flatpak instance, then created 0700
  and probed through the app's own writer; no stable fallback. The refusal names the wrapper fix.
- config: one override makes the profile the settings folder, so ui.json, Autosave/, Presets/
  and logs/ all land inside it. SoundCraft uses no eframe storage and no single-instance socket,
  and its only IPC (the control server) and updater are off in Nightly.
- os_window/channel_titles/services: distinct app id and window id, channel caption, About
  channel and version, and an exit hook that runs once from on_exit (macOS's only exit path).
- nightly_session: lease plus unclean-exit record under the profile.
- process_identity: the explicit Windows AUMID for Nightly only.
- Packaging: macos/{nightly.sh,nightly-lib.sh,nightly-sign.sh,nightly-verify.sh,nightly_plist.py},
  windows/{nightly.ps1, package.ps1 -Nightly -BuildOnly, sign.ps1 -Required/-CheckOnly/-CheckBuildEnvironment},
  the Nightly icon set derived from the stable art, and their synthetic suites.
- Two lines in @dylanmtaylor's files, for the flavor: nightly-common.sh checks the exact
  `SoundCraft <version> (nightly-v1)` line now that it exists, and linux/nightly.sh stages the
  real Nightly icon instead of the 1024 px stand-in.
- nightly-build.yml runs all three real scripts behind the full-ci label or a dispatch, with no
  secrets, and checks the archive, the version query and the isolation refusals.
2026-11-24 22:30:26 +01:00
Dylan M. Taylor 60502e950a packaging: port Linux nightly script and archive helpers from PhotoCraft 2026-11-24 16:17:47 -05:00
Dylan M. Taylor 790c71c381 fix(linux-packaging): isolate nightly config dir, fix Exec sed delimiter, and satisfy SonarCloud 2026-11-24 15:26:34 -05:00
Dylan M. Taylor c27eb7b3a7 Fix actionlint workflow concurrency key and channel-only nightly artifact basename 2026-11-24 14:21:21 -05:00
Dylan M. Taylorandskylartaylor f145a47331 ci(nightly): enable nightly workflows for supervised manual runs
Port Skylar's (@skylartaylor) storytold/photocraft#16594 to SoundCraft:
- Add `.github/nightly-signing-policy.json` (v3 policy adapted for `storytold/soundcraft`, CI workflow `380135771`, and `storytold_soundcraft` SonarCloud project).
- Add `.github/workflows/nightly.yml` and `.github/workflows/nightly-sign.yml` pinned to `craft-common-actions@605d58766e8f536564da8fc81d3676ac86816dea` for supervised manual `workflow_dispatch` runs by release managers.
- Add `docs/nightly-release-preparation.md` and `packaging/nightly-release-tests.py` local contract tests.

Credit: @skylartaylor (storytold/photocraft#16594)

Co-authored-by: skylartaylor <hi@skylar.cc>
2026-11-24 14:14:36 -05:00
Dylan M. Taylor 6b811d1103 packaging(linux): support co-installable nightly packages 2026-11-24 13:33:40 -05:00
201 changed files with 1678 additions and 12419 deletions
-16
View File
@@ -1,16 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+11 -13
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/soundcraft",
"repository_id": 1408486424,
"producer_workflow_id": 429730684,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
@@ -44,20 +44,18 @@
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"accepted_conditions": [],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
+1 -1
View File
@@ -214,7 +214,7 @@ jobs:
with:
persist-credentials: false
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@main
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
+7 -24
View File
@@ -1,8 +1,7 @@
name: SoundCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
@@ -23,37 +22,21 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/soundcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: main
app-name: soundcraft
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
# callee job may bind the existing release environment and export keys in its signing step.
+6 -7
View File
@@ -1,7 +1,7 @@
name: SoundCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
# A later explicit opt-in may add a cadence (and a reviewed dispatcher with it).
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
@@ -22,14 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: main
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: soundcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
-20
View File
@@ -1,20 +0,0 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
-1
View File
@@ -81,7 +81,6 @@ Layers, checked by `cargo xtask layers`; nothing below L6 depends on egui, efram
- Audio formats, codecs and waveform peaks come from `craft-audio` in `storytold/craft-libs`; `soundcraft_model::FileFormat` maps them onto the session model.
- Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`), each module with its own `specs()` registered in `crates/engine/src/cmd.rs`; UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Menus, shortcuts, CLI, control channel and MCP dispatch the same ids. Panels act through `engine.execute(id, params)`. Programmatic calls open no dialogs; `ui.menu.invoke` does.
- Parity: `crates/engine/catalog/menus.txt` lists the reference menu leaves; `cargo xtask parity` writes `docs/parity-checklist.md`; a test enforces a floor that only rises.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): the parity report marks a leaf `headless: yes` only when the engine registry implements it (what `soundcraft-cli` and the MCP server load); the UI layer's `parity_with` extras never count. Other leaves take their `no`/`partial` value and `reach:` (`window`, `os`, `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or read `unknown`. When a command lands, drop or narrow its mark; `headless_marks_are_current` fails on one that only hides a `yes`.
- Progress docs: `ROADMAP.md`, `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md` and the per-area `docs/*-parity.md`. Releases: `docs/releasing.md` (push to `release`; `cargo xtask version [set X.Y.Z]`). Control protocol: `docs/control-protocol.md`.
### Checks
Generated
+80 -1302
View File
File diff suppressed because it is too large Load Diff
+28 -35
View File
@@ -11,9 +11,9 @@ rust-version = "1.95"
repository = "https://github.com/storytold/soundcraft"
[workspace.dependencies]
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
# internal
soundcraft-interchange = { path = "crates/interchange" }
soundcraft-time = { path = "crates/time" }
@@ -61,34 +61,27 @@ cpal = "0.18"
midir = "=0.11.1"
# Which file paths stored in a session may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
# Video containers and bitstreams, shared with the other craft apps.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
# H.264 and ProRes codecs shared with the other Craft apps.
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
# Audio file formats, codecs and waveform overviews, shared with the other craft apps. It shares
# types with craft-media, so both stay on one rev.
# Standard MIDI Files and the note/controller model, shared with the other craft apps.
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
# AAF property-stream framing, shared with the other craft apps.
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["egui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode
# the framework's components draw in (craft-libs).
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
egui = { version = "0.37" }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -131,18 +124,18 @@ debug = 0
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "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" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+3 -9
View File
@@ -88,7 +88,7 @@ where things are.
</tr>
<tr>
<td><b>Automation and markers.</b> Breakpoint automation for volume, pan, mute, sends and every plugin parameter, written live in Write, Touch and Latch, plus memory locations and a big counter.</td>
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64 and ARM64), Linux (AppImage, deb, rpm, Flatpak, Arch), FreeBSD, and a WebAssembly build that runs in the browser.</td>
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64, x86, Arm), Linux (AppImage, deb, rpm, Flatpak), FreeBSD, and a WebAssembly build that runs in the browser.</td>
</tr>
<tr>
<td width="50%"><img alt="The Video window showing a colour-bar test movie with a timecode burn-in, above a Video track with thumbnails in the Edit window" src="docs/images/video.png"></td>
@@ -302,9 +302,7 @@ very welcome, in the issues or on Discord.
|---|---|---|
| x64 (64-bit Intel/AMD) | `soundcraft-<ver>-windows-x64.msi` | `soundcraft-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `soundcraft-<ver>-windows-arm64.msi` | `soundcraft-<ver>-windows-arm64-portable.zip` |
For 32-bit Windows, [SoundCraft v0.18.0](https://github.com/storytold/soundcraft/releases/tag/v0.18.0)
was the last release with both an x86 MSI and portable ZIP.
| x86 (32-bit) | `soundcraft-<ver>-windows-x86.msi` | `soundcraft-<ver>-windows-x86-portable.zip` |
Installers and executables are code-signed.
@@ -342,19 +340,15 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
| Flatpak | `soundcraft-<ver>-linux-x86_64.flatpak` | `soundcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `soundcraft-<ver>-linux-x86_64.deb` | `soundcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `soundcraft-<ver>-linux-x86_64.rpm` | `soundcraft-<ver>-linux-aarch64.rpm` | |
| Arch Linux | `soundcraft-<ver>-linux-x86_64.pkg.tar.zst` | `soundcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
| Tarball | `soundcraft-<ver>-linux-x86_64.tar.gz` | `soundcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
`soundcraft-<ver>-linux-riscv64.rpm`, and `soundcraft-<ver>-linux-riscv64.tar.gz`
(glibc 2.39+, e.g. Ubuntu 24.04).
RISC-V (riscv64): `soundcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (glibc 2.39+, e.g. Ubuntu 24.04).
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `soundcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 (ARM64) | `soundcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+4 -6
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (Languages table: Spanish full; previously trivial: French and Spanish partial; previously minor: long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
@@ -87,10 +87,10 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
|---|---|---|---:|
| English | en | full | 100 % |
| Simplified Chinese | zh-Hans | none | 0 % |
| Spanish | es | full — 100 % of fixed UI strings and engine errors; tests pass | 100 % (native-speaker review done) |
| Spanish | es | none (PR #143 open) | 0 % |
| Hindi | hi | none | 0 % |
| Arabic | ar | none | 0 % |
| French | fr | partial — catalog of 1,368 strings, the rest in English | ≈ 62 % |
| French | fr | none (PR #143 open) | 0 % |
| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
| Indonesian | id | none | 0 % |
| Japanese | ja | none | 0 % |
@@ -98,7 +98,7 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
| Korean | ko | none | 0 % |
| Vietnamese | vi | none | 0 % |
Other languages shipped: Spanish complete (fixed UI strings and engine errors, native-speaker review). French is partial (≈ 62 %). Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
Other languages shipped: 0 complete. Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
## Upcoming
@@ -189,8 +189,6 @@ mutated and truncated movies. Field reports from the first public week are track
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | trivial | Languages table: Spanish catalog complete with native-speaker review. Estimates unchanged |
| 2026-11-24 | trivial | Languages table: French and Spanish catalogs, partial (≈ 62 %), PR #143. Estimates unchanged |
| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged |
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
+1 -10
View File
@@ -22,12 +22,9 @@ fn is_control_method(method: &str) -> bool {
| "ui.move"
| "ui.click"
| "ui.drag"
| "ui.scroll"
| "ui.zoom"
| "ui.key"
| "ui.text"
| "ui.screenshot"
| "audio.health"
| "app.quit"
)
}
@@ -68,14 +65,8 @@ mod tests {
assert_eq!(m, "engine.execute");
let (m, _) = app_request("track.new", json!({}));
assert_eq!(m, "engine.execute");
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "audio.health", "app.quit"] {
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
assert_eq!(app_request(method, json!({})).0, method);
}
for (method, params) in [
("ui.scroll", json!({"x": 120, "y": 80, "dx": 5, "dy": -15, "unit": "line"})),
("ui.zoom", json!({"x": 120, "y": 80, "factor": 1.5, "steps": 4})),
] {
assert_eq!(app_request(method, params.clone()), (method.to_string(), params));
}
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ fn write_help() -> &'static str {
/// soundcraft-cli: SoundCraft without a window
#[derive(Parser)]
#[command(name = "soundcraft-cli", version = long_version(), propagate_version = true, arg_required_else_help = true)]
#[command(name = "soundcraft-cli", version = long_version(), arg_required_else_help = true)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
+2 -5
View File
@@ -40,12 +40,9 @@ pub(crate) fn parity(args: &ParityArgs, out: &mut dyn Write) -> Result<(), CliEr
for m in p["per_menu"].as_array().cloned().unwrap_or_default() {
md.push_str(&format!("| {} | {} | {} |\n", m["menu"].as_str().unwrap_or(""), m["implemented"], m["total"]));
}
md.push_str(&format!("\n{}\n", soundcraft_engine::catalog::headless_summary_line(&p)));
md.push_str("A leaf the engine implements is `headless: yes`: `soundcraft-cli` and the MCP server load that registry. The rest carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n");
md.push_str("\n## Not yet implemented\n\n");
for m in p["headless_missing"].as_array().cloned().unwrap_or_default() {
let reach = m["reach"].as_str().map(|r| format!(", reach: {r} ({})", m["why"].as_str().unwrap_or(""))).unwrap_or_default();
md.push_str(&format!("- {}: headless: {}{reach}\n", m["path"].as_str().unwrap_or(""), m["headless"].as_str().unwrap_or("")));
for m in p["missing"].as_array().cloned().unwrap_or_default() {
md.push_str(&format!("- {}\n", m.as_str().unwrap_or("")));
}
if let Some(path) = &args.write {
std::fs::write(path, &md).map_err(|source| CliError::File { path: path.clone(), source })?;
+1 -2
View File
@@ -73,11 +73,10 @@ fn at_rate(pos: u64, from: u32, to: u32) -> u64 {
fn write_replacing(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
let name = target.file_name().map_or_else(|| "output".into(), |n| n.to_string_lossy().into_owned());
let tmp = target.with_file_name(format!(".{name}.{}.part", std::process::id()));
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
let written = (|| {
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, target)
})();
if written.is_err() {
-1
View File
@@ -73,7 +73,6 @@ pub(crate) fn run_cmds(args: &RunArgs, out: &mut dyn Write, err: &mut dyn Write)
pub(crate) fn script(args: &ScriptArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
let path = &args.file;
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let mut e = load_engine(&args.engine, err)?;
let keep = args.keep_going;
let mut failed = false;
-13
View File
@@ -89,19 +89,6 @@ fn version_flags_print_the_long_version_to_stdout() {
}
}
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
/// return without running it (`mcp` and `app` would otherwise wait on something).
#[test]
fn every_subcommand_prints_the_version() {
let release = format!("{} ({} {})\n", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
for sub in ["info", "convert", "run", "script", "commands", "describe", "app", "mcp", "parity", "plugins"] {
for spelling in ["--version", "-V"] {
let got = invoke(&[sub, spelling]);
assert_eq!((got.code, got.stdout, got.stderr), (0, format!("soundcraft-cli-{sub} {release}"), String::new()), "{sub} {spelling}");
}
}
}
#[test]
fn version_is_not_a_subcommand() {
assert_usage_error(&invoke(&["version"]), "unrecognized subcommand 'version'");
@@ -26,15 +26,6 @@ fn invoke(dir: &Path, args: &[&str]) -> Output {
Command::new(crate::common::soundcraft_cli_binary()).current_dir(dir).env("SOUNDCRAFT_NO_PREFS", "1").args(args).output().unwrap()
}
#[test]
fn script_accepts_a_leading_utf8_bom() {
let dir = Scratch::new();
std::fs::write(dir.0.join("bom.txt"), "\u{feff}track.new {\"name\":\"BOM\",\"count\":1,\"format\":\"stereo\"}\n").unwrap();
let output = invoke(&dir.0, &["script", "bom.txt"]);
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
assert!(String::from_utf8_lossy(&output.stdout).contains("track.new:"));
}
#[test]
fn keep_going_runs_later_commands_and_finishes_but_reports_failure() {
let dir = Scratch::new();
-2
View File
@@ -17,8 +17,6 @@ path = "src/main.rs"
soundcraft-engine = { workspace = true }
craft-audio.workspace = true
soundcraft-ui-egui.workspace = true
# The page command API (storytold/craft-libs#413): window.soundcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2bfc45c49378effb801c6433758fb5aaa5d7808e", version = "0.1.0" }
soundcraft-playback = { workspace = true }
soundcraft-model = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
-79
View File
@@ -1,79 +0,0 @@
//! `window.soundcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
//!
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
//! `screenshot`, as promises with a timeout). This module is SoundCraft's part: a [`Request`] that
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
//! reply. SoundCraft's control request has no abandon state, so a call the page gave up on still runs
//! when the app reaches it, as it does for a desktop client that timed out.
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError, TrySendError, sync_channel};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use serde_json::{Value, json};
use soundcraft_ui_egui::ControlRequest;
use wasm_bindgen_futures::JsFuture;
/// The app id in `window.<app>`.
const APP: &str = "soundcraft";
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
/// How many control requests may wait for the app at once. `craft-web-api` already refuses calls past its own
/// in-flight limit; this bounds the app's queue too, so a flood of calls can't grow it without limit.
const QUEUE: usize = 64;
/// Put `window.soundcraft` on the page and return the queue the app drains each frame (hand it to
/// `SoundApp::with_control`). An existing `window.soundcraft` keeps the functions it already has.
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = sync_channel::<ControlRequest>(QUEUE);
let request: Request = Rc::new(move |method, params| {
let (control, reply) = ControlRequest::new(method, params);
if let Err(refused) = queue.try_send(control) {
let error = match refused {
TrySendError::Full(_) => format!("soundcraft is busy: {QUEUE} requests are already waiting for the app"),
TrySendError::Disconnected(_) => "the app is not running".to_string(),
};
return Box::pin(async move { json!({"ok": false, "error": error}) });
}
ctx.request_repaint();
Box::pin(wait(reply))
});
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
log::warn!("couldn't install window.{APP}: {e:?}");
}
requests
}
/// The app's reply, polled about once a frame.
async fn wait(reply: Receiver<Value>) -> Value {
loop {
match reply.try_recv() {
Ok(reply) => return reply,
Err(TryRecvError::Empty) => {
if !sleep(POLL_MS).await {
return json!({"ok": false, "error": "this page has no timer to wait for the app with"});
}
}
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
}
}
}
async fn sleep(ms: i32) -> bool {
// `false` when this page has no timer to wait with (no window, or the timer is refused): the caller ends the
// call with an error instead of going round again at once.
let timer = std::cell::Cell::new(false);
let promise = js_sys::Promise::new(&mut |resolve, _| {
let set = web_sys::window().is_some_and(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms).is_ok());
timer.set(set);
if !set {
let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED);
}
});
let _ = JsFuture::from(promise).await;
timer.get()
}
+1 -4
View File
@@ -6,8 +6,7 @@
//! from this directory (output in `dist/web`).
//!
//! Differences from the desktop app:
//! - no TCP control channel (browsers can't listen on sockets); `window.soundcraft` (`api`) drives the
//! same control channel from the page instead;
//! - no TCP control channel (browsers can't listen on sockets);
//! - no file system: File > Open Session…, Import > Audio…/MIDI… and files dropped on the page are
//! read as bytes through the browser's file picker; a session is saved as ONE bundle file
//! (`<name>.scraftz`: the `.scraft` and its `Audio Files/`), and every save or export arrives as a
@@ -19,8 +18,6 @@
//! empty session instead of the demo.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(target_arch = "wasm32")]
mod web;
+1 -4
View File
@@ -49,10 +49,9 @@ pub fn start() {
if let Some(rs) = &cc.wgpu_render_state {
log::info!("soundcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
}
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
let app = SoundApp::new(engine, Some(player), Services::default()).with_control(crate::api::install(cc.egui_ctx.clone()));
let app = SoundApp::new(engine, Some(player), Services::default());
Ok(Box::new(WebShell { app, inbox: Rc::default(), samples: Rc::default() }))
}),
)
@@ -225,14 +224,12 @@ impl eframe::App for WebShell {
self.app.logic(ctx);
// A prompt opened during this frame becomes a picker on the next one.
self.take_path_prompt(ctx);
self.app.close_path(ctx);
}
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
/// shell.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
-109
View File
@@ -1,109 +0,0 @@
// Real-browser check of window.soundcraft (the page command API from craft-web-api): serve a built
// copy of the web app, load it in headless Chromium and drive every function the crate installs.
//
// Usage, from a folder where Playwright is installed (`npm i playwright`, then `npx playwright install chromium`):
// node <repo>/apps/soundcraft-web/tests/page-api.mjs <site folder>
// The site folder is a built copy of the web app: `trunk build --release` in apps/soundcraft-web
// (dist/web), or the unpacked `packaging/web/package.sh` zip. Exits non-zero on the first failed check.
//
// Not repeated here: the 30 s request timeout belongs to craft-web-api and is covered by that crate's own
// tests. The limit on calls waiting for the app (64) is exercised below: it needs a craft-web-api that has it
// (craft-libs#733) and the app's own bounded queue.
import { createRequire } from 'node:module'
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import assert from 'node:assert/strict'
const dir = process.argv[2]
if (!dir) { console.error('usage: node page-api.mjs <site folder>'); process.exit(2) }
const require = createRequire(path.join(process.cwd(), 'noop.js'))
const { chromium } = (() => { try { return require('playwright') } catch { return require('@playwright/test') } })()
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png' }
const server = http.createServer(async (req, res) => {
const route = decodeURIComponent(req.url.split('?')[0])
const file = path.join(dir, route === '/' ? 'index.html' : route)
try {
const body = await readFile(file)
res.writeHead(200, { 'content-type': types[path.extname(file)] || 'application/octet-stream' })
res.end(body)
} catch { res.writeHead(404); res.end() }
})
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
const origin = `http://127.0.0.1:${server.address().port}`
const browser = await chromium.launch({ headless: true, args: ['--disable-gpu'] })
try {
const page = await (await browser.newContext({ viewport: { width: 1280, height: 900 } })).newPage()
const errors = []
page.on('pageerror', (e) => errors.push(e.message))
// ?webgl forces the WebGL2 backend: headless Chromium has no WebGPU adapter.
await page.goto(`${origin}/?webgl`)
await page.locator('canvas').first().waitFor({ timeout: 180_000 })
await page.waitForFunction(() => window.soundcraft && typeof window.soundcraft.request === 'function', null, { timeout: 180_000 })
const names = await page.evaluate(() => Object.keys(window.soundcraft).sort())
for (const f of ['request', 'execute', 'commands', 'docInspect', 'uiInspect', 'screenshot']) {
assert(names.includes(f), `window.soundcraft.${f} is installed (found: ${names.join(' ')})`)
}
// A call that rejects is reported, not thrown, so each check can look at the error.
const call = (fn, ...args) => page.evaluate(async ([fn, args]) => {
try { return { ok: true, value: await window.soundcraft[fn](...args) } }
catch (e) { return { ok: false, error: String((e && e.message) || e), isError: e instanceof Error } }
}, [fn, args])
const commands = await call('commands')
assert(commands.ok && Array.isArray(commands.value) && commands.value.length > 0, `commands() lists the commands: ${JSON.stringify(commands).slice(0, 200)}`)
assert(commands.value.some((c) => c.id === 'track.new'), 'commands() includes track.new')
const doc = await call('docInspect')
assert(doc.ok && typeof doc.value === 'object', `docInspect() resolves with an object: ${JSON.stringify(doc).slice(0, 200)}`)
const ui = await call('uiInspect')
assert(ui.ok && typeof ui.value === 'object', `uiInspect() resolves with an object: ${JSON.stringify(ui).slice(0, 200)}`)
// execute changes the session, and docInspect shows it.
const docBefore = await call('docInspect')
assert(docBefore.ok, `docInspect() resolves before execute: ${JSON.stringify(docBefore).slice(0, 200)}`)
const ran = await call('execute', 'track.new', {})
assert(ran.ok, `execute('track.new') resolves: ${JSON.stringify(ran).slice(0, 300)}`)
const docAfter = await call('docInspect')
assert(docAfter.ok, `docInspect() resolves after execute: ${JSON.stringify(docAfter).slice(0, 200)}`)
assert.notEqual(JSON.stringify(docBefore.value), JSON.stringify(docAfter.value), 'docInspect() changes after execute(track.new)')
// Failures reject with an Error that names what went wrong.
const unknownCommand = await call('execute', 'no.such.command', {})
assert(!unknownCommand.ok && unknownCommand.isError && unknownCommand.error.includes('no.such.command'), `execute of an unknown command rejects with an Error naming it: ${JSON.stringify(unknownCommand)}`)
const unknownMethod = await call('request', 'no.such.method', {})
assert(!unknownMethod.ok && unknownMethod.isError && unknownMethod.error.includes('no.such.method'), `an unknown method rejects with an Error naming it: ${JSON.stringify(unknownMethod)}`)
const shot = await call('screenshot')
assert(shot.ok, `screenshot() resolves: ${JSON.stringify(shot).slice(0, 200)}`)
const data = shot.value && shot.value.data
assert(typeof data === 'string' && data.length > 1000, 'screenshot() carries base64 data')
assert.equal(Buffer.from(data, 'base64').subarray(1, 4).toString(), 'PNG', 'the screenshot is a PNG')
// Several calls at once all settle.
const settled = await page.evaluate(() => Promise.all([1, 2, 3, 4, 5].map(() => window.soundcraft.uiInspect())).then((r) => r.length))
assert.equal(settled, 5, 'five concurrent calls all settle')
// Overload: far more calls than may wait at once. The ones over the limit are refused at once as busy, the
// ones within it are answered, and the page can call again afterwards (the slots came back).
const burst = await page.evaluate(() => Promise.all(
Array.from({ length: 300 }, () => window.soundcraft.uiInspect().then(() => 'ok', (e) => String((e && e.message) || e))),
))
const refused = burst.filter((r) => r !== 'ok')
console.log(`burst of ${burst.length}: ${burst.length - refused.length} answered, ${refused.length} refused (${refused[0]})`)
assert(refused.length > 0, 'calls beyond the limit are refused')
assert(refused.every((r) => /busy/i.test(r)), `every refusal says busy: ${refused.find((r) => !/busy/i.test(r))}`)
assert(burst.includes('ok'), 'the calls within the limit are answered')
assert.equal(burst.length, 300, 'every call settled, none was left waiting')
const afterBurst = await call('uiInspect')
assert(afterBurst.ok, `a call after the burst is accepted again: ${JSON.stringify(afterBurst).slice(0, 200)}`)
assert.deepEqual(errors, [], 'no uncaught page errors')
console.log('PASS window.soundcraft: all six functions, the failure paths and concurrent calls work against the real app')
} finally {
await browser.close()
server.close()
}
+1 -4
View File
@@ -67,10 +67,7 @@ fn main() {
}
if let Err(e) = res.compile() {
if std::env::var_os("SOUNDCRAFT_REQUIRE_WINRES").is_some() {
// The workspace denies `clippy::panic`, build scripts included: stop the build with
// the reason on stderr.
eprintln!("embedding Windows resources failed: {e}");
std::process::exit(1);
panic!("embedding Windows resources failed: {e}");
}
println!("cargo:warning=soundcraft.exe built without icon/version resources: {e}");
}
+2 -8
View File
@@ -183,16 +183,10 @@ mod config_tests {
app.ui = load_ui(&path).unwrap().unwrap();
assert_eq!(app.ui.theme, soundcraft_ui_egui::theme::ThemeMode::Light);
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), edit);
assert_eq!(
app.ui.mix_docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
egui::Rect::from_min_size(egui::pos2(140.0, 150.0), egui::vec2(280.0, 420.0))
);
assert_eq!(app.ui.mix_docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [140.0, 150.0, 280.0, 420.0]);
app.ui.window = MainWindow::Edit;
app.run("ui.dock", serde_json::json!({"operation":"open","panel":"tracks"})).unwrap();
assert_eq!(
app.ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
egui::Rect::from_min_size(egui::pos2(80.0, 90.0), egui::vec2(260.0, 400.0))
);
assert_eq!(app.ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [80.0, 90.0, 260.0, 400.0]);
let mut invalid_mix = app.ui.clone();
invalid_mix.mix_docking = soundcraft_ui_egui::docking::edit_default();
let invalid_bytes = serde_json::to_vec(&invalid_mix).unwrap();
+3 -9
View File
@@ -22,8 +22,8 @@
//! callback must never do. Code that runs on the audio thread logs anyway (the cpal error callback,
//! the synth's full event queue, a hosted plugin's failed `process`, a CLAP plugin calling the
//! host's `log` from its audio thread, the panic hook). So the cpal callbacks mark their thread
//! (`soundcraft_playback::mark_audio_thread`; the mix engine renders every strip on the marked
//! thread itself), and a record from a marked thread is not written
//! (`soundcraft_playback::mark_audio_thread`; the mix engine carries the mark into the worker
//! threads that render strips for it), and a record from a marked thread is not written
//! there: the first one is kept in a fixed buffer (`try_lock`, no allocation, never waits) and the
//! rest are only counted (an atomic). Another thread writes them out: the UI thread every frame
//! ([`AppLogger::report_audio_thread`]) and any other thread before its own next record.
@@ -166,13 +166,7 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
let message = message.strip_suffix('\n').unwrap_or(message);
// Control characters are written escaped: a message quoting a session file (a plugin id, a
// path) must not start a line of its own in the log or steer the terminal.
let mut escaped = String::with_capacity(message.len());
for c in message.chars() {
if c.is_control() { escaped.extend(c.escape_default()) } else { escaped.push(c) }
}
format!("{ts} {level:<5} [{thread}] {target}: {escaped}\n")
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
}
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
+2 -9
View File
@@ -158,15 +158,8 @@ fn a_line_carries_time_level_thread_target_and_message() {
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "soundcraft_mix", "eq_7band: the plugin did not accept its stored state"),
"2026-10-08T07:59:17.728Z WARN [main] soundcraft_mix: eq_7band: the plugin did not accept its stored state\n"
);
// A message with breaks of its own stays one record; the record still ends in exactly one newline.
assert!(
format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\\nb\n"),
"a break inside the message is escaped, the final one dropped"
);
assert!(
format_line("t", log::Level::Error, "w", "x", "plugin \u{1b}[2J\r\n2026 INFO forged")
.ends_with("x: plugin \\u{1b}[2J\\r\\n2026 INFO forged\n")
);
// A multi-line message keeps its lines; the record still ends in exactly one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
}
#[test]
+8 -38
View File
@@ -71,6 +71,8 @@ impl eframe::App for App {
}
if self.0.quit_requested {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else if ctx.input(|i| i.viewport().close_requested()) && dialogs::ask_to_save(&mut self.0, "app.quit", &serde_json::json!({})) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
soundcraft_ui_egui::fit_window_to_screen(ctx);
let (inner, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().maximized.unwrap_or(false)));
@@ -94,17 +96,13 @@ impl eframe::App for App {
soundcraft_ui_egui::os_title(app_name, Some(document.0))
};
set_title(ctx, title);
// Last: the runtime's close path, which asks about unsaved changes before the window closes.
self.0.close_path(ctx);
}
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
/// shell.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.0.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
soundcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.guarded(|app| app.ui(ui));
}
fn on_exit(&mut self) {
@@ -215,23 +213,14 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Report a refused launch profile on standard error, and in a dialog on a Windows or X11/Wayland
/// desktop session: a Nightly build started from a file manager has no console to read. macOS keeps
/// the console line, because a modal before its event loop never appears.
/// Report a refused launch profile on standard error, and in a dialog on a desktop session: a
/// Nightly build started from a file manager has no console to read.
fn report_launch_profile_error(error: &str) {
eprintln!("SoundCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("SoundCraft launch profile: {error}");
return;
@@ -342,15 +331,11 @@ fn main() -> eframe::Result {
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
#[cfg(target_os = "windows")]
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
#[cfg(all(unix, not(target_os = "macos")))]
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; SOUNDCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
let forced_x11 = env.use_xwayland(std::env::var_os("DISPLAY").as_ref());
#[cfg(not(all(unix, not(target_os = "macos"))))]
let forced_x11 = false;
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
if env.use_xwayland(std::env::var_os("DISPLAY").as_ref()) {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
@@ -384,7 +369,6 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
soundcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11)?;
let player =
if no_audio { None } else { Some(soundcraft_playback::Player::with_config(Arc::new(engine.session().clone()), &prefs.audio)) };
let mut app = SoundApp::new(engine, player, services());
@@ -465,17 +449,3 @@ mod tests {
assert_eq!(titles("Song * — SoundCraft"), 1);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+1 -79
View File
@@ -149,12 +149,6 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
@@ -168,56 +162,11 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
@@ -303,8 +252,6 @@ fn validate_for(
Ok(confirmed)
}
const PROFILE_FOLDERS: [&str; 3] = ["Autosave", "Presets", "logs"];
#[cfg(test)]
mod tests {
use super::*;
@@ -481,31 +428,6 @@ mod tests {
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
+4
View File
@@ -2,4 +2,8 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+16 -15
View File
@@ -153,9 +153,6 @@ impl RunLoop {
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
#[test]
fn timers_and_descriptors_follow_registration() {
@@ -171,21 +168,25 @@ mod tests {
assert_eq!(due, vec![a, b], "a late frame fires each timer once");
assert!(rl.remove_timer(a) && !rl.remove_timer(a));
assert_eq!(rl.due(t0 + Duration::from_secs(2)), vec![b]);
// A connected stream has defined read and write readiness on both Linux and BSD.
let (stream, mut peer) = UnixStream::pair().unwrap();
let fd = stream.as_raw_fd();
assert!(rl.add_fd(fd, CLAP_POSIX_FD_READ));
assert!(!rl.add_fd(fd, CLAP_POSIX_FD_READ), "registered once");
let mut fds = [0; 2];
// SAFETY: `fds` holds the two descriptors `pipe` writes.
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
assert!(rl.add_fd(fds[0], CLAP_POSIX_FD_READ));
assert!(!rl.add_fd(fds[0], CLAP_POSIX_FD_READ), "registered once");
assert!(!rl.add_fd(-1, CLAP_POSIX_FD_READ));
assert!(rl.ready().is_empty(), "nothing to read");
peer.write_all(b"x").unwrap();
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_READ)]);
// The unread byte is still there, so reporting read as well would be a stale interest.
assert!(rl.modify_fd(fd, CLAP_POSIX_FD_WRITE));
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_WRITE)]);
assert!(rl.remove_fd(fd) && !rl.has_fd(fd));
assert!(rl.ready().is_empty(), "no callbacks for an unregistered descriptor");
// SAFETY: a valid one-byte buffer written to our own pipe.
assert_eq!(unsafe { libc::write(fds[1], b"x".as_ptr().cast(), 1) }, 1);
assert_eq!(rl.ready(), vec![(fds[0], CLAP_POSIX_FD_READ)]);
assert!(rl.modify_fd(fds[0], CLAP_POSIX_FD_WRITE));
assert!(rl.ready().is_empty(), "a read end never becomes writable");
assert!(rl.remove_fd(fds[0]) && !rl.has_fd(fds[0]));
rl.clear();
assert!(!rl.has_timer(b));
// SAFETY: closing the pipe we opened.
unsafe {
libc::close(fds[0]);
libc::close(fds[1]);
}
}
}
-2
View File
@@ -478,8 +478,6 @@ pub fn create_unique_folder(parent: &Path, prefix: &str) -> std::io::Result<Path
for _ in 0..16 {
let random = |_| std::collections::hash_map::RandomState::new().build_hasher().finish();
let dir = parent.join(format!("{prefix}-{:016x}{:016x}", random(0), random(1)));
// Only Unix sets a mode on the builder, so elsewhere it is never mutated.
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
+1 -149
View File
@@ -96,92 +96,6 @@ pub fn is_placeholder(path: &str) -> bool {
PLACEHOLDERS.contains(&path)
}
/// RFC-0052 hand marks for catalog leaves the engine registry doesn't implement:
/// `(path, headless, reach, why)`. A path ending in ` > ` marks every leaf under it; the longest
/// matching path wins.
///
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
/// command, isn't one yet). `yes` is never written here: a leaf is `yes` only when the engine registry
/// that `soundcraft-cli` and the MCP server load implements it. UI-layer ids (`parity_with`'s
/// `extra`) don't count. An unmarked missing leaf is `unknown`. [`headless_errors`] rejects marks
/// that match nothing or only hide a `yes`.
pub const HEADLESS: &[(&str, &str, &str, &str)] = &[
("File > Open > Project...", "no", "os", "online project service"),
("File > Open > Sketch...", "no", "engine-gap", "sketch files could be opened by a command"),
("File > Dashboard...", "no", "window", "the start dialog"),
("File > Start Collaboration...", "no", "os", "online collaboration service"),
("File > Import > ", "no", "engine-gap", "the import could be a command"),
("File > Export > ", "no", "engine-gap", "the export could be a command"),
("File > Sign In", "no", "os", "online account service"),
("Edit > Automation > ", "no", "engine-gap", "automation copies could be commands"),
("View > ", "no", "window", "shows or hides part of a desktop window"),
("Track > Change Track Width > Show / Hide...", "no", "window", "a desktop dialog"),
("Track > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
("Clip > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
("AudioSuite > ", "no", "engine-gap", "offline processing over the crates/dsp plug-ins could be commands"),
("Options > Activate HEAT", "no", "engine-gap", "the processor could be an engine option"),
("Setup > Machine Track Arming Profiles...", "no", "os", "external machine control hardware"),
("Window > ", "no", "window", "opens or arranges a desktop window"),
("Window > Collaboration > ", "no", "os", "online collaboration service"),
("Window > Splice", "no", "os", "online sample service"),
("Window > SoundFlow", "no", "os", "third-party automation service"),
];
/// Whether a `HEADLESS` mark path covers a catalog leaf.
fn mark_covers(mark: &str, leaf: &str) -> bool {
mark == leaf || (mark.ends_with(" > ") && leaf.starts_with(mark))
}
/// A leaf's RFC-0052 `headless:` value, `reach:` and reason: `yes` when the engine implements it,
/// else the longest `marks` path that covers it, else `unknown`.
pub fn headless_of<'a>(leaf: &str, in_engine: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) {
if in_engine {
return ("yes", None, "");
}
marks.iter().filter(|m| mark_covers(m.0, leaf)).max_by_key(|m| m.0.len()).map_or(("unknown", None, ""), |m| (m.1, Some(m.2), m.3))
}
/// Problems with `marks` against `leaves` (`(path, in_engine)`): bad values, a mark that covers no
/// leaf, and a mark whose leaves the engine all implements (it would only hide a `yes`).
pub fn headless_errors(marks: &[(&str, &str, &str, &str)], leaves: &[(&str, bool)]) -> Vec<String> {
let mut errs = Vec::new();
for (i, (path, value, reach, _)) in marks.iter().enumerate() {
if !matches!(*value, "no" | "partial") {
errs.push(format!("headless mark `{path}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
}
if !matches!(*reach, "window" | "os" | "engine-gap") {
errs.push(format!("headless mark `{path}`: reach `{reach}` is not window, os or engine-gap"));
}
if marks[..i].iter().any(|m| m.0 == *path) {
errs.push(format!("headless mark `{path}` is written twice"));
}
let covered: Vec<bool> = leaves.iter().filter(|l| mark_covers(path, l.0)).map(|l| l.1).collect();
if covered.is_empty() {
errs.push(format!("headless mark `{path}` matches no catalog leaf"));
} else if covered.iter().all(|live| *live) {
errs.push(format!("headless mark `{path}` is stale: the engine implements every leaf it covers"));
}
}
errs
}
/// The RFC-0052 summary line for a [`parity_with`] report.
pub fn headless_summary_line(p: &Value) -> String {
let h = &p["headless"];
let n = |v: &Value| v.as_u64().unwrap_or(0);
format!(
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**",
n(&h["yes"]),
n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]),
n(&h["no"]["window"]),
n(&h["no"]["os"]),
n(&h["no"]["engine-gap"]),
n(&h["partial"]),
n(&h["unknown"]),
)
}
pub fn catalog() -> Vec<&'static str> {
MENUS.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
}
@@ -208,27 +122,17 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
let mut done = 0usize;
let mut missing = Vec::new();
let mut per_menu: std::collections::BTreeMap<String, (usize, usize)> = Default::default();
let mut headless: Vec<(&str, Option<&str>)> = Vec::new();
let mut headless_missing = Vec::new();
for e in &cat {
let top = e.split(" > ").next().unwrap_or("").to_string();
let slot = per_menu.entry(top).or_default();
slot.1 += 1;
let in_engine = implemented_by(e, &[]).is_some();
let (value, reach, why) = headless_of(e, in_engine, HEADLESS);
headless.push((value, reach));
if value != "yes" {
headless_missing.push(json!({"path": e, "headless": value, "reach": reach, "why": why}));
}
if in_engine || (!extra.is_empty() && implemented_by(e, extra).is_some()) {
if implemented_by(e, extra).is_some() {
done += 1;
slot.0 += 1;
} else {
missing.push(*e);
}
}
let count = |v: &str| headless.iter().filter(|h| h.0 == v).count();
let no = |r: &str| headless.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count();
let pct = if cat.is_empty() { 0.0 } else { done as f64 * 100.0 / cat.len() as f64 };
json!({
"total": cat.len(),
@@ -236,13 +140,6 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
"percent": (pct * 10.0).round() / 10.0,
"per_menu": per_menu.iter().map(|(k, (d, t))| json!({"menu": k, "implemented": d, "total": t})).collect::<Vec<_>>(),
"missing": missing,
"headless": {
"yes": count("yes"),
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
"partial": count("partial"),
"unknown": count("unknown"),
},
"headless_missing": headless_missing,
})
}
@@ -262,51 +159,6 @@ mod tests {
}
}
#[test]
fn headless_marks_are_current() {
let leaves: Vec<(&str, bool)> = catalog().into_iter().map(|e| (e, implemented_by(e, &[]).is_some())).collect();
let errs = headless_errors(HEADLESS, &leaves);
assert!(errs.is_empty(), "{errs:?}");
}
#[test]
fn headless_yes_is_the_engine_only() {
let p = parity_json();
let h = &p["headless"];
assert_eq!(h["yes"], p["implemented"], "engine-only parity: every implemented leaf is yes");
// AudioSuite has no engine command: every leaf is marked, none reads as reachable.
let audiosuite: Vec<&Value> = p["headless_missing"]
.as_array()
.into_iter()
.flatten()
.filter(|m| m["path"].as_str().is_some_and(|x| x.starts_with("AudioSuite > ")))
.collect();
assert!(!audiosuite.is_empty());
assert!(audiosuite.iter().all(|m| m["headless"] == "no" && m["reach"] == "engine-gap"));
// A UI-layer alias makes a leaf implemented for the desktop report, not headless.
let ui = [("Window > Mix", "window.mix")];
let with_ui = parity_with(&ui);
assert!(with_ui["implemented"].as_u64() > p["implemented"].as_u64());
assert_eq!(with_ui["headless"], p["headless"]);
assert!(headless_summary_line(&p).contains(&format!("{} yes", h["yes"])));
}
#[test]
fn headless_marks_pick_the_longest_path_and_refuse_bad_ones() {
let marks = [("W > ", "no", "window", "a"), ("W > C > ", "no", "os", "b"), ("X", "partial", "engine-gap", "c")];
assert_eq!(headless_of("W > C > M", false, &marks), ("no", Some("os"), "b"));
assert_eq!(headless_of("W > Mix", false, &marks), ("no", Some("window"), "a"));
assert_eq!(headless_of("W > Mix", true, &marks).0, "yes");
assert_eq!(headless_of("Y", false, &marks).0, "unknown");
assert_eq!(headless_of("WX", false, &marks).0, "unknown", "a prefix mark needs the separator");
let leaves = [("W > Mix", false), ("X", true)];
let bad = [("W > ", "yes", "window", ""), ("W > ", "no", "desk", ""), ("X", "no", "os", ""), ("Z", "no", "os", "")];
let errs = headless_errors(&bad, &leaves);
for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`X` is stale", "`Z` matches no catalog leaf"] {
assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}");
}
}
#[test]
fn parity_floor() {
let p = parity_json();
+1 -2
View File
@@ -168,8 +168,7 @@ pub fn import(e: &mut Engine, path: &str, first: Option<TrackId>, at: Samples) -
.unwrap_or(2);
let kind = if audio_lane { soundcraft_model::TrackKind::Audio } else { soundcraft_model::TrackKind::Midi };
let fmt = if channels == 1 { soundcraft_model::ChannelFormat::Mono } else { soundcraft_model::ChannelFormat::Stereo };
let t = s.add_track(kind, fmt, Some("Clip Group"));
crate::no_input::assign_first_input(s, t)
s.add_track(kind, fmt, Some("Clip Group"))
}
};
let mut prepared = Vec::new();
-1
View File
@@ -66,7 +66,6 @@ pub use file::bounce_job;
pub(crate) use edit::remember_selection;
pub use strip_silence::strip_silence_scan;
pub use tab::tab_stop_ahead;
pub type Run = fn(&mut Engine, &Value) -> Result<Value>;
/// `Err(reason)` = disabled.
+7 -69
View File
@@ -21,23 +21,14 @@ pub fn specs() -> Vec<CommandSpec> {
)]
}
/// How many times longer than its input a process's output can be.
fn growth(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> f64 {
match name {
"time_stretch" => ratio,
"pitch_shift" => 2f64.powf(f64::from(semitones) / 12.0),
"varispeed" => f64::from(to) / sr,
"speed_ramp" if selection == SpeedRampSelection::Extend => 1.5,
_ => 1.0,
}
}
/// The most frames a process can take in: these processes cut their output at MAX_OFFLINE_SAMPLES frames.
fn frame_limit(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> usize {
let longest = |grows: f64| (soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / grows) as usize;
match name {
"time_stretch" | "pitch_shift" | "varispeed" | "speed_ramp" => {
(soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / growth(name, ratio, semitones, sr, to, selection)) as usize
}
"time_stretch" => longest(ratio),
"pitch_shift" => longest(2f64.powf(f64::from(semitones) / 12.0)),
"varispeed" => longest(f64::from(to) / sr),
"speed_ramp" => longest(if selection == SpeedRampSelection::Extend { 1.5 } else { 1.0 }),
_ => usize::MAX,
}
}
@@ -89,33 +80,14 @@ fn process(e: &mut Engine, p: &Value) -> Result<Value> {
let selection = if get("selection", 0.0) >= 0.5 { SpeedRampSelection::Extend } else { SpeedRampSelection::FitTo };
let fades = get("fades", 1.0) >= 0.5;
let most = frame_limit(&name, ratio, semitones, sr.as_f64(), to, selection);
// Each clip once: a clip listed again would otherwise process the result of its first pass
// (an expanding process compounding its length every time).
let mut seen = std::collections::HashSet::new();
let ids: Vec<_> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
// Refuse before processing anything. Every result is kept as a new source for the life of
// the command (and undo holds it), so cap the total output across clips, not just each one.
// (pitch_shift resamples its stretched result back to the input length)
let grows = if name == "pitch_shift" { 1.0 } else { growth(&name, ratio, semitones, sr.as_f64(), to, selection).max(1.0) };
let mut budget = soundcraft_mix::MAX_RENDER_SAMPLES;
for id in &ids {
let Some((track, clip)) = e.session().find_clip(*id) else { continue };
if !clip.is_audio() {
continue;
}
let channels = e.session().track(track).map_or(1, |t| t.channels()).max(1);
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
let frames = (clip.length.max(0) as f64 * grows).ceil() as usize;
budget = budget
.checked_sub(frames.saturating_mul(channels))
.ok_or_else(|| bad("audiosuite.process", "too much audio to process in one command"))?;
}
let mut done = 0;
for id in ids {
let Some((track, clip)) = e.session().find_clip(id).map(|(t, c)| (t, c.clone())) else { continue };
if !clip.is_audio() {
continue;
}
let channels = e.session().track(track).map_or(1, |t| t.channels());
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
let mut audio = soundcraft_mix::render_clips(e.session(), track, clip.range());
// Render without the clip's own fades: re-render a copy without fades so they stay editable.
let mut tmp = e.session().clone();
@@ -390,40 +362,6 @@ mod tests {
assert_eq!(e.session().tracks[0].clips().len(), 1, "one clip, not one per duplicate listing");
}
#[test]
fn a_clip_listed_twice_is_processed_once() {
let (mut e, id) = gained_clip();
let out =
e.execute("audiosuite.process", &json!({"process": "time_stretch", "params": {"ratio": 4.0}, "clips": [id.0, id.0, id.0]})).unwrap();
assert_eq!(out["processed"], 1);
let c = e.session().tracks[0].clips()[0].clone();
assert!(c.length <= 64 * 4 + 64, "stretched once, not compounded: {}", c.length);
assert_eq!(e.session().sources.len(), 2, "one new source, not one per listing");
}
#[test]
fn process_refuses_a_total_budget_across_clips() {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Tone"));
let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.5; 64]] };
let src = crate::io::add_source(&mut s, "tone", buf, None, FileFormat::Wav);
// Three clips each within the per-clip limit whose results together exceed the budget.
let len = (soundcraft_mix::MAX_RENDER_SAMPLES / 3 + 1) as i64;
let ids: Vec<u64> = (0..3)
.map(|k| {
let id = s.new_clip_id();
crate::edit::place_clip(&mut s, t, Clip::audio(id, "tone", src, 0, k * len, len));
id.0
})
.collect();
let mut e = crate::Engine::new(s);
let before = serde_json::to_value(e.session()).unwrap();
let out = e.execute("audiosuite.process", &json!({"process": "reverse", "clips": ids}));
let ok = matches!(out, Err(crate::EngineError::BadParams(_, ref m)) if m.contains("too much audio"));
assert!(ok, "three clips over budget, but got: {out:?}");
assert_eq!(serde_json::to_value(e.session()).unwrap(), before, "refused before processing anything");
}
#[test]
fn generate_refuses_a_total_budget_across_tracks() {
let mut e = Engine::new(Session::default());
+2 -6
View File
@@ -162,11 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
let t = match track {
Some(t) if s.track(t).is_some_and(|x| x.kind == soundcraft_model::TrackKind::Audio) => t,
Some(_) => return Err(bad("clip.place_source", "audio files go on audio tracks")),
None => {
let t =
s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name));
crate::no_input::assign_first_input(s, t)
}
None => s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name)),
};
let (sh, len) = (s.edit.edit_mode == soundcraft_model::EditMode::Shuffle, frames.max(1));
let at = if sh { crate::edit::shuffle_slot(s, t, at, &[]) } else { at };
@@ -305,7 +301,7 @@ const MAX_LOOPS: i64 = 1000;
fn loop_clips(e: &mut Engine, p: &Value) -> Result<Value> {
let ids = clip_ids_param(e, p);
let count = i64_or(p, "count", 4).clamp(1, MAX_LOOPS);
let count = i64_or(p, "count", 4).clamp(1, 512);
let total = position_param(e, "clip.loop", p, "length")?;
let fill = p.get("fill").and_then(Value::as_bool).unwrap_or(false);
let s = e.session_mut();
-7
View File
@@ -469,13 +469,6 @@ mod tests {
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "length": 100_100})).unwrap()["loops"], 1000);
}
#[test]
fn loop_count_accepts_up_to_the_documented_thousand() {
let (mut e, t, ids) = engine_with(&[(0, 100, 0)]);
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "count": 600})).unwrap()["loops"], 599);
assert_eq!(e.session().track(t).unwrap().clips().len(), 600);
}
#[test]
fn regroup_reuses_group() {
let (mut e, _, ids) = engine_with(&[(0, 100, 0), (500, 100, 0), (900, 100, 0)]);
+7 -42
View File
@@ -9,7 +9,7 @@ use super::more_util::toggle_flag;
use crate::edit as ops;
use crate::{Clipboard, Engine, Result, cmd};
use serde_json::{Value, json};
use soundcraft_model::{Clip, ClipId, EditMode, Fade, FadeShape, Session, TrackId};
use soundcraft_model::{ClipId, EditMode, Fade, FadeShape, Session, TrackId};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -741,9 +741,10 @@ fn trim_to_file(e: &mut Engine, p: &Value) -> Result<Value> {
if let Some((frames, lo, hi)) = trim_limits(s, id)
&& let Some(c) = s.find_clip_mut(id)
{
let (file_start, file_end) = file_span(c, frames);
c.trim_start_to(file_start.max(lo));
c.trim_end_to(file_end.min(hi));
let off = c.source_offset();
let new_start = c.start - off;
c.trim_start_to(new_start.max(lo));
c.trim_end_to((new_start + frames).min(hi));
n += 1;
}
}
@@ -759,24 +760,15 @@ fn trim_to_fill(e: &mut Engine, p: &Value) -> Result<Value> {
if let Some((frames, lo, hi)) = trim_limits(s, id)
&& let Some(c) = s.find_clip_mut(id)
{
let (file_start, file_end) = file_span(c, frames);
let file_start = c.start - c.source_offset();
c.trim_start_to(r.start.max(file_start).max(lo));
c.trim_end_to(r.end.min(file_end).min(hi));
c.trim_end_to(r.end.min(file_start + frames).min(hi));
n += 1;
}
}
Ok(json!({"trimmed": n}))
}
/// Where a clip's whole source file lies on the timeline. The mixer plays `offset + rel / stretch`,
/// so the file starts `offset * stretch` before the clip and spans `frames * stretch` samples.
fn file_span(c: &Clip, frames: Samples) -> (Samples, Samples) {
let stretch = if c.stretch.is_finite() && c.stretch > 0.0 { c.stretch } else { 1.0 };
let scale = |n: Samples| if (stretch - 1.0).abs() >= 1e-9 { (n as f64 * stretch).round() as Samples } else { n };
let start = c.start.saturating_sub(scale(c.source_offset()));
(start, start.saturating_add(scale(frames)))
}
/// How far a trim may extend an audio clip: its source length in frames, and the earliest
/// start and latest end before it would run over the clip before or after it on the playlist
/// (an extension never overwrites, like the trim tool). An overlap the clip already has with
@@ -1262,33 +1254,6 @@ mod tests {
assert_eq!(bounds(&e, t), vec![(0, 10_000, 0), (10_000, 40_000, 10_000), (40_000, 45_000, 0)]);
}
/// A lone stretched clip (start 20,000, length 10,000, source offset 5,000) over the 60,000-frame source.
fn stretched_trim_session(stretch: f64) -> (Engine, TrackId, Vec<ClipId>) {
let (mut e, t, ids) = trim_session(&[(20_000, 10_000, 5_000)]);
if let Some(c) = e.session_mut().find_clip_mut(ids[0]) {
c.stretch = stretch;
}
(e, t, ids)
}
#[test]
fn trim_to_file_boundaries_covers_the_whole_stretched_file() {
let (mut e, t, ids) = stretched_trim_session(2.0);
e.execute("edit.trim_to_file_boundaries", &json!({"clips": [ids[0].0]})).unwrap();
let (start, end, offset) = bounds(&e, t)[0];
assert_eq!(offset, 0, "the clip starts at the file start");
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "it plays every file frame: {start}..{end}");
}
#[test]
fn trim_to_fill_selection_stops_at_the_stretched_file() {
let (mut e, t, ids) = stretched_trim_session(2.0);
e.execute("edit.trim_to_fill_selection", &json!({"clips": [ids[0].0], "start": 0, "end": 500_000})).unwrap();
let (start, end, offset) = bounds(&e, t)[0];
assert_eq!(offset, 0);
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "a wider selection stops at the file: {start}..{end}");
}
#[test]
fn trim_to_fill_selection_stops_at_the_neighbours() {
let (mut e, t, ids) = trim_session(&[(0, 10_000, 0), (20_000, 10_000, 20_000), (40_000, 5_000, 0)]);
+4 -34
View File
@@ -313,16 +313,10 @@ fn add_marker(e: &mut Engine, p: &Value) -> Result<Value> {
let at = position_param(e, "markers.add", p, "at")?;
let st = position_param(e, "markers.add", p, "start")?;
let en = position_param(e, "markers.add", p, "end")?;
let kind = match p.get("kind") {
None | Some(Value::Null) => MarkerKind::Marker,
Some(v) => match v.as_str() {
Some("marker") => MarkerKind::Marker,
Some("selection") => MarkerKind::Selection,
Some("none") => MarkerKind::None,
Some(other) => return Err(bad("markers.add", format!("unknown kind `{other}`"))),
// A present non-string is neither a documented kind nor an omitted one.
None => return Err(bad("markers.add", "kind must be a string")),
},
let kind = match str_param(p, "kind") {
Some("selection") => MarkerKind::Selection,
Some("none") => MarkerKind::None,
_ => MarkerKind::Marker,
};
let (a, b) = match (at, st, en) {
(Some(a), _, _) => (a, a),
@@ -586,30 +580,6 @@ mod tests {
}
}
/// `markers.add` rejects an unknown or non-string `kind` instead of silently adding a plain
/// marker; an absent or null one still means a plain marker.
#[test]
fn markers_add_rejects_an_unknown_kind() {
let mut e = crate::Engine::default();
let err = e.execute("markers.add", &json!({"name": "x", "kind": "garbage"})).unwrap_err();
assert!(err.to_string().contains("kind"), "unexpected error: {err}");
assert!(e.session().markers.is_empty());
for bad in [json!(123), json!(true), json!(["marker"]), json!({"kind": "marker"}), json!(1.5)] {
let err = e.execute("markers.add", &json!({"name": "x", "kind": bad})).unwrap_err();
assert!(err.to_string().contains("kind"), "{bad}: unexpected error: {err}");
assert!(e.session().markers.is_empty(), "{bad}: a marker was added");
}
let plain = e.execute("markers.add", &json!({"name": "Plain", "kind": null, "at": 500})).unwrap();
assert_eq!(e.session().markers.len(), 1, "null is still an omitted kind");
let verse = e.execute("markers.add", &json!({"name": "Verse", "kind": "marker", "at": 1000})).unwrap();
let pre = e.execute("markers.add", &json!({"name": "Pre", "kind": "none", "at": 2000})).unwrap();
let kind_of =
|e: &crate::Engine, r: &serde_json::Value| e.session().markers.iter().find(|m| Some(m.id.0) == r["id"].as_u64()).map(|m| m.kind);
assert_eq!(kind_of(&e, &plain), Some(soundcraft_model::MarkerKind::Marker));
assert_eq!(kind_of(&e, &verse), Some(soundcraft_model::MarkerKind::Marker));
assert_eq!(kind_of(&e, &pre), Some(soundcraft_model::MarkerKind::None));
}
/// Constant replaces the tempo over [start, end) only; the tempo at the old end tick carries on after it.
#[test]
fn tempo_constant_is_bounded_by_its_range() {
-17
View File
@@ -52,23 +52,6 @@ fn import_audio_places_audio_offered_by_a_worker() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn import_audio_refuses_a_non_audio_target() {
let dir = std::env::temp_dir().join(format!("sc-import-non-audio-target-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let wav = tone_wav(&dir, "tone.wav");
let mut e = Engine::default();
e.execute("track.new", &json!({"kind": "instrument", "name": "Keys"})).unwrap();
let err = e.execute("file.import_audio", &json!({"path": wav, "track": "Keys"})).unwrap_err();
assert!(err.to_string().contains("audio track"), "{err}");
assert_eq!(e.session().tracks.len(), 1);
assert!(e.session().sources.is_empty());
assert!(e.session().tracks[0].clips().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn export_session_text_needs_replace_to_overwrite() {
let dir = std::env::temp_dir().join(format!("sc-export-text-replace-{}", std::process::id()));
+2 -19
View File
@@ -11,7 +11,7 @@ use soundcraft_model::{AutoParam, AutomationMode, INSERT_SLOTS, Insert, SEND_SLO
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mix.volume", "Set Volume", [], None, "{tracks?, db: -144..12 | delta_db}", has_selection, volume),
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1 (stereo: required, 0 = left, 1 = right)}", has_selection, pan),
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1}", has_selection, pan),
cmd!("mix.mute", "Mute", [], Some("Shift+M"), "{tracks?, value?: bool}", has_selection, |e, p| toggle(
e,
p,
@@ -280,25 +280,8 @@ fn pan(e: &mut Engine, p: &Value) -> Result<Value> {
let tracks = tracks_required(e, "mix.pan", p)?;
let v = (p.get("pan").and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("mix.pan", "`pan` (number) required"))? as f32)
.clamp(-1.0, 1.0);
// A stereo track has one panner per channel, so it must say which: moving only the left one
// by default folded the left channel into the right. An index the track lacks is an error too.
// `null` means no index, as with `slot`. `i64_or` rounds, so the number has to be whole already.
let idx = match p.get("index") {
None | Some(Value::Null) => None,
Some(i) => {
let whole = i.as_f64().is_some_and(|f| f.fract() == 0.0);
Some(usize::try_from(i64_or(p, "index", -1)).ok().filter(|n| whole && *n <= 1).ok_or_else(|| bad("mix.pan", "`index` must be 0 or 1"))?)
}
};
let idx = i64_or(p, "index", 0).clamp(0, 1) as usize;
let s = e.session_mut();
for tr in tracks.iter().filter_map(|t| s.track(*t)) {
match (idx, tr.mixer.pan.len()) {
(None, 2) => return Err(bad("mix.pan", format!("`{}` is stereo: give `index` 0 (left channel) or 1 (right channel)", tr.name))),
(Some(1), 1) => return Err(bad("mix.pan", format!("`{}` is mono: its only panner is `index` 0", tr.name))),
_ => {}
}
}
let idx = idx.unwrap_or(0);
for t in &tracks {
if let Some(tr) = s.track_mut(*t)
&& let Some(slot) = tr.mixer.pan.get_mut(idx)
-32
View File
@@ -413,38 +413,6 @@ fn clip_gain_to_volume_with_a_large_envelope_stays_fast() {
assert!(lane.points.len() as i64 >= n);
}
/// A stereo track has a panner per channel. `mix.pan` without `index` used to move only the left
/// one, which folded the left channel into the right.
#[test]
fn panning_a_stereo_track_names_the_channel() {
let mut e = Engine::default();
e.execute("track.new", &json!({"name": "Pad", "format": "stereo"})).unwrap();
e.execute("track.new", &json!({"name": "Vox", "format": "mono"})).unwrap();
let pans = |e: &Engine, name: &str| e.session().tracks.iter().find(|t| t.name == name).map(|t| t.mixer.pan.clone());
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3})).is_err());
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 1.0]), "a refused pan leaves the track alone");
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3, "index": 1})).unwrap();
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
// A whole number written as a float counts; a fraction is an error (1.4 used to round to 1).
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.4})).is_err());
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.0})).unwrap();
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 0.9]));
// `null` means no index, as with `slot`, so a stereo track still needs one.
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.0, "index": null})).is_err());
// A mono track has one panner: no index needed, and any other index is an error, not a no-op.
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.25, "index": null})).unwrap();
assert_eq!(pans(&e, "Vox"), Some(vec![0.25]));
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.5})).unwrap();
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
for index in [json!(1), json!(2), json!(-1), json!("1"), json!(0.4)] {
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.0, "index": index})).is_err(), "index {index}");
}
// One stereo track without an index stops the whole command.
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox", "Pad"], "pan": 0.2})).is_err());
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
}
/// Live input toggles stay outside document history in both enabled and disabled states.
#[test]
fn live_input_states_are_transient_and_survive_document_history() {
+1 -2
View File
@@ -476,8 +476,7 @@ fn import_session_data(e: &mut Engine, p: &Value) -> Result<Value> {
let id = "file.import_session_data";
let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad(id, "`path` required"))?.to_string();
let text_v = crate::io::read_session_text(&path)?;
let mut other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
crate::no_input::upgrade_legacy_inputs(&mut other);
let other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
let names: Option<Vec<String>> =
p.get("tracks").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
let picked: Vec<soundcraft_model::Track> = match &names {
-7
View File
@@ -58,13 +58,6 @@ fn tab(e: &mut Engine, p: &Value) -> Result<Value> {
Ok(json!({"selection": r}))
}
/// Whether Tab has a stop after the insertion point or the selection's start. Every stop of a clip lies at or before
/// its end, which is a stop itself.
pub fn tab_stop_ahead(s: &Session) -> bool {
let from = s.edit.selection.start;
s.tracks.iter().filter(|t| s.edit.selected_tracks.contains(&t.id)).flat_map(|t| t.clips()).any(|c| c.start.max(c.end()) > from)
}
/// The nearest stop after `from` (before it when `back`) on the selected tracks.
fn stop(s: &Session, from: Samples, back: bool) -> Option<Samples> {
let nearer = |x: Samples, best: Option<Samples>| {
+16 -12
View File
@@ -98,16 +98,8 @@ pub fn specs() -> Vec<CommandSpec> {
)),
cmd!("track.commit", "Commit...", ["Track"], Some("Alt+Shift+C"), "{tracks?}", has_selection, commit),
cmd!("track.bounce", "Bounce...", ["Track"], Some("Cmd+Alt+Shift+B"), "{tracks?}", has_selection, commit),
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], Some("Shift+A"), "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
cmd!(
"track.mute_sends",
"All",
["Track", "Mute Sends"],
Some("Shift+Q"),
"{tracks?, mute?: bool} (toggles when omitted)",
has_selection,
|e, p| super::track_more::mute_sends_where(e, p, 0, 10)
),
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
cmd!("track.mute_sends", "All", ["Track", "Mute Sends"], None, "{tracks?, mute?: bool}", has_selection, mute_sends),
cmd!(noundo "track.set_record_to_input_only", "Set Record Tracks to Input Only", ["Track"], Some("Alt+K"), "{}", always, |e, _| {
let s = e.runtime_session_mut();
let mut n = 0;
@@ -300,7 +292,6 @@ fn new_track_row(e: &mut Engine, p: &Value) -> Result<Vec<TrackId>> {
let mut ids = Vec::new();
for _ in 0..count {
let id = s.add_track(kind, format, name.as_deref());
crate::no_input::assign_first_input(s, id);
if let Some(t) = s.track_mut(id) {
if let Some(tb) = ticks {
t.ticks_timebase = tb;
@@ -475,7 +466,6 @@ fn split_mono(e: &mut Engine, p: &Value) -> Result<Value> {
_ => format!("{}", ch + 1),
};
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{}.{suffix}", src.name)));
crate::no_input::assign_first_input(s, id);
let mut clips = src.clips().to_vec();
for c in &mut clips {
c.id = s.new_clip_id();
@@ -962,6 +952,20 @@ fn bypass_inserts(e: &mut Engine, p: &Value) -> Result<Value> {
Ok(json!({"bypass": target}))
}
fn mute_sends(e: &mut Engine, p: &Value) -> Result<Value> {
let tracks = tracks_required(e, "track.mute_sends", p)?;
let s = e.session_mut();
let target = p.get("mute").and_then(Value::as_bool).unwrap_or(true);
for t in &tracks {
if let Some(tr) = s.track_mut(*t) {
for snd in tr.mixer.sends.iter_mut().flatten() {
snd.mute = target;
}
}
}
Ok(json!({"mute": target}))
}
fn create_click(e: &mut Engine, _: &Value) -> Result<Value> {
let s = e.session_mut();
let id = s.add_track(TrackKind::Aux, ChannelFormat::Mono, Some("Click"));
+31 -66
View File
@@ -68,56 +68,38 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
load_preset
),
cmd!(
"track.bypass_inserts_ae",
"Inserts A-E",
["Track", "Bypass Inserts"],
Some("Shift+2"),
"{tracks?, bypass?: bool}",
has_selection,
|e, p| bypass_where(e, p, |i, _| i < 5)
),
cmd!(
"track.bypass_inserts_fj",
"Inserts F-J",
["Track", "Bypass Inserts"],
Some("Shift+3"),
"{tracks?, bypass?: bool}",
has_selection,
|e, p| bypass_where(e, p, |i, _| (5..10).contains(&i))
),
cmd!(
"track.bypass_eq",
"EQ",
["Track", "Bypass Inserts"],
Some("Shift+E"),
"{tracks?, bypass?: bool} — EQ plug-ins only",
has_selection,
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Eq))
),
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], Some("Shift+C"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Dynamics))
cmd!("track.bypass_inserts_ae", "Inserts A-E", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |i, _| i < 5)
}),
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], Some("Shift+V"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Reverb))
cmd!("track.bypass_inserts_fj", "Inserts F-J", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |i, _| (5..10).contains(&i))
}),
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], Some("Shift+D"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Delay))
cmd!("track.bypass_eq", "EQ", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool} — EQ plug-ins only", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Eq))
}),
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
e,
p,
|_, c| c == Some(Category::Dynamics)
)),
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
e,
p,
|_, c| c == Some(Category::Reverb)
)),
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
e,
p,
|_, c| c == Some(Category::Delay)
)),
cmd!("track.bypass_modulation", "Modulation", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Modulation))
}),
cmd!(
"track.bypass_modulation",
"Modulation",
["Track", "Bypass Inserts"],
Some("Shift+W"),
"{tracks?, bypass?: bool}",
has_selection,
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Modulation))
),
cmd!(
"track.mute_sends_ae",
"Sends A-E",
["Track", "Mute Sends"],
Some("Shift+4"),
None,
"{tracks?, mute?: bool} (toggles when omitted)",
has_selection,
|e, p| mute_sends_where(e, p, 0, 5)
@@ -126,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"track.mute_sends_fj",
"Sends F-J",
["Track", "Mute Sends"],
Some("Shift+5"),
None,
"{tracks?, mute?: bool} (toggles when omitted)",
has_selection,
|e, p| mute_sends_where(e, p, 5, 10)
@@ -353,7 +335,7 @@ fn bypass_where(e: &mut Engine, p: &Value, pick: fn(usize, Option<Category>) ->
Ok(json!({"bypass": target, "inserts": n}))
}
pub(super) fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
let tracks = tracks_required(e, "track.mute_sends", p)?;
let s = e.session_mut();
let all_muted = tracks.iter().filter_map(|t| s.track(*t)).all(|tr| tr.mixer.sends.iter().skip(from).take(to - from).flatten().all(|x| x.mute));
@@ -520,22 +502,15 @@ fn coalesce_vca(e: &mut Engine, p: &Value) -> Result<Value> {
}
fn designate_target(e: &mut Engine, p: &Value) -> Result<Value> {
let id = "track.designate_target_playlist";
let tracks = tracks_required(e, id, p)?;
let index = match p.get("index") {
None | Some(Value::Null) => None,
Some(value) => {
let index = value.as_u64().ok_or_else(|| bad(id, "`index` must be a nonnegative integer"))?;
Some(usize::try_from(index).map_err(|_| bad(id, "no such playlist"))?)
}
};
let tracks = tracks_required(e, "track.designate_target_playlist", p)?;
let idx = p.get("index").and_then(Value::as_u64);
let s = e.session_mut();
let mut out = Vec::new();
for t in &tracks {
let Some(tr) = s.track(*t) else { continue };
let i = index.unwrap_or(tr.active_playlist);
let i = idx.map_or(tr.active_playlist, |x| usize::try_from(x).unwrap_or(usize::MAX));
if i >= tr.playlists.len() {
return Err(bad(id, "no such playlist"));
return Err(bad("track.designate_target_playlist", "no such playlist"));
}
s.edit.values.insert(format!("playlist.target.{}", t.0), i as f64);
out.push(json!({"track": t, "target": i}));
@@ -599,8 +574,6 @@ mod tests {
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
e.execute("track.mute_sends_ae", &json!({})).unwrap();
assert!(e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
e.execute("track.mute_sends", &json!({})).unwrap();
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
}
#[test]
@@ -753,19 +726,11 @@ mod tests {
e.execute("track.playlist_new", &json!({})).unwrap();
e.execute("track.designate_target_playlist", &json!({})).unwrap();
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
let kick = e.session().track_by_name("Kick").unwrap().id;
for index in [json!(-1), json!("1"), json!(1.5), json!(u64::MAX)] {
assert!(e.execute("track.designate_target_playlist", &json!({"index": index})).is_err(), "{index}");
assert_eq!(target_playlist(e.session(), kick), Some(1), "{index} must leave the target unchanged");
}
e.execute("track.show_target_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 0);
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
e.execute("track.designate_target_playlist", &json!({"index": null})).unwrap();
assert_eq!(target_playlist(e.session(), kick), Some(0));
}
}
+1 -2
View File
@@ -29,8 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
always,
offset
),
cmd!(query "video.list", "Movies", [], None, "{} — lists session movies with media details, clip counts, `file_found`, and any recorded `offline` reason. \
The top-level `online` flag reports the Video Track Online setting.", always, |e, _| {
cmd!(query "video.list", "Movies", [], None, "{} — movies used by Video tracks (path, size, rate, codec, online file, why it is offline)", always, |e, _| {
let s = e.session();
let rows: Vec<Value> = s
.videos
+18 -51
View File
@@ -10,8 +10,7 @@
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - The result must lie inside one of the roots of its kind, compared by whole components
//! (`/work2` isn't inside `/work`), by the case the disk stores (links are resolved first, so a
//! differently cased spelling of a root still lands inside it).
//! (`/work2` isn't inside `/work`), without regard to case on Windows.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
@@ -267,12 +266,24 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
}
}
/// Is `path` (resolved) `root` or inside it, component by component? Both come from
/// `canonicalize`, which gives the name's case as the disk stores it, so equal means the same
/// folder; folding case would equate two folders on a case-sensitive Windows directory.
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
/// Windows, whose file systems ignore it)?
fn inside(path: &Path, root: &Path) -> bool {
let mut path = path.components();
root.components().all(|r| path.next().is_some_and(|p| p == r))
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
}
fn same_component(a: Component, b: Component) -> bool {
if a == b {
return true;
}
if !cfg!(windows) {
return false;
}
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
_ => false,
}
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
@@ -465,7 +476,7 @@ mod tests {
#[cfg(windows)]
#[test]
fn windows_resolves_case_and_refuses_devices() {
fn windows_ignores_case_and_refuses_devices() {
let (base, roots) = folders("case");
let upper = s(base.join("IN/a.scraft"));
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
@@ -477,50 +488,6 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// On a case-sensitive Windows directory `Work` and `work` are two folders: a root on one
/// doesn't grant the other, while a differently cased spelling of a name that is the same
/// folder (the ordinary, case-insensitive directories) is still accepted. Skipped, with a
/// note, where `fsutil` can't switch a directory to case-sensitive (it needs rights and the
/// NTFS volume's support).
#[cfg(windows)]
#[test]
fn windows_case_sensitive_directory_keeps_case_equal_folders_apart() {
let (base, _) = folders("case-sensitive");
let cs = base.join("cs");
std::fs::create_dir_all(&cs).unwrap();
let switched = std::process::Command::new("fsutil")
.args(["file", "setCaseSensitiveInfo"])
.arg(&cs)
.arg("enable")
.output()
.is_ok_and(|o| o.status.success());
if !switched {
eprintln!("skipped: cannot make {} case-sensitive", cs.display());
let _ = std::fs::remove_dir_all(base);
return;
}
for d in ["Work/sub", "work"] {
std::fs::create_dir_all(cs.join(d)).unwrap();
}
std::fs::write(cs.join("Work/a.scraft"), "x").unwrap();
std::fs::write(cs.join("work/secret.scraft"), "x").unwrap();
let roots = AutomationRoots::new(&[&cs.join("Work")], &[&cs.join("Work")]).unwrap().unwrap();
for access in [Access::Read, Access::Write] {
assert_eq!(roots.check(s(cs.join("Work/a.scraft")), access), Ok(()));
assert_eq!(roots.check(s(cs.join("Work/sub/New.scraft")), access), Ok(()));
// The other folder exists, and so does a name no folder has: both are outside.
for outside in ["work/secret.scraft", "work/new.scraft", "WORK/new.scraft"] {
let e = roots.check(s(cs.join(outside)), access).unwrap_err();
assert!(e.contains("outside the"), "{outside}: {e}");
}
}
// A root on the lower-case folder grants that one only.
let lower = AutomationRoots::new(&[&cs.join("work")], &[]).unwrap().unwrap();
assert_eq!(lower.check(s(cs.join("work/secret.scraft")), Access::Read), Ok(()));
assert!(lower.check(s(cs.join("Work/a.scraft")), Access::Read).is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn scopes_nest_and_stay_on_their_thread() {
let (base, roots) = folders("scopes");
+2 -10
View File
@@ -1097,8 +1097,7 @@ fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::colle
}
/// The record-enabled audio tracks, each with the input channels it records (those its input
/// route names, "In 3" → 2, wrapped to the device's `input_channels`; with no input,
/// [`NO_INPUT_CHANNEL`](crate::no_input::NO_INPUT_CHANNEL), which records silence) and a new take file
/// route names, "In 3" → 2, wrapped to the device's `input_channels`) and a new take file
/// `<track>_<NN>.wav` in the `Audio Files` of the session's folder (`unsaved_dir` until it is saved).
pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<(TrackId, Vec<usize>, PathBuf)> {
let dir = e.path.as_deref().and_then(|p| Path::new(p).parent()).unwrap_or(unsaved_dir);
@@ -1114,11 +1113,7 @@ pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<
}
_ => 0,
};
let inputs = if t.mixer.input == soundcraft_model::Route::None {
vec![crate::no_input::NO_INPUT_CHANNEL; t.channels()]
} else {
(0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect()
};
let inputs = (0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect();
let file = |n: usize| dir.join("Audio Files").join(format!("{}_{n:02}.wav", sanitize_name(&t.name)));
let path = (take_no..take_no + 1_000).map(file).find(|p| !p.exists()).unwrap_or_else(|| file(take_no));
(t.id, inputs, path)
@@ -1246,10 +1241,7 @@ pub(crate) fn read_aaf_plan(_: &str, _: &str, _: Option<&str>) -> Result<Value>
Err(EngineError::Io("AAF import needs the desktop app: its media files are read from a local folder".into()))
}
// Every test here plants a link, so the module and its helper are Unix-only. `cfg(test)` stays an
// attribute of its own: clippy allows `unwrap` in tests only under a plain `#[cfg(test)]`.
#[cfg(test)]
#[cfg(unix)]
mod exclusive_tests {
use super::*;
+1 -9
View File
@@ -176,13 +176,6 @@ fn place_import(
let file_rate = info.sample_rate;
let s = e.session_mut();
let session_rate = s.sample_rate.hz();
// An explicit non-audio target cannot play the clip: refuse it before registering
// the source, like `clip.place_source` does.
if let Some(t) = target
&& !s.track(t).is_some_and(|tr| tr.kind == TrackKind::Audio)
{
return Err(EngineError::BadParams("file.import_audio".into(), "audio files go on audio tracks".into()));
}
let src = add_source_audio(s, name, audio, path, FileFormat::of(info));
if let (Some(bwf), Some(sx)) = (info.bwf.as_ref(), s.sources.last_mut()) {
sx.time_reference = stamp_at_rate(bwf.time_reference, file_rate, session_rate);
@@ -192,8 +185,7 @@ fn place_import(
Some(t) => t,
None => {
let stem = Path::new(name).file_stem().and_then(OsStr::to_str).unwrap_or("Audio").to_string();
let t = s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem));
crate::no_input::assign_first_input(s, t)
s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem))
}
};
let cid = s.new_clip_id();
+8 -94
View File
@@ -87,7 +87,7 @@ fn lost_covers(lost: u8, device: u8) -> bool {
}
/// What `track` recorded of `events` over `range`, in ticks from the start of the range. A key
/// already down when the range starts sounds from its start, as long as it is held; one still down at its end ends there, and one
/// already down when the range starts is left out; one still down at its end ends there, and one
/// whose device lost input ends where that happened. Keys are told apart by device, channel and
/// pitch: the same pitch held on two devices gives two notes. A key held while loop recording
/// goes round ([`MidiTakeEvent::WRAP`]) is two notes: to the end of the loop, and from its start;
@@ -108,10 +108,9 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
// The round of the loop being played: it goes up at every `WRAP`.
let mut round = 0u32;
// Keys down: (device, channel, pitch) -> (start tick, velocity, round, the sample the key was
// pressed at, which is before the range only for a key held into it). Whether the loop went
// round between a press and its release is judged by their samples: two positions a few
// samples apart may share a tick, and a press in the last samples of the range starts its
// note a tick earlier so that it plays.
// pressed at). Whether the loop went round between a press and its release is judged by
// their samples: two positions a few samples apart may share a tick, and a press in the
// last samples of the range starts its note a tick earlier so that it plays.
let mut down: HashMap<(u8, u8, u8), (i64, u8, u32, Samples)> = HashMap::new();
let close = |seq: &mut Sequence,
(_, channel, pitch): (u8, u8, u8),
@@ -153,16 +152,7 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
round = round.saturating_add(1);
continue;
}
if e.at < range.start {
// Before the range (the pre-roll, or before the punch-in): a key pressed there and
// still down when the range starts is recorded from the start of the range, "the
// start of the note is quantized to the punch-in point" (Reference Guide p.822).
// An entry there that ends a note pressed in the range is a late callback, as below.
if round > 0 || held_into_range(s, input, devices, e, &mut down, range.start) {
continue;
}
}
if e.at >= range.end {
if e.at < range.start || e.at >= range.end {
continue;
}
let at = tick(e.at);
@@ -185,7 +175,7 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
match e.status & 0xF0 {
0x90 if d2 > 0 => {
// The same key again without a release: the first note ends here.
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at.max(range.start))) {
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at)) {
close(&mut seq, key, open, at, 64, round, e.at);
}
}
@@ -219,45 +209,6 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
seq
}
/// Follow the keys pressed and released before a record range starts, in `down` (as the take
/// builder keeps them: start tick, velocity, round, the sample the key was pressed at, which for
/// these keys alone is before `start`). A key still down when the range starts goes on from its
/// first tick; one released before it, or whose device lost input, leaves nothing. Returns
/// false when `e` is left to the range: a lost-input entry (for the keys pressed in the range),
/// or an entry for a key pressed in the range, stamped early by a late audio callback.
fn held_into_range(
s: &Session,
input: &MidiInput<'_>,
devices: &[String],
e: &MidiTakeEvent,
down: &mut HashMap<(u8, u8, u8), (i64, u8, u32, Samples)>,
start: Samples,
) -> bool {
if e.status == MidiTakeEvent::LOST {
down.retain(|k, open| open.3 >= start || !lost_covers(e.device, k.0));
return false;
}
let channel = e.status & 0x0F;
if midi_filtered(s, e.status) || !input.accepts(devices.get(usize::from(e.device)).map(String::as_str), channel) {
return true;
}
let key = (e.device, channel, e.data1 & 0x7F);
let note = matches!(e.status & 0xF0, 0x80 | 0x90);
if note && down.get(&key).is_some_and(|open| open.3 >= start) {
return false;
}
match e.status & 0xF0 {
0x90 if e.data2 & 0x7F > 0 => {
down.insert(key, (0, e.data2 & 0x7F, 0, e.at));
}
0x80 | 0x90 => {
down.remove(&key);
}
_ => {}
}
true
}
/// Most events of one MIDI record pass that are kept.
pub const MAX_MIDI_TAKE_EVENTS: usize = 1 << 20;
@@ -359,7 +310,7 @@ mod tests {
assert_eq!(e.session().busses.len(), 0, "a MIDI input is not a bus name");
assert!(records_midi(&e));
let events = [
ev(40_000, 0, 0x90, 59, 80), // before the pass, released inside it: from the pass start
ev(40_000, 0, 0x90, 59, 80), // before the pass: left out, and so is its release
ev(48_000, 0, 0x90, 60, 100), // one beat at 120 bpm, 48 kHz: 24 000 samples = 960 ticks
ev(50_000, 0, 0x80, 59, 0),
ev(60_000, 1, 0x99, 36, 127),
@@ -377,7 +328,7 @@ mod tests {
assert_eq!((before, take.clips.len(), take.gaps), (0, 2, 0), "the track whose device was silent gets no clip");
let keys = sequence(&e, all, range);
let notes: Vec<(u8, u8, i64, i64, u8)> = keys.notes.iter().map(|n| (n.channel, n.pitch, n.start, n.length, n.release_velocity)).collect();
assert_eq!(notes, [(0, 59, 0, 80, 0), (0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
assert_eq!(notes, [(0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
assert_eq!(
keys.ctrls.iter().map(|c| (c.tick, c.kind, c.value)).collect::<Vec<_>>(),
[(960, CtrlKind::PitchBend, 4096), (1680, CtrlKind::Cc(64), 127)]
@@ -394,28 +345,6 @@ mod tests {
assert!(add_midi_recording(&mut e, Range::new(5, 5), &events, &devices, false).clips.is_empty());
}
#[test]
fn a_key_held_into_the_punch_in_is_recorded_from_the_punch_in() {
// Reference Guide p.822: played before the punch-in point, released after it.
let s = Session::default();
let range = Range::new(48_000, 144_000);
let events = [
ev(24_000, 0, 0x90, 60, 100), // held into the range
ev(30_000, 0, 0x90, 62, 100), // pressed and released before it: nothing
ev(36_000, 0, 0x80, 62, 0),
ev(40_000, 0, 0x90, 64, 90), // another one released before it
ev(44_000, 0, 0x80, 64, 0),
ev(72_000, 0, 0x80, 60, 30), // the held key, released one quarter into the range
ev(96_000, 0, 0x90, 67, 100),
ev(120_000, 0, 0x80, 67, 0),
];
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events, &[]));
assert_eq!(got, [(0, 60, 0, 960, 100, 30), (0, 67, 1920, 960, 100, 0)]);
// A key still down at the end of the range covers all of it.
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events[..1], &[]));
assert_eq!(got, [(0, 60, 0, 3840, 100, 64)]);
}
#[test]
fn the_same_pitch_on_two_devices_is_two_notes_and_lost_input_ends_only_its_device() {
let mut e = Engine::default();
@@ -621,21 +550,6 @@ mod tests {
let marked = [ev(24_000, 0, 0x90, 60, 100), ev(96_000, u8::MAX, MidiTakeEvent::WRAP, 0, 0), ev(48_000, 0, 0x80, 60, 0)];
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &marked, &[]));
assert_eq!(got.iter().map(|n| (n.2, n.3)).collect::<Vec<_>>(), [(960, 960)]);
// A punch range: a key pressed in it whose release is stamped before its start is one
// short note at the press too, and a key pressed and released before it stays out.
let punch = Range::new(48_000, 144_000);
let events = [
ev(30_000, 0, 0x90, 62, 100),
ev(36_000, 0, 0x80, 62, 0),
ev(49_000, 0, 0x90, 60, 100),
ev(47_000, 0, 0x80, 60, 40),
ev(72_000, 0, 0x90, 64, 100),
ev(47_400, 0, 0xB0, 64, 127), // a controller stamped there is still left out
ev(47_500, u8::MAX, MidiTakeEvent::LOST, 0, 0),
];
let seq = midi_take_sequence(&s, &MidiInput::default(), punch, MidiPass::Linear, &events, &[]);
assert_eq!(notes_of(&seq), [(0, 60, 40, 1, 100, 40), (0, 64, 960, 1, 100, 64)]);
assert!(seq.ctrls.is_empty());
}
#[test]
+1 -3
View File
@@ -562,9 +562,7 @@ mod open_tests {
let at = |f: &str| dir.join(f).to_string_lossy().into_owned();
assert_eq!(got[0], (stored_path("Movies/here.mov", &session).unwrap().to_string_lossy().into_owned(), None));
assert_eq!(got[1], (at("near.mov"), None));
// Joined part by part, as `relink_videos` does: `join("Video Files/filed.mov")` keeps the `/`,
// which differs from the relinked path on Windows.
assert_eq!(got[2], (dir.join("Video Files").join("filed.mov").to_string_lossy().into_owned(), None));
assert_eq!(got[2], (at("Video Files/filed.mov"), None));
assert_eq!(got[3], ("Old/gone.mov".into(), Some("file not found".into())));
assert_eq!(got[4].0, stored[4]);
assert!(got[4].1.as_deref().is_some_and(|why| why.starts_with("not opened:")), "{:?}", got[4]);
+3 -7
View File
@@ -18,7 +18,6 @@ pub mod feature_names;
pub mod file_access;
pub mod inspect;
pub mod io;
pub mod no_input;
pub mod score;
use serde_json::{Value, json};
@@ -221,9 +220,8 @@ impl Default for Engine {
}
impl Engine {
pub fn new(mut session: Session) -> Self {
pub fn new(session: Session) -> Self {
install_panic_hook();
no_input::upgrade_legacy_inputs(&mut session);
let doc = Arc::new(session);
Engine {
saved: Arc::clone(&doc),
@@ -298,10 +296,8 @@ impl Engine {
&mut Arc::make_mut(&mut self.doc).edit.zoom
}
/// Replace the whole document (open / new); clears history. A session saved before "no
/// input" existed is upgraded ([`no_input::upgrade_legacy_inputs`]).
pub fn replace_session(&mut self, mut s: Session) {
no_input::upgrade_legacy_inputs(&mut s);
/// Replace the whole document (open / new); clears history.
pub fn replace_session(&mut self, s: Session) {
self.transport = TransportStatus { position: s.edit.selection.start.max(0), ..TransportStatus::default() };
self.transport_requests.clear();
self.transport_requests.push(TransportRequest::ResetSession);
-122
View File
@@ -1,122 +0,0 @@
//! "no input" on an audio track (`Route::None`): the track records and monitors nothing, as
//! Pro Tools' No Input does. A new audio track gets its first input path explicitly instead.
//!
//! Sessions saved before this rule used `Route::None` for an audio track that recorded and
//! monitored hardware input 1 (the selector showed "In 1"). [`upgrade_legacy_inputs`] turns
//! those into the explicit first input when such a session is opened, so it keeps sounding and
//! recording as before. Sessions held by the engine carry [`NO_INPUT_MARKER`], so a "no input"
//! saved by this build stays "no input" when it is opened again.
use soundcraft_model::{ChannelFormat, Route, Session, TrackKind};
/// Set in `edit.flags` of every session the engine holds: its `Route::None` audio inputs mean
/// "no input". A session without it was saved before that, when they meant hardware input 1.
pub const NO_INPUT_MARKER: &str = "io.none_is_no_input";
/// The input channel an audio track with no input records: no device has it, so the take is
/// digital silence.
pub const NO_INPUT_CHANNEL: usize = usize::MAX;
/// The first hardware input path of a track of `format`: "In 1", "In 1-2", "In 1-6"…
pub fn first_input(format: ChannelFormat) -> Route {
match format.channels() {
0 | 1 => Route::Hardware("In 1".into()),
n => Route::Hardware(format!("In 1-{n}")),
}
}
/// Give the new track `id`, if it is an audio track, its first input path (Pro Tools assigns
/// new tracks an input path), and return `id`.
pub(crate) fn assign_first_input(s: &mut Session, id: soundcraft_model::TrackId) -> soundcraft_model::TrackId {
if let Some(t) = s.track_mut(id)
&& t.kind == TrackKind::Audio
&& t.mixer.input == Route::None
{
t.mixer.input = first_input(t.format);
}
id
}
/// A session saved before [`NO_INPUT_MARKER`]: each audio track whose input is `Route::None`
/// recorded and monitored hardware input 1, so it gets that input explicitly. Then the session
/// is marked, and running this again changes nothing.
pub fn upgrade_legacy_inputs(s: &mut Session) {
if s.edit.flag(NO_INPUT_MARKER) {
return;
}
for t in &mut s.tracks {
if t.kind == TrackKind::Audio && t.mixer.input == Route::None {
t.mixer.input = first_input(t.format);
}
}
s.edit.set_flag(NO_INPUT_MARKER, true);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Engine;
use serde_json::json;
use soundcraft_model::TrackId;
fn new_track(e: &mut Engine, format: &str) -> TrackId {
TrackId(e.execute("track.new", &json!({"format": format})).unwrap()["tracks"][0].as_u64().unwrap())
}
fn input(e: &Engine, t: TrackId) -> Route {
e.session().track(t).unwrap().mixer.input.clone()
}
#[test]
fn a_new_audio_track_gets_its_first_input_path() {
let mut e = Engine::default();
let mono = new_track(&mut e, "mono");
let stereo = new_track(&mut e, "stereo");
assert_eq!(input(&e, mono), Route::Hardware("In 1".into()));
assert_eq!(input(&e, stereo), Route::Hardware("In 1-2".into()));
let aux = TrackId(e.execute("track.new", &json!({"kind": "aux"})).unwrap()["tracks"][0].as_u64().unwrap());
assert_eq!(input(&e, aux), Route::None, "only audio tracks take a hardware input by default");
}
#[test]
fn a_track_with_no_input_records_no_device_channel() {
let dir = std::env::temp_dir().join(format!("soundcraft-no-input-{}", std::process::id()));
let mut e = Engine::default();
let vox = new_track(&mut e, "mono");
let gtr = new_track(&mut e, "stereo");
e.execute("track.input", &json!({"tracks": [vox.0, gtr.0], "input": "none"})).unwrap();
e.execute("mix.record_arm", &json!({"tracks": [vox.0, gtr.0], "value": true})).unwrap();
let plan = crate::io::plan_takes(&e, &dir, 30);
assert_eq!(
plan.iter().map(|(t, inputs, _)| (*t, inputs.clone())).collect::<Vec<_>>(),
vec![(vox, vec![NO_INPUT_CHANNEL]), (gtr, vec![NO_INPUT_CHANNEL; 2])]
);
}
#[test]
fn a_session_saved_before_no_input_existed_keeps_recording_input_1() {
let mut old = Session::default();
let vox = old.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Vox"));
let gtr = old.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Gtr"));
let keys = old.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys"));
let text = old.to_json().unwrap();
assert!(!text.contains(NO_INPUT_MARKER));
let mut e = Engine::default();
e.replace_session(Session::from_json(&text).unwrap());
assert_eq!(input(&e, vox), Route::Hardware("In 1".into()));
assert_eq!(input(&e, gtr), Route::Hardware("In 1-2".into()));
assert_eq!(input(&e, keys), Route::None, "a MIDI input is left alone");
assert!(!e.is_dirty(), "opening an old session does not modify it");
}
#[test]
fn no_input_survives_save_and_reopen() {
let mut e = Engine::default();
let vox = new_track(&mut e, "mono");
e.execute("track.input", &json!({"tracks": [vox.0], "input": "no input"})).unwrap();
let text = e.session().to_json().unwrap();
let mut reopened = Engine::default();
reopened.replace_session(Session::from_json(&text).unwrap());
assert_eq!(input(&reopened, vox), Route::None);
}
}
@@ -18,7 +18,7 @@ fn kick_trim(e: &Engine) -> f32 {
#[test]
fn mix_pan_rejects_a_missing_or_non_numeric_pan_and_keeps_the_pan() {
let mut e = engine_with_kick();
e.execute("mix.pan", &json!({"tracks": ["Kick"], "pan": -1.0, "index": 0})).unwrap();
e.execute("mix.pan", &json!({"tracks": ["Kick"], "pan": -1.0})).unwrap();
assert_eq!(kick_pan(&e)[0], -1.0);
for params in [json!({"tracks": ["Kick"]}), json!({"tracks": ["Kick"], "pan": "left"}), json!({"tracks": ["Kick"], "pan": null})] {
+1 -1
View File
@@ -68,8 +68,8 @@ fn insertion_trims_still_trim_unlocked_clips_beside_both_lock_kinds() {
for clip in &mut session.track_mut(track).unwrap().playlist_mut().unwrap().clips {
clip.start = 0;
}
let before = session.clone();
let mut engine = Engine::new(session);
let before = engine.session().clone();
let result = engine.execute(command, &json!({"tracks": [track.0], "at": 50})).unwrap();
assert_eq!(result["trimmed"], json!(1), "{command}");
let clips = engine.session().track(track).unwrap().clips();
-119
View File
@@ -1,119 +0,0 @@
//! Existing commands/history and saved session PCM for bounded send automation.
use craft_audio::AudioBuffer;
use serde_json::json;
use soundcraft_engine::{Engine, io};
use soundcraft_model::{AutoParam, ChannelFormat, Clip, FileFormat, Route, Session, TrackKind};
use soundcraft_time::Range;
use std::sync::Arc;
fn fixture() -> Engine {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Original"));
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 512]] };
let src = io::add_source(&mut s, "Original synthetic", buffer, None, FileFormat::Wav);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original", src, 0, 0, 512));
s.track_mut(t).unwrap().mixer.output = Route::None;
let mut e = Engine::new(s);
e.execute("mix.new_bus", &json!({"name":"Send","format":"stereo"})).unwrap();
e.execute("mix.send", &json!({"track":"Original","bus":"Send","slot":"A","level_db":0})).unwrap();
e.execute("track.new", &json!({"name":"Return","kind":"aux","format":"stereo"})).unwrap();
let bus = e.session().busses.iter().find(|b| b.name == "Send").unwrap().id;
let aux = e.session().tracks.iter().find(|t| t.kind == TrackKind::Aux).unwrap().id;
e.session_mut().track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
e.mark_clean();
e
}
fn render(e: &Engine) -> Vec<Vec<f32>> {
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 512), 37);
assert_eq!(out.len(), 2);
assert!(out.iter().all(|c| c.len() == 512));
out
}
fn point(e: &mut Engine, param: &str, at: i64, value: f32) {
e.execute("automation.set_point", &json!({"track":"Original","param":param,"at":at,"value":value})).unwrap();
}
#[test]
fn commands_undo_redo_reuse_renderer_and_preserve_render_state() {
let mut e = fixture();
let baseline = render(&e);
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_pan", 173, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let before = render(&e);
point(&mut e, "send_a_mute", 97, 1.0);
let after = render(&e);
assert_ne!(before, after);
assert_ne!(baseline, before);
let arc = e.session_arc();
let serialized = e.session().to_json().unwrap();
let revision = e.revision;
let history = e.undo_history();
let dirty = e.is_dirty();
let mut mix = soundcraft_mix::MixEngine::new(48_000.0, 512);
let mut out = vec![vec![0.0; 512]; 2];
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
mix.render(e.session(), 97, 13, &mut out);
assert!(Arc::ptr_eq(&arc, &e.session_arc()));
assert_eq!(serialized, e.session().to_json().unwrap());
assert_eq!(revision, e.revision);
assert_eq!(history, e.undo_history());
assert_eq!(dirty, e.is_dirty());
assert!(e.undo());
assert_eq!(render(&e), before);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, before);
assert!(e.redo());
assert_eq!(render(&e), after);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
e.execute("mix.automation_mode", &json!({"track":"Original","mode":"off"})).unwrap();
assert_eq!(render(&e), baseline);
}
#[test]
fn lane_commands_survive_folder_and_bundle_save_reopen_with_exact_pcm() {
let mut e = fixture();
e.execute("mix.send_level", &json!({"track":"Original","slot":"A","pan":0.5,"mute":true})).unwrap();
point(&mut e, "send_a_pan", 37, -1.0);
point(&mut e, "send_a_pan", 401, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
e.execute("automation.write_range", &json!({"track":"Original","param":"send_a_mute","start":97,"end":173,"value":1.0})).unwrap();
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let dir = std::env::temp_dir().join(format!("soundcraft-send-automation-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("Original/Send.scraft").to_string_lossy().into_owned();
io::save_session(&mut e, &path).unwrap();
let mut reopened = Engine::default();
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
assert_eq!(render(&reopened), expected);
let tr = reopened.session().tracks.iter().find(|t| t.name == "Original").unwrap();
assert_eq!(tr.lane(&AutoParam::SendPan(0)).unwrap().points.len(), 2);
assert!(!reopened.is_dirty());
assert!(!reopened.can_undo());
let (bundle, _) = io::session_bundle(e.session()).unwrap();
let mut bundled = Engine::default();
io::open_session_bytes(&mut bundled, "Send.scraftz", &bundle).unwrap();
assert_eq!(render(&bundled), expected);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn absent_enabled_field_keeps_legacy_reader_behavior() {
let mut e = fixture();
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let mut json = serde_json::to_value(e.session()).unwrap();
for track in json["tracks"].as_array_mut().unwrap() {
for lane in track["automation"].as_array_mut().unwrap() {
lane.as_object_mut().unwrap().remove("enabled");
}
}
let mut old: Session = serde_json::from_value(json).unwrap();
old.pool = e.session().pool.clone();
let tr = old.tracks.iter().find(|t| t.name == "Original").unwrap();
assert!(tr.automation.iter().all(|l| !l.enabled));
assert_eq!(soundcraft_mix::render_range(&old, Range::new(0, 512), 100), expected);
}
+10 -46
View File
@@ -70,7 +70,6 @@ mod midi;
mod offline;
mod pan;
mod routing;
mod send_automation;
mod strip;
mod threads;
@@ -264,18 +263,12 @@ impl MixEngine {
for s in self.strips.values_mut() {
for p in s.plugins.iter_mut().flatten() {
p.plugin.reset();
if p.failed && !p.retried {
p.failed = false;
p.retried = true;
}
p.failed = false;
}
if let Some(i) = &mut s.instrument {
i.plugin.all_notes_off();
i.plugin.reset();
if i.failed && !i.retried {
i.failed = false;
i.retried = true;
}
i.failed = false;
}
s.held.clear();
s.chase = true;
@@ -363,7 +356,7 @@ impl MixEngine {
}
for b in &s.busses {
let n = b.format.channels().clamp(1, MAX_CHANNELS);
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new(), age: send_automation::SignalAge::Empty });
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new() });
bus.fmt = b.format;
if bus.buf.len() != n {
bus.buf = vec![vec![0.0; mb]; n];
@@ -390,7 +383,7 @@ impl MixEngine {
self.begin_block(s, pos, frames);
let blk = Block { pos, frames, any_solo: any_solo(s) };
let order = std::mem::take(&mut self.order);
// Phase 1: independent strips (audio, instrument, MIDI), in parallel except on the audio thread.
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
let mut work = std::mem::take(&mut self.work);
work.clear();
for &i in &order {
@@ -455,7 +448,6 @@ impl MixEngine {
}
self.ensure_synced(s);
for b in self.busses.values_mut() {
b.age = send_automation::SignalAge::Empty;
for c in b.buf.iter_mut() {
c.iter_mut().take(frames).for_each(|x| *x = 0.0);
}
@@ -510,11 +502,9 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(lmax_t.saturating_sub(st.latency), ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
st.align_pre.set(lmax_t.saturating_sub(st.latency), ch);
st.align_pre.process(&mut st.pre, frames);
st.send_pre_age = st.send_pre_age.delayed(st.align_pre.len);
}
let waits = match &t.mixer.output {
Route::Main => true,
@@ -550,7 +540,6 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
st.out_extra.set(0, ch);
self.route_strip(t, &mut st, pos, frames);
self.strips.insert(t.id, st);
@@ -648,41 +637,22 @@ impl MixEngine {
let law = self.pan_law;
for (i, snd) in t.mixer.sends.iter().enumerate() {
let Some(snd) = snd else { continue };
if strip.muted {
continue;
}
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let age = if snd.pre_fader { strip.send_pre_age } else { strip.send_post_age };
let clock = age.clock(pos);
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
let ordinary = !src_fmt.is_ambisonic() && !dst.fmt.is_ambisonic();
let mute = ordinary.then(|| send_automation::Reader::for_send(t, AutoParam::SendMute, i, clock.at(0))).flatten();
if mute.is_none() && snd.mute {
if snd.mute || strip.muted {
continue;
}
let lvl = send_level(t, i, snd.level_db, pos);
let gain = db_to_gain(lvl);
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
if gain <= 0.0 {
continue;
}
dst.age.include(age);
let pan = (ordinary && src.len() == 1 && dst.fmt == ChannelFormat::Stereo)
.then(|| send_automation::Reader::for_send(t, AutoParam::SendPan, i, clock.at(0)))
.flatten();
if let Some(pan) = pan {
send_automation::apply_mono_stereo(src, frames, &mut dst.buf, gain, law, clock, pan, mute);
continue;
}
// Mono sends use the send's own pan; stereo sends go straight to L/R.
let stereo = if src.len() == 1 { [snd.pan, 0.0] } else { [-1.0, 1.0] };
let surround = snd.surround.as_ref().or(if snd.follow_main_pan { t.mixer.surround.as_ref() } else { None });
let m = build_matrix(src_fmt, src.len(), dst.fmt, dst.buf.len(), &PanSpec { stereo, surround }, law);
if let Some(mute) = mute {
send_automation::apply_gated(src, frames, &mut dst.buf, &m, gain, clock, mute);
} else {
apply_matrix(src, frames, &mut dst.buf, &m, gain);
}
apply_matrix(src, frames, &mut dst.buf, &m, gain);
}
let src: &[Vec<f32>] = match &t.mixer.output {
Route::Main | Route::Bus(_) if strip.out_extra.len > 0 => {
@@ -701,10 +671,7 @@ impl MixEngine {
let (dst, dst_fmt) = match &t.mixer.output {
Route::Main => (&mut self.main, self.main_fmt),
Route::Bus(b) => match self.busses.get_mut(b) {
Some(d) => {
d.age.include(strip.send_post_age.delayed(strip.out_extra.len));
(&mut d.buf, d.fmt)
}
Some(d) => (&mut d.buf, d.fmt),
None => return,
},
_ => return,
@@ -738,6 +705,3 @@ mod click;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod send_age_tests;
+1 -1
View File
@@ -1,7 +1,7 @@
use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains};
/// Per-block routing gains: `m[src][dst]`.
pub(crate) type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
/// How a source is panned: the stereo pan pair (mono uses `[0]`) and the optional surround pan.
pub(crate) struct PanSpec<'a> {
-120
View File
@@ -1,120 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use craft_audio::AudioBuffer;
use soundcraft_dsp::Plugin;
use super::send_automation::SignalAge;
use super::strip::{Block, BusBuf, LiveInput, MAX_LATENCY, PluginSlot, Strip, process_strip};
use super::*;
#[test]
fn known_bus_ages_accumulate_and_mixed_ages_keep_the_legacy_clock() {
let mut bus = SignalAge::Empty;
assert_eq!(bus.input(), SignalAge::Known(0));
bus.include(SignalAge::Known(71));
bus.include(SignalAge::Known(71));
assert_eq!(bus, SignalAge::Known(71));
let aux_pre = bus.delayed(23);
let aux_post = aux_pre.delayed(48);
assert_eq!(aux_pre, SignalAge::Known(94));
assert_eq!(aux_post, SignalAge::Known(142));
assert_eq!(aux_pre.clock(300).at(0), 206);
assert_eq!(aux_post.clock(300).at(0), 158);
let nested = aux_post.delayed(71);
assert_eq!(nested, SignalAge::Known(213));
bus.include(SignalAge::Known(142));
assert_eq!(bus, SignalAge::Mixed);
assert_eq!(bus.delayed(71).clock(300).at(0), 300);
}
#[test]
fn age_overflow_preserves_audio_with_the_legacy_clock_fallback() {
let age = SignalAge::Known(u64::MAX).delayed(1);
assert_eq!(age, SignalAge::Mixed);
assert_eq!(age.clock(-7).at(3), -4);
let mut bus = SignalAge::Known(71);
bus.include(SignalAge::Empty);
assert_eq!(bus, SignalAge::Known(71));
}
#[test]
fn processed_insert_age_is_uncapped_while_pdc_stays_capped_and_overflow_falls_back() {
struct DeclaredDelay {
inner: Box<dyn Plugin>,
latency: usize,
}
impl Plugin for DeclaredDelay {
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
self.inner.info()
}
fn prepare(&mut self, rate: f32, block: usize, channels: usize) {
self.inner.prepare(rate, block, channels);
}
fn reset(&mut self) {
self.inner.reset();
}
fn set_param(&mut self, id: &str, value: f32) -> bool {
self.inner.set_param(id, value)
}
fn param(&self, id: &str) -> Option<f32> {
self.inner.param(id)
}
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
self.inner.process(io, frames);
}
fn latency(&self) -> usize {
self.latency
}
}
fn slot(latency: usize) -> PluginSlot {
let mut inner = soundcraft_dsp::create("gain").unwrap();
inner.prepare(48_000.0, 16, 1);
PluginSlot::test_instance("gain".into(), 1, Box::new(DeclaredDelay { inner, latency }))
}
let mut source = Session::default();
source.edit.delay_compensation = false;
let audio = source.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let source_id = soundcraft_model::SourceId(900);
source.pool.insert(source_id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 16]] })));
let clip = source.new_clip_id();
let track = source.track_mut(audio).unwrap();
track.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared-age reference", source_id, 0, 0, 16));
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
track.mixer.inserts[1] = Some(soundcraft_model::Insert::new("gain"));
let mut pre = soundcraft_model::SendSlot::new(Route::None);
pre.pre_fader = true;
track.mixer.sends[0] = Some(pre);
let mut strip = Strip::new();
strip.buf = vec![vec![0.0; 16]];
strip.scratch = vec![0.0; 16];
strip.plugins = vec![Some(slot(MAX_LATENCY + 5)), Some(slot(MAX_LATENCY + 9))];
let busses = HashMap::new();
let live = LiveInput { input: &[], midi: &[], ports: None, midi_lost: 0, monitor_only: false, recording: false };
let blk = Block { pos: 0, frames: 16, any_solo: false };
process_strip(&source, source.track(audio).unwrap(), &mut strip, &busses, &live, blk);
let declared_sum = 2 * MAX_LATENCY as u64 + 14;
assert_eq!(strip.latency, MAX_LATENCY, "the existing PDC cap remains unchanged");
assert_eq!(strip.send_pre_age, SignalAge::Known(declared_sum));
assert_eq!(strip.send_post_age, SignalAge::Known(declared_sum));
assert_eq!(strip.align.len, 0);
assert_eq!(strip.align_pre.len, 0);
assert_eq!(strip.pre, vec![vec![0.25; 16]]);
assert_eq!(strip.buf, strip.pre, "declared age metadata never changes the processed PCM");
let bus = source.add_bus("Overflowing known input", ChannelFormat::Mono);
let aux = source.add_track(TrackKind::Aux, ChannelFormat::Mono, None);
let track = source.track_mut(aux).unwrap();
track.mixer.input = Route::Bus(bus);
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
let busses = HashMap::from([(bus, BusBuf { fmt: ChannelFormat::Mono, buf: vec![vec![0.25; 16]], age: SignalAge::Known(u64::MAX) })]);
let mut aux_strip = Strip::new();
aux_strip.buf = vec![vec![0.0; 16]];
aux_strip.plugins = vec![Some(slot(1))];
process_strip(&source, source.track(aux).unwrap(), &mut aux_strip, &busses, &live, blk);
assert_eq!(aux_strip.latency, 1);
assert_eq!(aux_strip.send_pre_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age.clock(300).at(0), 300);
assert_eq!(aux_strip.buf, vec![vec![0.25; 16]], "overflow preserves the output instead of silencing it");
}
-267
View File
@@ -1,267 +0,0 @@
//! Local send playback: sample-exact mono-to-stereo pan and stepped ordinary-bus mute.
//! No document mutation, allocation, locks or persistent cursor survive a callback/seek.
use super::MAX_CHANNELS;
use super::pan::Matrix;
use soundcraft_dsp::pan::{PanLaw, gains};
use soundcraft_model::{AutoParam, AutomationPoint, Track};
use soundcraft_time::Samples;
/// Source-sample age metadata only; it never changes routing or audio delay compensation.
/// A mixed-age sum has no single source clock, so new send readers retain their legacy clock.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub(crate) enum SignalAge {
#[default]
Empty,
Known(u64),
Mixed,
}
impl SignalAge {
pub(crate) fn input(self) -> Self {
match self {
Self::Empty => Self::Known(0),
other => other,
}
}
pub(crate) fn delayed(self, frames: usize) -> Self {
match self {
Self::Known(age) => u64::try_from(frames).ok().and_then(|frames| age.checked_add(frames)).map_or(Self::Mixed, Self::Known),
other => other,
}
}
pub(crate) fn include(&mut self, contribution: Self) {
*self = match (*self, contribution) {
(Self::Empty, age) | (age, Self::Empty) => age,
(Self::Known(a), Self::Known(b)) if a == b => Self::Known(a),
_ => Self::Mixed,
};
}
pub(crate) fn clock(self, position: Samples) -> Clock {
let age = match self {
Self::Known(age) => age,
Self::Empty | Self::Mixed => 0,
};
Clock::new(position, age)
}
}
/// A forward cursor rebuilt at each callback's absolute position. Like the existing mixer
/// readers, this deliberately ignores lane.enabled; global suspension/migration is separate.
/// Nonfinite or decreasing-time lanes fall back to the static control for the whole callback.
/// Finite values clamp to the control range; duplicate times deterministically use the last knot.
pub(super) struct Reader<'a> {
points: &'a [AutomationPoint],
next: usize,
mute: bool,
}
impl<'a> Reader<'a> {
pub(super) fn for_send(t: &'a Track, param: fn(u8) -> AutoParam, slot: usize, pos: Samples) -> Option<Self> {
if !t.mixer.automation_mode.reads() {
return None;
}
let param = param(u8::try_from(slot).ok()?);
let lane = t.lane(&param)?;
let points = &lane.points;
if points.is_empty() || points.iter().any(|p| !p.value.is_finite()) || points.windows(2).any(|p| p[0].at > p[1].at) {
return None;
}
Some(Self { points, next: points.partition_point(|p| p.at <= pos), mute: matches!(param, AutoParam::SendMute(_)) })
}
pub(super) fn value(&mut self, pos: Samples) -> f32 {
while self.points.get(self.next).is_some_and(|p| p.at <= pos) {
self.next = self.next.saturating_add(1);
}
let Some(a) = self.points.get(self.next.saturating_sub(1)) else { return 0.0 };
let lo = if self.mute { 0.0 } else { -1.0 };
let av = a.value.clamp(lo, 1.0);
if self.next == 0 || self.mute {
return av;
}
let Some(b) = self.points.get(self.next) else { return av };
// Valid timestamps may span i64::MIN..MAX. Widen before subtraction, and interpolate
// bounded values in f64 so neither timestamp nor value arithmetic can overflow.
let width = i128::from(b.at) - i128::from(a.at);
if width <= 0 {
return av;
}
let fraction = ((i128::from(pos) - i128::from(a.at)) as f64 / width as f64).clamp(0.0, 1.0);
(f64::from(av) + (f64::from(b.value.clamp(lo, 1.0)) - f64::from(av)) * fraction) as f32
}
}
/// Timeline position represented by a delayed source tap. Widen the entire expression before
/// clamping, so advancing a frame near MIN/MAX does not lose an earlier delay subtraction.
#[derive(Clone, Copy)]
pub(super) struct Clock {
position: Samples,
age: u64,
}
impl Clock {
pub(super) fn new(position: Samples, age: u64) -> Self {
Self { position, age }
}
pub(super) fn at(self, frame: usize) -> Samples {
let frame = i128::try_from(frame).unwrap_or(i128::MAX);
let at = i128::from(self.position).saturating_add(frame).saturating_sub(i128::from(self.age));
at.clamp(i128::from(Samples::MIN), i128::from(Samples::MAX)) as Samples
}
}
impl From<Samples> for Clock {
fn from(position: Samples) -> Self {
Self::new(position, 0)
}
}
#[cfg(test)]
fn frame_position(pos: Samples, frame: usize) -> Samples {
Clock::from(pos).at(frame)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn apply_mono_stereo(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
gain: f32,
law: PanLaw,
pos: impl Into<Clock>,
mut pan: Reader<'_>,
mut mute: Option<Reader<'_>>,
) {
let clock = pos.into();
let Some(src) = src.first() else { return };
for (i, sample) in src.iter().enumerate().take(frames) {
let at = clock.at(i);
if mute.as_mut().is_some_and(|m| m.value(at) >= 0.5) {
continue;
}
let (left, right) = gains(pan.value(at), law);
for (channel, factor) in [(0, left), (1, right)] {
if let Some(out) = dst.get_mut(channel).and_then(|c| c.get_mut(i)) {
*out += sample * gain * factor;
}
}
}
}
/// Keep the existing static routing matrix (including mono folds and surround positions),
/// applying only the exact mute gate. Sparse taps are prepared on the stack once per block.
pub(super) fn apply_gated(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
matrix: &Matrix,
gain: f32,
pos: impl Into<Clock>,
mut mute: Reader<'_>,
) {
let clock = pos.into();
let mut taps = [[(0usize, 0.0f32); MAX_CHANNELS]; MAX_CHANNELS];
let mut counts = [0usize; MAX_CHANNELS];
for (d, (taps, count)) in taps.iter_mut().zip(counts.iter_mut()).enumerate().take(dst.len()) {
for (s, row) in matrix.iter().enumerate().take(src.len().min(MAX_CHANNELS)) {
let g = row.get(d).copied().unwrap_or(0.0);
if g != 0.0
&& let Some(tap) = taps.get_mut(*count)
{
*tap = (s, g);
*count += 1;
}
}
}
for i in 0..frames {
if mute.value(clock.at(i)) >= 0.5 {
continue;
}
for (d, channel) in dst.iter_mut().enumerate().take(MAX_CHANNELS) {
let Some(out) = channel.get_mut(i) else { continue };
let mut acc = 0.0;
for &(s, g) in taps.get(d).and_then(|t| counts.get(d).and_then(|n| t.get(..*n))).unwrap_or(&[]) {
acc += src.get(s).and_then(|c| c.get(i)).copied().unwrap_or(0.0) * gain * g;
}
*out += acc;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use soundcraft_model::{AutomationLane, ChannelFormat, Session, TrackKind};
fn track(points: &[(i64, f32)], mute: bool) -> Track {
let mut s = Session::default();
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let t = s.track_mut(id).unwrap();
let mut lane = AutomationLane::new(if mute { AutoParam::SendMute(0) } else { AutoParam::SendPan(0) });
lane.points = points.iter().map(|&(at, value)| AutomationPoint { at, value }).collect();
t.automation.push(lane);
t.clone()
}
#[test]
fn wide_interpolation_does_not_overflow() {
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MIN).unwrap();
assert_eq!(r.value(i64::MIN), -1.0);
assert!(r.value(0).abs() < 1e-7);
assert_eq!(r.value(i64::MAX), 1.0);
assert_eq!(frame_position(i64::MAX - 1, 3), i64::MAX);
}
#[test]
fn endpoints_duplicates_and_finite_extremes_are_deterministic() {
let t = track(&[(3, -f32::MAX), (3, 0.25), (7, f32::MAX)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, 0).unwrap();
assert_eq!(r.value(0), -1.0);
assert_eq!(r.value(3), 0.25);
assert_eq!(r.value(5), 0.625);
assert_eq!(r.value(9), 1.0);
let t = track(&[(i64::MIN, -f32::MAX), (i64::MAX, f32::MAX)], true);
let mut r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MIN).unwrap();
assert_eq!(r.value(0), 0.0);
assert_eq!(r.value(i64::MAX), 1.0);
}
#[test]
fn short_buffers_and_saturating_positions_do_not_panic() {
let t = track(&[(i64::MIN, 0.0), (i64::MAX, 1.0)], true);
let r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MAX - 1).unwrap();
let mut dst = vec![vec![0.0; 1]];
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
apply_gated(&[vec![0.25; 2]], 4, &mut dst, &matrix, 1.0, i64::MAX - 1, r);
assert_eq!(dst, vec![vec![0.25]]);
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MAX - 1).unwrap();
apply_mono_stereo(&[vec![0.25; 2]], 4, &mut [], 1.0, PanLaw::Minus3, i64::MAX - 1, r, None);
}
#[test]
fn source_clock_clamps_after_the_composite_delay_expression() {
assert_eq!(Clock::new(i64::MIN + 5, 10).at(8), i64::MIN + 3);
assert_eq!(Clock::new(i64::MAX, 10).at(3), i64::MAX - 7);
assert_eq!(Clock::new(i64::MAX, 10).at(20), i64::MAX);
assert_eq!(Clock::new(-5, 10).at(3), -12);
assert_eq!(Clock::new(i64::MAX, u64::MAX).at(0), i64::MIN);
assert_eq!(Clock::new(i64::MIN, u64::MAX).at(0), i64::MIN);
}
#[test]
fn delayed_reader_seed_and_gate_advancement_use_the_same_clock() {
let t = track(&[(0, 0.0), (30, 1.0), (40, 0.0)], true);
let clock = Clock::new(45, 25);
let reader = Reader::for_send(&t, AutoParam::SendMute, 0, clock.at(0)).unwrap();
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
let mut destination = vec![vec![0.0; 25]];
apply_gated(&[vec![0.25; 25]], 25, &mut destination, &matrix, 1.0, clock, reader);
assert_eq!(destination[0], (0..25).map(|frame| if (10..20).contains(&frame) { 0.0 } else { 0.25 }).collect::<Vec<_>>());
}
}
+9 -42
View File
@@ -5,7 +5,6 @@ use super::live_midi::{LiveMidi, LiveNotes, MidiPorts, midi_thru};
use super::midi::{chase_controllers, schedule_notes};
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
use super::routing::solo_muted;
use super::send_automation::SignalAge;
use super::{
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
db_to_gain,
@@ -17,8 +16,6 @@ use std::sync::Arc;
pub(crate) struct BusBuf {
pub(crate) fmt: ChannelFormat,
pub(crate) buf: Vec<Vec<f32>>,
/// Age shared by the routed contributions in this block, or Mixed when they differ.
pub(crate) age: SignalAge,
}
pub(crate) struct PluginSlot {
@@ -32,17 +29,6 @@ pub(crate) struct PluginSlot {
/// so the audio thread reuses its allocation.
lanes: Vec<usize>,
pub(crate) failed: bool,
/// A failed plugin is retried once on the next reset; a second failure keeps it out for the
/// rest of the session, so a plugin that always fails stops oscillating the track's latency
/// (and the compensation reallocations that go with it) on every stop or seek (#919).
pub(crate) retried: bool,
}
#[cfg(test)]
impl PluginSlot {
pub(crate) fn test_instance(id: String, ch: usize, plugin: Box<dyn Plugin>) -> Self {
Self { id, ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }
}
}
pub(crate) struct Strip {
@@ -69,9 +55,6 @@ pub(crate) struct Strip {
clipbuf: Vec<Vec<f32>>,
/// Total latency of the active inserts (samples).
pub(crate) latency: usize,
/// Sample ages of the selected send taps after their actual applied alignment.
pub(crate) send_pre_age: SignalAge,
pub(crate) send_post_age: SignalAge,
/// Delay compensation: align this strip with the slowest one (post- and pre-fader paths),
/// plus extra delay for direct-to-main outputs so they line up with aux returns.
pub(crate) align: DelayLine,
@@ -170,8 +153,6 @@ impl Strip {
clip_fx: HashMap::new(),
clipbuf: Vec::new(),
latency: 0,
send_pre_age: SignalAge::Known(0),
send_post_age: SignalAge::Known(0),
align: DelayLine::default(),
align_pre: DelayLine::default(),
out_extra: DelayLine::default(),
@@ -222,7 +203,7 @@ impl SlotCtx<'_> {
let state = if third { ins.state_bytes() } else { None };
create_instance_for(&ins.plugin, state.as_deref(), self.sr, self.mb, ch, self.offline).map(|n| n.plugin)
}?;
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false })
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false })
}
}
@@ -253,11 +234,9 @@ fn zero_buf(buf: &mut [Vec<f32>], frames: usize) {
}
}
/// Input monitoring: the track hears its hardware input instead of its clips. With no input
/// (`Route::None`) it hears nothing.
/// Input monitoring: the track hears its hardware input instead of its clips.
fn monitor_input(t: &Track, strip: &mut Strip, live: &LiveInput<'_>, frames: usize) {
let first = match &t.mixer.input {
Route::None => return,
Route::Hardware(h) => {
h.trim_start_matches("In ").split(['-', ' ']).next().and_then(|n| n.parse::<usize>().ok()).map_or(0, |n| n.saturating_sub(1))
}
@@ -304,11 +283,10 @@ fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) {
}
/// An aux or folder reads the bus its input is routed from.
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) -> SignalAge {
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) {
if let Route::Bus(b) = &t.mixer.input
&& let Some(src) = busses.get(b)
{
let input_age = src.age.input();
let (ns, nd) = (src.buf.len(), strip.buf.len());
let dst_fmt = strip_format(t, nd);
let m = if src.fmt == dst_fmt && ns == nd {
@@ -324,9 +302,7 @@ fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, f
build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3)
};
apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0);
return input_age;
}
SignalAge::Known(0)
}
/// Render the track's instrument into the strip.
@@ -411,12 +387,10 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
}
/// Run the active inserts in order; records their latency and the first gain reduction.
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport, input_age: SignalAge) {
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) {
let Block { pos, frames, .. } = blk;
let mut gr = 0.0f32;
let inst_latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
let mut latency = inst_latency;
let mut send_age = input_age.delayed(inst_latency);
let mut latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
for (i, ins) in t.mixer.inserts.iter().enumerate() {
let (Some(ins), Some(Some(slot))) = (ins, strip.plugins.get_mut(i)) else { continue };
if !ins.active || ins.bypass || slot.failed {
@@ -429,17 +403,13 @@ fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport,
strip.failures.record(i);
continue;
}
let declared_latency = slot.plugin.latency();
latency = latency.saturating_add(declared_latency);
send_age = send_age.delayed(declared_latency);
latency = latency.saturating_add(slot.plugin.latency());
if gr == 0.0 {
gr = slot.plugin.gain_reduction_db();
}
}
strip.gr = gr;
strip.latency = latency.min(MAX_LATENCY);
strip.send_pre_age = send_age;
strip.send_post_age = send_age;
}
/// Fader gain (volume, trim and VCA automation), read at every sample of the block.
@@ -490,7 +460,6 @@ fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) {
pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, live: &LiveInput<'_>, blk: Block) {
let Block { pos, frames, any_solo } = blk;
zero_buf(&mut strip.buf, frames);
let mut input_age = SignalAge::Known(0);
let transport = transport_at(s, pos, !live.monitor_only, live.recording);
match t.kind {
TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => {
@@ -501,9 +470,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
// doing so, to release its notes).
TrackKind::Instrument | TrackKind::Midi if live.monitor_only && !midi_thru(t) && !strip.live.touched() => {}
TrackKind::Audio => render_audio_clips(s, t, strip, blk),
TrackKind::Aux | TrackKind::Folder => {
input_age = read_aux_bus(t, strip, busses, frames);
}
TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames),
TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, live, blk, &transport),
_ => {}
}
@@ -513,7 +480,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
c.iter_mut().take(frames).for_each(|x| *x *= trim);
}
}
run_inserts(t, strip, blk, &transport, input_age);
run_inserts(t, strip, blk, &transport);
let soloed_out = solo_muted(s, t, any_solo);
strip.muted = t.mixer.mute || soloed_out;
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
@@ -657,7 +624,7 @@ mod apply_params_tests {
fn recorder() -> (PluginSlot, Arc<Mutex<Vec<(String, f32)>>>) {
let sets = Arc::new(Mutex::new(Vec::new()));
let plugin = Box::new(Recorder { inner: soundcraft_dsp::create("gain").unwrap(), sets: Arc::clone(&sets) });
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }, sets)
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false }, sets)
}
fn lane(slot: u8, param: &str, point: Option<f32>) -> AutomationLane {
-43
View File
@@ -698,31 +698,6 @@ fn an_insert_that_puts_out_nan_is_taken_out_until_the_next_reset() {
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
}
/// A plugin that fails again after its one reset retry stays failed for the session, instead of
/// oscillating the track's latency (and its delay-line reallocations) on every stop/seek (#919).
#[test]
fn a_repeatedly_failing_insert_gets_only_one_reset_retry() {
let (mut s, a) = session_with_dc(0.5, 48_000);
let _b = add_dc_track(&mut s, 0.5, 48_000);
s.track_mut(a).unwrap().mixer.inserts[2] = Some(Insert::new("clap:test.nan"));
let mut eng = MixEngine::new(48_000.0, 512);
eng.set_external_instances(true);
let both = render_block(&mut eng, &s, 0);
eng.adopt(nan(a, 2, 1));
let only_b = render_block(&mut eng, &s, 512);
assert!((only_b - both / 2.0).abs() < 1e-6, "{only_b} vs {both}");
// While failed it passes the track's audio through, dry.
assert_eq!(render_block(&mut eng, &s, 1024), both);
// The first reset grants the single retry; it fails again.
eng.reset();
assert_eq!(render_block(&mut eng, &s, 1536), only_b);
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
// A later reset does not retry it again: the block stays dry and the count does not move.
eng.reset();
assert_eq!(render_block(&mut eng, &s, 2048), both);
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
}
#[test]
fn nan_from_an_instrument_or_a_master_insert_is_contained() {
let mut s = synth_session(-6.0);
@@ -1143,7 +1118,6 @@ fn a_hosted_instruments_latency_is_compensated() {
#[test]
fn input_monitoring_replaces_clips() {
let (mut s, t) = session_with_dc(0.5, 4800);
s.track_mut(t).unwrap().mixer.input = Route::Hardware("In 1".into());
let mut eng = MixEngine::new(48_000.0, 512);
eng.input = vec![vec![0.25; 512]];
let mut out = vec![vec![0.0; 512]; 2];
@@ -1162,23 +1136,6 @@ fn input_monitoring_replaces_clips() {
assert!(out[0][100].abs() < 1e-6, "stopped, unmonitored: silence");
}
/// A track whose input is "no input" (`Route::None`) hears nothing, not hardware input 1.
#[test]
fn a_track_with_no_input_monitors_nothing() {
let (mut s, t) = session_with_dc(0.0, 4800);
let mut eng = MixEngine::new(48_000.0, 512);
eng.input = vec![vec![0.25; 512], vec![0.5; 512]];
eng.monitor_only = true;
let mut out = vec![vec![0.0; 512]; 2];
s.track_mut(t).unwrap().mixer.input_monitor = true;
s.track_mut(t).unwrap().mixer.input = Route::None;
eng.render(&s, 0, 512, &mut out);
assert!(out.iter().all(|c| c.iter().all(|x| *x == 0.0)), "no input: silence, not In 1");
s.track_mut(t).unwrap().mixer.input = Route::Hardware("In 2".into());
eng.render(&s, 512, 512, &mut out);
assert!((out[0][100] - 0.5 * std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3, "In 2 is heard: {}", out[0][100]);
}
#[test]
fn empty_session_is_silent() {
let s = Session::default();
+5 -8
View File
@@ -1,15 +1,16 @@
use super::AUDIO_THREAD;
/// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks
/// do, every call: one thread-local store). [`MixEngine::render`] renders every strip on that
/// thread itself instead of handing strips to worker threads. Code that might run there asks
/// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads
/// count as the audio thread while they render for it. Code that might run there asks
/// [`on_audio_thread`] before doing anything that blocks; the desktop app's logger does, so a
/// `log::` record from the audio thread never takes a lock or touches a file.
pub fn mark_audio_thread() {
AUDIO_THREAD.set(true);
}
/// True on the thread [`mark_audio_thread`] marked. Lock-free and allocation-free.
/// True on the thread [`mark_audio_thread`] marked, and on a worker while it renders strips for
/// it. Lock-free and allocation-free.
pub fn on_audio_thread() -> bool {
AUDIO_THREAD.get()
}
@@ -28,11 +29,7 @@ fn as_audio_thread(audio: bool, f: impl FnOnce()) {
f();
}
/// Process strips: in parallel on native targets when there are enough of them, except on the
/// realtime audio thread. There they render one after the other on the thread itself: the pool's
/// workers run at normal priority, so under load the callback would wait for starved workers
/// (priority inversion) and miss its deadline, and waiting on them blocks, which the callback
/// never may. Offline renders (bounces) keep the parallelism.
/// Process strips, in parallel on native targets when there are enough of them.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn run_strips<T: Send>(work: &mut [T], f: impl Fn(&mut T) + Sync + Send) {
use rayon::prelude::*;
-435
View File
@@ -1,435 +0,0 @@
//! Independent PCM references for the bounded send consumers, with no hosted plugins/devices.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus, render_range};
use soundcraft_model::{
AutoParam, AutomationLane, AutomationMode, AutomationPoint, BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId,
TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
const LEN: usize = 640;
const PAN: [(i64, f32); 3] = [(37, -1.0), (173, 0.75), (401, 1.0)];
const MUTE: [(i64, f32); 5] = [(37, 0.0), (97, 1.0), (173, 0.0), (257, 1.0), (349, 0.0)];
fn fixture(format: ChannelFormat) -> (Session, TrackId, BusId) {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, format, None);
let src = SourceId(900);
let channels = (0..format.channels()).map(|ch| (0..LEN).map(|n| signal(ch, n)).collect()).collect();
s.pool.insert(src, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels })));
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original synthetic", src, 0, 0, LEN as i64));
let bus = s.add_bus("Send", ChannelFormat::Stereo);
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
let tr = s.track_mut(t).unwrap();
tr.mixer.output = Route::None;
let mut send = SendSlot::new(Route::Bus(bus));
send.level_db = 0.0;
tr.mixer.sends[0] = Some(send);
(s, t, bus)
}
fn signal(ch: usize, n: usize) -> f32 {
if n % 17 < 9 { 0.25 + ch as f32 / 100.0 } else { -0.125 - ch as f32 / 200.0 }
}
fn lane(s: &mut Session, t: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
s.track_mut(t).unwrap().automation.push(lane);
}
fn automated() -> (Session, TrackId, BusId) {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
(s, t, bus)
}
// The expectation never calls AutomationLane::value_at, pan::gains or any mixer helper.
fn expected_pan(at: i64) -> f64 {
if at <= PAN[0].0 {
return f64::from(PAN[0].1);
}
for pair in PAN.windows(2) {
if at < pair[1].0 {
let f = (at - pair[0].0) as f64 / (pair[1].0 - pair[0].0) as f64;
return f64::from(pair[0].1) + f64::from(pair[1].1 - pair[0].1) * f;
}
}
f64::from(PAN[2].1)
}
fn muted(at: i64) -> bool {
MUTE.iter().rev().find(|p| p.0 <= at).unwrap_or(&MUTE[0]).1 >= 0.5
}
fn pan_factors(p: f64, law: PanLaw) -> [f64; 2] {
if law == PanLaw::Zero {
return [(1.0 - p).min(1.0), (1.0 + p).min(1.0)];
}
let depth = match law {
PanLaw::Minus3 => -3.0,
PanLaw::Minus4_5 => -4.5,
PanLaw::Minus6 => -6.0,
PanLaw::Zero => 0.0,
};
let angle = (p + 1.0) * std::f64::consts::PI / 4.0;
[angle.cos().max(0.0).powf(depth / -3.0103), angle.sin().max(0.0).powf(depth / -3.0103)]
}
fn assert_shape(out: &[Vec<f32>], channels: usize, frames: usize) {
assert_eq!(out.len(), channels);
for channel in out {
assert_eq!(channel.len(), frames);
}
}
fn check(out: &[Vec<f32>], start: i64, frames: usize, law: PanLaw, scale: f64) {
assert_shape(out, 2, frames);
for (ch, values) in out.iter().enumerate() {
for (n, &actual) in values.iter().enumerate() {
let at = start + n as i64;
let reference = if muted(at) { 0.0 } else { f64::from(signal(0, at as usize)) * scale * pan_factors(expected_pan(at), law)[ch] };
assert!((f64::from(actual) - reference).abs() < 2e-7, "channel {ch}, at {at}: {actual} vs {reference}");
}
}
}
fn chunks(eng: &mut MixEngine, s: &Session, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut out = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut k = 0;
while offset < length {
let n = sizes[k % sizes.len()].min(length - offset);
let mut block = vec![vec![0.0; n]; 2];
eng.render(s, start + offset as i64, n, &mut block);
for (out, block) in out.iter_mut().zip(block) {
out.extend(block);
}
offset += n;
k += 1;
}
out
}
#[test]
fn pan_and_mute_match_independent_pcm_across_chunks() {
let (s, _, bus) = automated();
for block in [1, 37, 64, 100, 512, 1024] {
let mut e = MixEngine::new(48_000.0, block.max(16));
let out = chunks(&mut e, &s, 0, LEN, &[block]);
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
let mut e = MixEngine::new(48_000.0, 1024);
check(&chunks(&mut e, &s, 0, LEN, &[1, 37, 64, 3, 100, 19]), 0, LEN, PanLaw::Minus3, 1.0);
check(&render_bus(&s, bus, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn all_pan_laws_match_numeric_reference_and_static_calibration() {
let (s, _, _) = automated();
for law in [PanLaw::Minus3, PanLaw::Minus4_5, PanLaw::Minus6, PanLaw::Zero] {
let mut e = MixEngine::new(48_000.0, 1024);
e.pan_law = law;
check(&chunks(&mut e, &s, 0, LEN, &[100]), 0, LEN, law, 1.0);
for at in [0, 77, 173, 349, 401] {
let (mut reference, t, _) = fixture(ChannelFormat::Mono);
reference.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pan = expected_pan(at) as f32;
let mut static_engine = MixEngine::new(48_000.0, 16);
static_engine.pan_law = law;
let static_pcm = chunks(&mut static_engine, &reference, at, 1, &[1]);
let automated_pcm = chunks(&mut e, &s, at, 1, &[1]);
assert_shape(&automated_pcm, 2, 1);
assert_shape(&static_pcm, 2, 1);
assert_eq!(automated_pcm, static_pcm);
}
}
}
#[test]
fn seeking_used_engine_has_no_cursor_history() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
let _ = chunks(&mut e, &s, 0, 520, &[100]);
for at in [31, 77, 97, 98, 173, 256, 257, 301] {
let out = chunks(&mut e, &s, at, 31, &[17, 1, 13]);
check(&out, at, 31, PanLaw::Minus3, 1.0);
let mut fresh = MixEngine::new(48_000.0, 1024);
assert_eq!(out, chunks(&mut fresh, &s, at, 31, &[17, 1, 13]));
}
}
#[test]
fn loop_wrap_and_tiny_final_chunks_use_absolute_knots() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
// Same loop splitting as playback: do not render past the loop end before wrapping.
for _ in 0..3 {
check(&chunks(&mut e, &s, 37, 264, &[100, 63]), 37, 264, PanLaw::Minus3, 1.0);
}
for _ in 0..2 {
check(&chunks(&mut e, &s, 97, 76, &[37]), 97, 76, PanLaw::Minus3, 1.0);
}
}
#[test]
fn modes_and_lane_enabled_preserve_existing_reader_policy() {
for mode in AutomationMode::ALL {
let (mut s, t, _) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.automation_mode = mode;
tr.mixer.sends[0].as_mut().unwrap().mute = true;
for lane in &mut tr.automation {
lane.enabled = false;
}
let out = render_range(&s, Range::new(0, LEN as i64), 37);
assert_shape(&out, 2, LEN);
if mode == AutomationMode::Off {
assert!(out.iter().flatten().all(|v| *v == 0.0));
} else {
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
}
}
#[test]
fn missing_and_empty_lanes_keep_static_pan_and_mute() {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendPan(0), &[]);
lane(&mut s, t, AutoParam::SendMute(0), &[]);
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().mute = true;
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
#[test]
fn static_matrix_mute_steps_and_threshold_match_reference() {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendMute(0), &[(0, 0.49), (97, 0.5), (173, 0.0)]);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, 2, LEN);
assert_shape(&reference, 2, LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if (97..173).contains(&i) { 0.0 } else { r });
}
}
}
#[test]
fn mute_preserves_routing_for_mono_surround_and_sixteen_channels() {
for fmt in [ChannelFormat::Mono, ChannelFormat::Stereo, ChannelFormat::Surround51, ChannelFormat::Atmos714, ChannelFormat::Atmos916] {
let (mut s, t, bus) = fixture(fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, fmt.channels(), LEN);
assert_shape(&reference, fmt.channels(), LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if muted(i as i64) { 0.0 } else { r });
}
}
}
}
#[test]
fn wider_source_and_destination_send_pan_keep_static_routing() {
for (src_fmt, dst_fmt) in [
(ChannelFormat::Stereo, ChannelFormat::Stereo),
(ChannelFormat::Mono, ChannelFormat::Surround51),
(ChannelFormat::Surround51, ChannelFormat::Stereo),
] {
let (mut s, t, bus) = fixture(src_fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = dst_fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
assert_shape(&reference, dst_fmt.channels(), LEN);
let actual = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert_shape(&actual, dst_fmt.channels(), LEN);
assert_eq!(actual, reference);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
}
}
#[test]
fn pre_post_fader_send_level_and_direct_output_are_preserved() {
for pre in [false, true] {
let (mut s, t, bus) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let snd = tr.mixer.sends[0].as_mut().unwrap();
snd.pre_fader = pre;
snd.level_db = -3.0;
let factor = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
check(&render_range(&s, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, factor);
// Keep the direct path isolated from the Aux while comparing source-main PCM.
let aux = s.tracks.iter().find(|tr| tr.kind == TrackKind::Aux).unwrap().id;
s.track_mut(aux).unwrap().inactive = true;
s.track_mut(t).unwrap().mixer.output = Route::Main;
let direct = render_range(&s, Range::new(0, LEN as i64), 37);
s.track_mut(t).unwrap().automation.clear();
s.track_mut(t).unwrap().mixer.sends[0] = None;
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 37), direct);
assert_eq!(s.bus(bus).unwrap().format, ChannelFormat::Stereo);
}
}
#[test]
fn track_solo_and_vca_suppression_cannot_be_unmuted_by_send_lane() {
for suppression in [0, 1, 2] {
let (mut s, t, _) = automated();
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pre_fader = true;
match suppression {
0 => s.track_mut(t).unwrap().mixer.mute = true,
1 => {
let other = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
s.track_mut(other).unwrap().mixer.solo = true;
}
_ => {
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, None);
s.track_mut(vca).unwrap().mixer.mute = true;
s.track_mut(t).unwrap().mixer.vca = Some(vca.0);
}
}
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
}
#[test]
fn slots_a_and_j_and_absent_slots_do_not_drive_each_other() {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let other = s.add_bus("J", ChannelFormat::Stereo);
let mut send = SendSlot::new(Route::Bus(other));
send.level_db = 0.0;
s.track_mut(t).unwrap().mixer.sends[9] = Some(send);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(9), &PAN);
lane(&mut s, t, AutoParam::SendMute(9), &MUTE);
lane(&mut s, t, AutoParam::SendMute(8), &[(0, 1.0)]);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
check(&render_bus(&s, other, Range::new(0, LEN as i64), 100), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn malformed_lanes_fall_back_without_changing_document() {
for points in [
vec![AutomationPoint { at: 3, value: -1.0 }, AutomationPoint { at: 1, value: 1.0 }],
vec![AutomationPoint { at: 0, value: f32::NAN }],
vec![AutomationPoint { at: 0, value: f32::INFINITY }],
] {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut lane = AutomationLane::new(param);
lane.points = points.clone();
s.track_mut(t).unwrap().automation.push(lane);
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
#[test]
fn stereo_sends_keep_legacy_left_right_routing_for_every_static_pan() {
for static_pan in [-1.0, -0.75, 0.0, 0.75, 1.0, f32::NAN, f32::INFINITY] {
for state in ["absent", "empty", "off", "malformed", "active"] {
for pre in [false, true] {
for gated in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = static_pan;
send.pre_fader = pre;
send.level_db = -3.0;
match state {
"absent" => {}
"empty" => lane(&mut s, t, AutoParam::SendPan(0), &[]),
"off" => {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
}
"malformed" => {
let mut pan = AutomationLane::new(AutoParam::SendPan(0));
pan.points = vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: -1.0 }];
s.track_mut(t).unwrap().automation.push(pan);
}
"active" => lane(&mut s, t, AutoParam::SendPan(0), &PAN),
_ => unreachable!(),
}
if gated {
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
}
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
// Existing stereo sends route channels directly to L/R. This reference
// does not call either routing matrices or a pan helper.
let expected = if gated && state != "off" && muted(n as i64) { 0.0 } else { f64::from(signal(ch, n)) * scale };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} gated={gated} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
assert_eq!(s.track(t).unwrap().mixer.sends[0].as_ref().unwrap().pan.to_bits(), static_pan.to_bits());
}
}
}
}
}
#[test]
fn inactive_mono_send_lanes_match_independent_static_controls() {
for state in ["absent", "empty", "off", "unordered", "nan", "infinite"] {
for pre in [false, true] {
for static_mute in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = -0.625;
send.mute = static_mute;
send.pre_fader = pre;
send.level_db = -3.0;
if state == "off" {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
} else if state != "absent" {
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut control = AutomationLane::new(param);
control.points = match state {
"empty" => vec![],
"unordered" => vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: 0.0 }],
"nan" => vec![AutomationPoint { at: 0, value: f32::NAN }],
"infinite" => vec![AutomationPoint { at: 0, value: f32::INFINITY }],
_ => unreachable!(),
};
s.track_mut(t).unwrap().automation.push(control);
}
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
let factors = pan_factors(-0.625, PanLaw::Minus3);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
let expected = if static_mute { 0.0 } else { f64::from(signal(0, n)) * scale * factors[ch] };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} muted={static_mute} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
}
}
-322
View File
@@ -1,322 +0,0 @@
//! Send automation follows the delayed audio at its tap, without changing existing PDC routing.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus};
use soundcraft_model::{
AutoParam, AutomationLane, BusId, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
// The built-in Maximizer uses 1.5 ms of lookahead: 72 samples at 48 kHz, with a declared
// and physical delay of 72 - 1 = 71. Its untouched threshold 0 dB gives unity drive;
// every synthetic level stays below the default -0.3 dB ceiling, so there is no limiting.
// Expected timelines use these declared values, not mixer latency fields or the clock helper.
const LOOKAHEAD: usize = 71;
const SOURCE_FRAMES: usize = 2048;
const MUTE_AT: i64 = 300;
const AMPLITUDE: f32 = 0.25;
struct Graph {
session: Session,
capture: BusId,
receiver: TrackId,
clip_start: i64,
pan_start: i64,
pan_end: i64,
}
fn maximizers(session: &mut Session, track: TrackId, count: usize) {
for slot in session.track_mut(track).unwrap().mixer.inserts.iter_mut().take(count) {
*slot = Some(Insert::new("maximizer"));
}
}
fn source(session: &mut Session, insert_count: usize, clip_start: i64) -> TrackId {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Declared DC"));
let id = SourceId(901);
session.pool.insert(id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![AMPLITUDE; SOURCE_FRAMES]] })));
let clip = session.new_clip_id();
let t = session.track_mut(track).unwrap();
t.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared DC", id, 0, clip_start, SOURCE_FRAMES as i64));
t.mixer.pan = vec![0.0];
t.mixer.output = Route::None;
maximizers(session, track, insert_count);
track
}
fn silent_audio(session: &mut Session, insert_count: usize) {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Unrelated silent lookahead"));
session.track_mut(track).unwrap().mixer.output = Route::None;
maximizers(session, track, insert_count);
}
fn aux(session: &mut Session, input: BusId, format: ChannelFormat, insert_count: usize) -> TrackId {
let track = session.add_track(TrackKind::Aux, format, None);
let t = session.track_mut(track).unwrap();
t.mixer.input = Route::Bus(input);
t.mixer.output = Route::None;
t.mixer.pan = if format == ChannelFormat::Mono { vec![0.0] } else { vec![-1.0, 1.0] };
maximizers(session, track, insert_count);
track
}
fn silent_aux(session: &mut Session, insert_count: usize) {
let input = session.add_bus("Unrelated empty input", ChannelFormat::Mono);
aux(session, input, ChannelFormat::Mono, insert_count);
}
fn return_to_main(session: &mut Session, input: BusId) -> TrackId {
let track = aux(session, input, ChannelFormat::Stereo, 0);
session.track_mut(track).unwrap().mixer.output = Route::Main;
track
}
fn automation(session: &mut Session, track: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
session.track_mut(track).unwrap().automation.push(lane);
}
fn send(session: &mut Session, sender: TrackId, capture: BusId, pre: bool, pan_start: i64, pan_end: i64, automated_pan: bool) {
let mut send = SendSlot::new(Route::Bus(capture));
send.level_db = 0.0;
send.pre_fader = pre;
send.pan = -1.0;
session.track_mut(sender).unwrap().mixer.sends[0] = Some(send);
automation(session, sender, AutoParam::SendMute(0), &[(-512, 0.0), (MUTE_AT, 1.0)]);
if automated_pan {
automation(session, sender, AutoParam::SendPan(0), &[(pan_start, -1.0), (pan_end, 1.0)]);
}
}
fn ordinary(pre: bool, own_inserts: usize, silent_inserts: usize, pdc: bool, clip_start: i64, pan_start: i64, pan_end: i64) -> Graph {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let sender = source(&mut session, own_inserts, clip_start);
if silent_inserts > 0 {
silent_audio(&mut session, silent_inserts);
}
let capture = session.add_bus("Automation capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, pan_start, pan_end, true);
let receiver = return_to_main(&mut session, capture);
Graph { session, capture, receiver, clip_start, pan_start, pan_end }
}
fn make_mix() -> MixEngine {
let mut mix = MixEngine::new(48_000.0, 1024);
mix.pan_law = PanLaw::Zero;
mix
}
fn capture_pcm(mix: &mut MixEngine, graph: &Graph, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut main = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut block = 0;
while offset < length {
let n = sizes[block % sizes.len()].min(length - offset);
let mut main_block = vec![vec![0.0; n]; 2];
mix.render(&graph.session, start + offset as i64, n, &mut main_block);
for (output, samples) in main.iter_mut().zip(main_block) {
assert_eq!(samples.len(), n);
output.extend(samples);
}
offset += n;
block += 1;
}
main
}
fn numeric_pan(at: i64, first: i64, last: i64) -> [f32; 2] {
let pan = if at <= first {
-1.0
} else if at >= last {
1.0
} else {
(-1.0 + 2.0 * (at - first) as f64 / (last - first) as f64) as f32
};
// Independent declared zero-depth pan law; no routing or automation helper is called.
[(1.0 - pan).min(1.0), (1.0 + pan).min(1.0)]
}
fn check_known(output: &[Vec<f32>], graph: &Graph, start: i64, delay: usize, length: usize) {
assert_eq!(output.len(), 2);
for (channel, samples) in output.iter().enumerate() {
assert_eq!(samples.len(), length);
for (offset, &sample) in samples.iter().enumerate() {
let source_time = start + offset as i64 - delay as i64;
let audible =
offset >= delay && source_time >= graph.clip_start && source_time < graph.clip_start + SOURCE_FRAMES as i64 && source_time < MUTE_AT;
let expected = if audible { AMPLITUDE * numeric_pan(source_time, graph.pan_start, graph.pan_end)[channel] } else { 0.0 };
assert!(sample.is_finite());
assert!(
(sample - expected).abs() < 2e-7,
"channel {channel}, emit {}, source {source_time}, delay {delay}: {sample} != {expected}",
start + offset as i64
);
}
}
assert!(output.iter().flatten().any(|sample| sample.abs() > 0.02), "declared capture must be audible");
}
#[test]
fn unrelated_silent_lookahead_keeps_audio_pre_post_pan_and_last_source_sample_299() {
for pre in [false, true] {
let graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 800, &[1, 7, 37, 100, 3, 64]);
assert_eq!(mix.latency, LOOKAHEAD, "the unrelated real Maximizer actually contributes latency");
check_known(&output, &graph, 0, LOOKAHEAD, 800);
let last = output[0].iter().rposition(|sample| sample.abs() > 1e-6).unwrap();
assert_eq!(last, MUTE_AT as usize - 1 + LOOKAHEAD);
// Public render_bus uses its default -3 dB law. This separate mute-only fixture
// holds the static send at its left endpoint, whose factors are exactly1/0.
let mut offline_session = graph.session.clone();
offline_session.tracks[0].automation.retain(|lane| lane.param != AutoParam::SendPan(0));
let offline = render_bus(&offline_session, graph.capture, Range::new(0, 640), 37);
assert_eq!(offline[0].len(), 640);
assert_eq!(offline[0].iter().rposition(|sample| sample.abs() > 1e-6), Some(299));
for (channel, samples) in offline.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let expected = if at < MUTE_AT as usize && channel == 0 { AMPLITUDE } else { 0.0 };
assert!((sample - expected).abs() < 2e-7);
}
}
}
}
#[test]
fn aux_pre_tap_omits_post_alignment_while_both_taps_include_upstream_and_own_delay() {
for pdc in [false, true] {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Own upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let sender = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Aux capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let tap_delay = if pdc && !pre { 3 * LOOKAHEAD } else { 2 * LOOKAHEAD };
let observation_delay = if pdc { 2 * LOOKAHEAD } else { 0 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[100, 17, 1, 37, 64]);
assert_eq!(mix.latency, if pdc { 3 * LOOKAHEAD } else { 0 });
check_known(&output, &graph, 0, tap_delay + observation_delay, 900);
}
}
}
#[test]
fn nested_aux_taps_accumulate_the_actual_upstream_path_instead_of_global_latency() {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
silent_audio(&mut session, 2);
let first_bus = session.add_bus("Nested first", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(first_bus);
let first_aux = aux(&mut session, first_bus, ChannelFormat::Mono, 1);
let second_bus = session.add_bus("Nested second", ChannelFormat::Mono);
session.track_mut(first_aux).unwrap().mixer.output = Route::Bus(second_bus);
let sender = aux(&mut session, second_bus, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Nested capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
// Upstream audio2*71; first Aux own+alignment2*71; target pre adds1*71,
// target post adds2*71. The scalar global mix delay is only4*71.
let tap_delay = if pre { 5 * LOOKAHEAD } else { 6 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 1100, &[37, 3, 100, 64, 1]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
check_known(&output, &graph, 0, tap_delay + observation_delay, 1100);
}
}
#[test]
fn output_extra_downstream_aux_and_master_delay_do_not_shift_the_send_clock() {
for pre in [false, true] {
let mut graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let source = graph.session.tracks[0].id;
graph.session.track_mut(source).unwrap().mixer.output = Route::Main;
maximizers(&mut graph.session, graph.receiver, 1);
silent_aux(&mut graph.session, 2);
let master = graph.session.add_track(TrackKind::Master, ChannelFormat::Stereo, None);
maximizers(&mut graph.session, master, 1);
let mut mix = make_mix();
let main = capture_pcm(&mut mix, &graph, 0, 900, &[100, 37, 1, 64]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
assert!(main.iter().all(|channel| channel[..4 * LOOKAHEAD].iter().all(|sample| *sample == 0.0)));
assert!(main[0][4 * LOOKAHEAD] > 0.4, "main really traverses the excluded output/Aux/Master delays");
for (channel, samples) in main.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let source_time = at as i64 - (4 * LOOKAHEAD) as i64;
let expected = if source_time < 0 {
0.0
} else {
let sent = if source_time < MUTE_AT { AMPLITUDE * numeric_pan(source_time, 0, 600)[channel] } else { 0.0 };
AMPLITUDE + sent
};
assert!((sample - expected).abs() < 2e-7, "exclusion channel {channel}, emit {at}: {sample} != {expected}");
}
}
}
}
#[test]
fn unequal_aux_pre_and_direct_bus_ages_keep_the_documented_raw_clock_fallback() {
for target_pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Mixed upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let contributor = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let mixed_bus = session.add_bus("Unequal actual ages", ChannelFormat::Mono);
session.track_mut(contributor).unwrap().mixer.output = Route::Bus(mixed_bus);
let mut pre_send = SendSlot::new(Route::Bus(mixed_bus));
pre_send.level_db = 0.0;
pre_send.pre_fader = true;
session.track_mut(contributor).unwrap().mixer.sends[0] = Some(pre_send);
let sender = aux(&mut session, mixed_bus, ChannelFormat::Mono, 0);
let capture = session.add_bus("Mixed capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, target_pre, 0, 600, false);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[37, 100, 1, 3, 64]);
let extra = if target_pre { 0 } else { 2 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let delays = [2 * LOOKAHEAD + extra + observation_delay, 3 * LOOKAHEAD + extra + observation_delay];
for (at, (&left, &right)) in output[0].iter().zip(&output[1]).enumerate() {
let contributions = delays.iter().filter(|&&delay| at >= delay).count();
let expected = if at < MUTE_AT as usize + observation_delay { AMPLITUDE * contributions as f32 } else { 0.0 };
assert!((left - expected).abs() < 2e-7, "mixed tap pre={target_pre} emit{at}: {left} != {expected}");
assert_eq!(right, 0.0);
}
assert!(output[0].iter().any(|sample| *sample > 0.02));
}
}
#[test]
fn negative_positions_and_reset_seek_use_the_delayed_source_clock_with_pdc_off() {
let graph = ordinary(false, 1, 0, false, -512, -300, 300);
let mut mix = make_mix();
let negative = capture_pcm(&mut mix, &graph, -128, 256, &[1, 37, 3, 64, 17]);
assert_eq!(mix.latency, 0, "PDC is off while the insert still physically delays its source");
check_known(&negative, &graph, -128, LOOKAHEAD, 256);
mix.reset();
let seek = capture_pcm(&mut mix, &graph, 240, 400, &[100, 1, 37, 3]);
check_known(&seek, &graph, 240, LOOKAHEAD, 400);
assert_eq!(seek[1].iter().rposition(|sample| sample.abs() > 1e-6), Some(130));
}
+5 -74
View File
@@ -1,7 +1,7 @@
use super::{
Arc, AtomicBool, AtomicU32, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering,
OutputTrouble, Plugin, PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared,
SyncSender, TrackId, devices, itu_stereo_fold, main_channels, midi, record, sync_channel,
Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin,
PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId,
itu_stereo_fold, main_channels, midi, record, sync_channel,
};
use soundcraft_mix::{LiveMidi, midi_port_bit, midi_thru};
use soundcraft_model::TrackKind;
@@ -17,29 +17,6 @@ pub(crate) struct Fault {
pub(crate) beats: std::sync::atomic::AtomicU64,
/// The UI has been told.
reported: AtomicBool,
/// Underruns the device reported, callbacks that overran their buffer period, and the worst
/// callback's share of its buffer time (‰), since the stream opened or the last
/// [`Player::take_health`], and the device callbacks in that time.
xruns: std::sync::atomic::AtomicU64,
late_callbacks: std::sync::atomic::AtomicU64,
worst_load: AtomicU32,
callbacks: std::sync::atomic::AtomicU64,
}
/// How the realtime audio path keeps up, for the UI and for stress tests: since the output
/// opened, or since the last [`Player::take_health`].
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub struct AudioHealth {
/// Device callbacks (none for the silent clock).
pub callbacks: u64,
/// Underruns (dropouts) the device reported.
pub xruns: u64,
/// Callbacks that overran their buffer period. Not every one is an audible gap, and the
/// device may report the same overrun as an xrun too (CoreAudio does).
pub late_callbacks: u64,
/// The slowest callback's render time as a share of its buffer period, to 0.001 (1.0 = it
/// overran).
pub worst_load: f64,
}
impl Fault {
@@ -56,50 +33,6 @@ impl Fault {
};
(!self.reported.swap(true, Ordering::Relaxed)).then_some(trouble)
}
/// A device callback rendered `frames` at `rate` in `took`. Lock-free and allocation-free.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn note_callback(&self, took: std::time::Duration, frames: usize, rate: f64) {
self.callbacks.fetch_add(1, Ordering::Relaxed);
if frames == 0 || rate <= 0.0 {
return;
}
let load = took.as_secs_f64() * rate / frames as f64;
if load > 1.0 {
self.late_callbacks.fetch_add(1, Ordering::Relaxed);
}
self.worst_load.fetch_max((load * 1000.0).min(f64::from(u32::MAX)) as u32, Ordering::Relaxed);
}
/// The stream reported an error (on the audio thread or another). A lost stream is recorded
/// as gone; a transient xrun is counted and the stream keeps playing.
pub(crate) fn note_stream_error(&self, e: &cpal::Error) {
if devices::stream_lost(e) {
self.gone.store(true, Ordering::Relaxed);
} else if e.kind() == cpal::ErrorKind::Xrun {
self.xruns.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.load(Ordering::Relaxed),
xruns: self.xruns.load(Ordering::Relaxed),
late_callbacks: self.late_callbacks.load(Ordering::Relaxed),
worst_load: f64::from(self.worst_load.load(Ordering::Relaxed)) / 1000.0,
}
}
/// The health so far, counting afresh from here: each counter is swapped for zero, so an
/// event the callback records meanwhile lands in this reading or the next, never in neither.
pub(crate) fn take_health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.swap(0, Ordering::Relaxed),
xruns: self.xruns.swap(0, Ordering::Relaxed),
late_callbacks: self.late_callbacks.swap(0, Ordering::Relaxed),
worst_load: f64::from(self.worst_load.swap(0, Ordering::Relaxed)) / 1000.0,
}
}
}
/// How long a playing output may go without a block before it counts as stalled.
@@ -1048,16 +981,14 @@ impl Side {
}
}
/// `false` when no block was rendered since the last take (`out` keeps its readings).
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) -> bool {
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) {
if !source.fresh {
// No block since the last take: keep the readings, but not those of deleted tracks.
out.tracks.retain(|id, _| source.tracks.contains_key(id));
return false;
return;
}
copy_meter_snapshot(source, out);
source.reset_levels();
true
}
pub(crate) fn copy_meter_snapshot(source: &MeterSnapshot, out: &mut MeterSnapshot) {
-105
View File
@@ -175,62 +175,6 @@ pub(crate) fn device(host: &cpal::Host, name: Option<&str>, output: bool) -> Opt
if output { host.default_output_device() } else { host.default_input_device() }
}
/// Why the device does not run at the chosen buffer size, when it does not. `running` is the
/// size the open stream reports it runs at, when it reports one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BufferNote {
/// The size is outside the range the driver reports; the device runs at its default buffer.
/// A range of one size (a shared-mode WASAPI device reports only its period) means the device
/// runs only at that size.
OutsideRange { min: u32, max: u32, running: Option<u32> },
/// The driver refused the size although it reports no range, or one that holds the size; the
/// device runs at its default buffer.
Refused { want: u32, running: Option<u32> },
/// The device took the size, but the open stream runs at another one (a host may round a
/// fixed size to one the hardware supports).
Rounded { want: u32, running: u32 },
}
impl BufferNote {
/// The note in English (the reply's `buffer_note`, and the key of the window's translation).
pub fn english(&self) -> String {
match *self {
BufferNote::OutsideRange { min, max, .. } if min == max => format!("The device runs only at {min} samples."),
BufferNote::OutsideRange { min, max, running: Some(n) } => {
format!("The device allows {min}–{max} samples; it runs at its default buffer, {n} samples.")
}
BufferNote::OutsideRange { min, max, running: None } => format!("The device allows {min}–{max} samples; it runs at its default buffer."),
BufferNote::Refused { want, running: Some(n) } => {
format!("The device did not take {want} samples; it runs at its default buffer, {n} samples.")
}
BufferNote::Refused { want, running: None } => format!("The device did not take {want} samples; it runs at its default buffer."),
BufferNote::Rounded { want, running } => format!("The device runs at {running} samples, not {want}."),
}
}
}
/// The note for a chosen buffer (`want`) the device did not take (`used`, `None` for its
/// default), or took but runs at another size, given the range its driver reports and the size
/// the open stream runs at.
pub fn buffer_note(want: Option<u32>, used: Option<u32>, range: Option<(u32, u32)>, running: Option<u32>) -> Option<BufferNote> {
let want = want?;
if used == Some(want) {
return running.filter(|&n| n != want).map(|running| BufferNote::Rounded { want, running });
}
Some(match range {
Some((min, max)) if !(min..=max).contains(&want) => BufferNote::OutsideRange { min, max, running },
_ => BufferNote::Refused { want, running },
})
}
/// The range a driver reports, if it reports one.
pub(crate) fn buffer_range(supported: &cpal::SupportedBufferSize) -> Option<(u32, u32)> {
match supported {
cpal::SupportedBufferSize::Range { min, max } => Some((*min, *max)),
cpal::SupportedBufferSize::Unknown => None,
}
}
/// The buffer to request: the chosen size when the device's range allows it, else the default.
pub(crate) fn buffer_size(want: Option<u32>, supported: &cpal::SupportedBufferSize) -> cpal::BufferSize {
match (want, supported) {
@@ -246,55 +190,6 @@ pub(crate) fn buffer_size(want: Option<u32>, supported: &cpal::SupportedBufferSi
mod tests {
use super::*;
/// A buffer the driver does not take is said, not silently replaced (#1757).
#[test]
fn a_buffer_the_device_did_not_take_gets_a_note() {
// The RME UFX on Core Audio allows 15..=3072 frames (measured); 4096 opens at its default.
assert_eq!(buffer_note(Some(4096), None, Some((15, 3072)), None), Some(BufferNote::OutsideRange { min: 15, max: 3072, running: None }));
assert_eq!(
BufferNote::OutsideRange { min: 15, max: 3072, running: None }.english(),
"The device allows 15–3072 samples; it runs at its default buffer."
);
// The driver gave no range and refused the size.
assert_eq!(buffer_note(Some(100), None, None, None), Some(BufferNote::Refused { want: 100, running: None }));
// A size within the reported range that still failed is refused, not outside the range.
assert_eq!(buffer_note(Some(256), None, Some((15, 3072)), None), Some(BufferNote::Refused { want: 256, running: None }));
// Taken as asked, or nothing asked: no note.
assert_eq!(buffer_note(Some(256), Some(256), Some((15, 3072)), Some(256)), None);
assert_eq!(buffer_note(None, None, Some((15, 3072)), Some(512)), None);
}
/// The note says the size the device runs at, when the stream reports it.
#[test]
fn the_note_says_the_buffer_the_device_runs_at() {
let note = buffer_note(Some(4096), None, Some((15, 3072)), Some(512)).unwrap();
assert_eq!(note, BufferNote::OutsideRange { min: 15, max: 3072, running: Some(512) });
assert_eq!(note.english(), "The device allows 15–3072 samples; it runs at its default buffer, 512 samples.");
let refused = buffer_note(Some(100), None, None, Some(480)).unwrap();
assert_eq!(refused.english(), "The device did not take 100 samples; it runs at its default buffer, 480 samples.");
}
/// A fixed size the device opened with can still run at another size (cpal: "the host may
/// round to hardware-supported values"); the note names the size it runs at.
#[test]
fn a_size_the_device_took_but_runs_differently_gets_a_note() {
let note = buffer_note(Some(100), Some(100), Some((15, 3072)), Some(128)).unwrap();
assert_eq!(note, BufferNote::Rounded { want: 100, running: 128 });
assert_eq!(note.english(), "The device runs at 128 samples, not 100.");
assert_eq!(buffer_note(Some(100), Some(100), Some((15, 3072)), Some(100)), None, "runs as asked");
assert_eq!(buffer_note(Some(100), Some(100), Some((15, 3072)), None), None, "no running size reported");
}
/// A shared-mode WASAPI device reports one size (its period, 480 frames at 48 kHz on the
/// Windows test machine), so the range has a single value.
#[test]
fn a_device_with_one_buffer_size_is_said_to_run_only_at_it() {
let note = buffer_note(Some(256), None, Some((480, 480)), Some(480)).unwrap();
assert_eq!(note, BufferNote::OutsideRange { min: 480, max: 480, running: Some(480) });
assert_eq!(note.english(), "The device runs only at 480 samples.");
assert_eq!(buffer_note(Some(256), None, Some((480, 480)), None).unwrap().english(), "The device runs only at 480 samples.");
}
#[test]
fn config_round_trips_and_tolerates_missing_fields() {
let c = AudioConfig {
+12 -46
View File
@@ -48,9 +48,8 @@ const BLOCK: usize = 512;
/// Room for replaced snapshots on their way back; `update_session` empties it before each send.
const OLD_SESSIONS: usize = 16;
pub use callback::AudioHealth;
/// The realtime audio thread marker lives in the mix engine, which renders every strip on the
/// marked thread itself; the cpal callbacks here set it.
/// The realtime audio thread marker lives in the mix engine, which carries it into the strips it
/// renders on worker threads; the cpal callbacks here set it.
pub use soundcraft_mix::{mark_audio_thread, on_audio_thread};
mod callback;
@@ -63,7 +62,7 @@ use callback::{STALL, copy_meter_snapshot};
use callback::{guarded_block, stalled};
#[cfg(test)]
use stream::pick_output_config;
use stream::{Opened, build_output, first_started, open_device, running_buffer, start_stream};
use stream::{Opened, build_output, first_started, open_device, start_stream};
/// Meter values for the UI: the highest peak (and gain reduction) of every block rendered since
/// the UI last took them with [`Player::take_meters`]. The audio thread renders blocks faster than
@@ -106,12 +105,6 @@ impl MeterSnapshot {
self.fresh = true;
}
/// Zero every level, keeping the entries and their storage: for a reader whose readings went
/// stale because no block has arrived for a while (the device stopped calling back).
pub fn clear_levels(&mut self) {
self.reset_levels();
}
/// Drop the entries of deleted tracks.
fn forget(&mut self, gone: &[TrackId]) {
for id in gone {
@@ -185,10 +178,6 @@ pub struct Player {
pub device_channels: u16,
/// The device buffer in frames when one was chosen (`None`: the device default).
pub device_buffer: Option<u32>,
/// The buffer range the output device's driver reports, when it reports one.
pub device_buffer_range: Option<(u32, u32)>,
/// The buffer the open output stream reports it runs at (`None` when it reports none).
pub device_buffer_running: Option<u32>,
/// True when no audio device could be opened (silent clock).
pub silent: bool,
}
@@ -222,19 +211,6 @@ impl Player {
self.fault.trouble(stalled)
}
/// How the realtime path has kept up since the output opened or the last
/// [`Player::take_health`]: callbacks, device-reported underruns, late callbacks and the
/// worst callback load.
pub fn health(&self) -> AudioHealth {
self.fault.health()
}
/// [`Player::health`] so far, then count afresh (a stress run measures from a take). No
/// event is lost between the reading and the restart.
pub fn take_health(&self) -> AudioHealth {
self.fault.take_health()
}
fn side(&self) -> std::sync::MutexGuard<'_, Side> {
self.side.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -258,7 +234,7 @@ impl Player {
Mutex::new(side)
};
match open_device(want, want_ch, cfg) {
Ok((device, config, format, name, buffer_range)) => {
Ok((device, config, format, name)) => {
// The chosen buffer size first; if the device refuses it, its default.
let mut attempts = vec![config];
if config.buffer_size != cpal::BufferSize::Default {
@@ -290,11 +266,9 @@ impl Player {
cpal::BufferSize::Fixed(n) => Some(n),
cpal::BufferSize::Default => None,
};
let running = running_buffer(&stream);
log::info!(
"audio device: {name} @ {rate} Hz, {channels} ch, {format}, buffer {}{}",
buffer.map_or("default".to_string(), |n| n.to_string()),
running.map_or(String::new(), |n| format!(" (runs at {n})"))
"audio device: {name} @ {rate} Hz, {channels} ch, {format}, buffer {}",
buffer.map_or("default".to_string(), |n| n.to_string())
);
Player {
shared,
@@ -308,8 +282,6 @@ impl Player {
device_rate: rate,
device_channels: config.channels,
device_buffer: buffer,
device_buffer_range: buffer_range,
device_buffer_running: running,
silent: false,
}
}
@@ -387,8 +359,6 @@ impl Player {
device_rate: rate,
device_channels: 0,
device_buffer: None,
device_buffer_range: None,
device_buffer_running: None,
silent: true,
}
}
@@ -412,8 +382,6 @@ impl Player {
device_rate: session.sample_rate.hz(),
device_channels: 0,
device_buffer: None,
device_buffer_range: None,
device_buffer_running: None,
silent: true,
}
}
@@ -571,15 +539,13 @@ impl Player {
/// Take the meters accumulated since the last call into reusable UI storage and start a new
/// period: `out` gets the highest peak of every block rendered in between. If no block was
/// rendered since (a large device buffer renders several blocks per callback), `out` keeps
/// the previous values rather than dropping to silence, and the call returns `false`: when
/// that goes on for longer than any device buffer lasts, the device has stopped calling back
/// and the reader should clear the readings ([`MeterSnapshot::clear_levels`]). Call it from
/// one place only (two readers would split the peaks between them). Once track/channel
/// counts are stable this performs no allocation. The audio thread only ever `try_lock`s, so
/// holding the lock here never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) -> bool {
/// the previous values rather than dropping to silence. Call it from one place only (two
/// readers would split the peaks between them). Once track/channel counts are stable this
/// performs no allocation. The audio thread only ever `try_lock`s, so holding the lock here
/// never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) {
let mut source = self.shared.meters.lock().unwrap_or_else(PoisonError::into_inner);
take_meter_snapshot(&mut source, out)
take_meter_snapshot(&mut source, out);
}
}
-12
View File
@@ -669,18 +669,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_channel_the_device_does_not_have_is_recorded_as_digital_silence() {
// A track with no input records `usize::MAX`, a channel no device has.
let dir = std::env::temp_dir().join(format!("soundcraft-silent-take-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut take = TakeWriter::create(TrackId(1), vec![usize::MAX, 0], dir.join("Vox_01.wav"), 48_000, ONE_FILE).unwrap();
take.write(&[0.25; 200], 2);
take.write_header();
assert_eq!(decode(&dir.join("Vox_01.wav")), vec![vec![0.0; 100], vec![0.25; 100]]);
let _ = std::fs::remove_dir_all(&dir);
}
/// Files of 100 stereo or 200 mono frames: blocks that straddle a file's end are split there.
#[test]
fn a_take_that_fills_its_file_goes_on_in_the_next() {
+9 -19
View File
@@ -1,5 +1,5 @@
use super::callback::{AudioState, Fault, guarded_block};
use super::{Arc, AudioConfig, Cmd, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
/// Start a freshly built output stream. `false` when the device refuses to start it, so the caller
/// treats it like a stream that failed to build and tries the next configuration.
@@ -13,12 +13,6 @@ pub(crate) fn start_stream(stream: &impl cpal::traits::StreamTrait) -> bool {
}
}
/// The buffer a started stream reports it runs at: Core Audio's device buffer, WASAPI's period.
/// `None` when the backend cannot say (or says 0).
pub(crate) fn running_buffer(stream: &impl cpal::traits::StreamTrait) -> Option<u32> {
stream.buffer_size().ok().filter(|n| *n > 0)
}
/// A built output stream and the channels and fault flag its callback shares with the player.
pub(crate) struct Opened {
pub(crate) stream: cpal::Stream,
@@ -63,14 +57,10 @@ where
let mut scratch = vec![0.0f32; 8192 * frame];
let chunk = scratch.len();
let (failed, guard, gone) = (Arc::clone(fault), Arc::clone(shared), Arc::clone(fault));
#[cfg(not(target_arch = "wasm32"))]
let rate = f64::from(config.sample_rate);
device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
mark_audio_thread();
#[cfg(not(target_arch = "wasm32"))]
let started = std::time::Instant::now();
for out in data.chunks_mut(chunk) {
let Some(s) = scratch.get_mut(..out.len()) else { return };
guarded_block(&failed, &guard, s, |d| state.fill(d, channels));
@@ -78,8 +68,6 @@ where
*o = T::from_sample(*x);
}
}
#[cfg(not(target_arch = "wasm32"))]
failed.note_callback(started.elapsed(), data.len() / frame, rate);
},
// cpal may call this on the audio thread (on ALSA in a loop while the device stays
// broken): marked, so the logger hands the record off instead of writing it.
@@ -89,7 +77,9 @@ where
// stream that must be rebuilt (`StreamInvalidated`), stops playback until the user
// reconnects; a rerouted default device (`DeviceChanged`) keeps playing on the new
// route, and an xrun is transient, so neither counts as losing the stream.
gone.note_stream_error(&e);
if devices::stream_lost(&e) {
gone.gone.store(true, Ordering::Relaxed);
}
log::warn!("audio stream error: {e}");
},
None,
@@ -104,7 +94,7 @@ pub(crate) fn open_device(
want_rate: u32,
want_ch: u16,
cfg: &AudioConfig,
) -> Result<(cpal::Device, cpal::StreamConfig, cpal::SampleFormat, String, Option<(u32, u32)>), String> {
) -> Result<(cpal::Device, cpal::StreamConfig, cpal::SampleFormat, String), String> {
use cpal::traits::DeviceTrait;
let host = devices::host(cfg);
let device = devices::device(&host, cfg.output.as_deref(), true).ok_or_else(|| "no output device".to_string())?;
@@ -113,10 +103,10 @@ pub(crate) fn open_device(
let want_ch = want_ch.max(2);
let rates: Vec<u32> = cfg.sample_rate.into_iter().chain(Some(want_rate)).collect();
let configs: Vec<cpal::SupportedStreamConfigRange> = device.supported_output_configs().map(|configs| configs.collect()).unwrap_or_default();
let (config, format, range) = match pick_output_config(&configs, &rates, want_ch) {
let (config, format) = match pick_output_config(&configs, &rates, want_ch) {
Some((mut c, buffers, format)) => {
c.buffer_size = devices::buffer_size(cfg.buffer_size, &buffers);
(c, format, devices::buffer_range(&buffers))
(c, format)
}
None => {
let d = device.default_output_config().map_err(|e| e.to_string())?;
@@ -136,10 +126,10 @@ pub(crate) fn open_device(
};
let mut stream_config = c.config();
stream_config.buffer_size = devices::buffer_size(cfg.buffer_size, c.buffer_size());
(stream_config, c.sample_format(), devices::buffer_range(c.buffer_size()))
(stream_config, c.sample_format())
}
};
Ok((device, config, format, name, range))
Ok((device, config, format, name))
}
/// Pick the output configuration for the first requested rate the device offers (the configured
+4 -37
View File
@@ -15,8 +15,7 @@ impl cpal::traits::StreamTrait for Fake {
fn pause(&self) -> Result<(), cpal::Error> {
Ok(())
}
/// The fake stream reports 0 frames, which says nothing about a buffer (see
/// `a_stream_that_reports_no_buffer_size_has_no_running_buffer`).
/// The fake stream has no clock and no fixed buffer; neither is used by these tests.
fn buffer_size(&self) -> Result<cpal::FrameCount, cpal::Error> {
Ok(0)
}
@@ -26,12 +25,6 @@ impl cpal::traits::StreamTrait for Fake {
}
}
#[test]
fn a_stream_that_reports_no_buffer_size_has_no_running_buffer() {
// The fake reports 0 frames, which says nothing about the device.
assert_eq!(stream::running_buffer(&Fake { starts: true }), None);
}
#[test]
fn a_stream_that_will_not_start_is_reported_as_failed() {
assert!(!start_stream(&Fake { starts: false }));
@@ -162,7 +155,7 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
// The last block alone (what the UI used to see) is quiet.
assert!(st.mix.meters[&t].peak[0] < 0.05);
let mut ui = MeterSnapshot::default();
assert!(take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui), "new blocks arrived");
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] > 0.85, "{:?}", ui.tracks[&t]);
assert!(ui.tracks[&t].peaks[0] > 0.85);
assert!(ui.main.peak[0] > 0.5 && ui.main.peaks.iter().all(|p| *p > 0.5), "{:?}", ui.main);
@@ -170,12 +163,9 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
st.fill(&mut out, 2);
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] < 0.05 && ui.main.peak[0] < 0.05);
// No block since the last take: the reading stays rather than dropping to silence, and the
// reader is told, so it can clear readings that stay stale (the device stopped calling back).
assert!(!take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui));
// No block since the last take: the reading stays rather than dropping to silence.
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] > 0.005);
ui.clear_levels();
assert!(ui.tracks[&t].peak[0] == 0.0 && ui.main.peak[0] == 0.0 && ui.tracks[&t].peaks.len() == 1, "{:?}", ui.tracks[&t]);
}
#[test]
@@ -289,28 +279,6 @@ fn a_lost_or_stalled_device_is_reported_once() {
assert_eq!((fault.trouble(false), fault.trouble(true)), (Some(OutputTrouble::Gone), None));
}
#[test]
fn underruns_and_late_callbacks_are_counted_until_taken() {
use std::time::Duration;
let f = Fault::default();
let error = |kind| cpal::Error::with_message(kind, "test");
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
// 512 frames at 48 kHz last 10.67 ms.
f.note_callback(Duration::from_millis(4), 512, 48_000.0);
f.note_callback(Duration::from_millis(16), 512, 48_000.0);
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
let h = f.health();
assert_eq!(h, AudioHealth { callbacks: 3, xruns: 2, late_callbacks: 1, worst_load: 1.5 });
assert!(!f.gone.load(Ordering::Relaxed), "an underrun is not a lost device");
assert_eq!(f.take_health(), h);
assert_eq!(f.health(), AudioHealth::default());
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
assert_eq!(f.health().callbacks, 1);
f.note_stream_error(&error(cpal::ErrorKind::DeviceNotAvailable));
assert!(f.gone.load(Ordering::Relaxed));
}
#[test]
fn audio_state_plays_and_stops_at_end() {
let s = Arc::new(soundcraft_model::Session::default());
@@ -728,7 +696,6 @@ fn armed_tracks_are_heard_and_metered_after_playback_stops() {
let mut s = soundcraft_model::Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
s.track_mut(t).unwrap().mixer.record_arm = true;
s.track_mut(t).unwrap().mixer.input = soundcraft_model::Route::Hardware("In 1".into());
let shared = Arc::new(Shared {
position: AtomicI64::new(0),
playing: AtomicBool::new(false),
-5
View File
@@ -10,11 +10,6 @@ repository.workspace = true
[dependencies]
craft-mime.workspace = true
craft-ui.workspace = true
craft-behavior.workspace = true
craft-host.workspace = true
craft-keymap.workspace = true
craft-theme.workspace = true
craft-window.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
soundcraft-midi.workspace = true
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-21
View File
@@ -114,8 +114,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
"End" => "Fim",
"Extract" => "Extrair",
"File" => "Arquivo",
"File path" => "Caminho do arquivo",
"Folder path" => "Caminho da pasta",
"Format" => "Formato",
"Grab bag" => "Diversos",
"Grid" => "Grade",
@@ -325,23 +323,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
}
"No engine" => "Sem mecanismo de áudio",
"default buffer" => "buffer padrão",
"The audio settings were changed outside this window; your unapplied changes were replaced." => {
"As configurações de áudio foram alteradas fora desta janela; suas alterações não aplicadas foram substituídas."
}
"The device allows {}–{} samples; it runs at its default buffer." => {
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão."
}
"The device did not take {} samples; it runs at its default buffer." => {
"O dispositivo não aceitou {} amostras; ele funciona com o buffer padrão."
}
"The device runs only at {} samples." => "O dispositivo funciona apenas com {} amostras.",
"The device runs at {} samples, not {}." => "O dispositivo funciona com {} amostras, não {}.",
"The device allows {}–{} samples; it runs at its default buffer, {} samples." => {
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão, {} amostras."
}
"The device did not take {} samples; it runs at its default buffer, {} samples." => {
"O dispositivo não aceitou {} amostras; ele funciona com o buffer padrão, {} amostras."
}
"Bus name: {name}" => "Nome do bus: {name}",
"Model" => "Modelo",
"Version" => "Versão",
@@ -1782,8 +1763,6 @@ fn menu_translate(source: &str) -> Option<&'static str> {
"Enable Track Notes Dialog" => "Ativar o diálogo de notas da pista",
"English" => "Inglês",
"Portuguese (Brazil)" => "Português (Brasil)",
"French" => "Francês",
"Spanish" => "Espanhol",
"key:Space" => "Espaço",
"key:Up" => "Cima",
"key:Down" => "Baixo",
+1 -1
View File
@@ -176,7 +176,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let current=state.compositions.iter().find(|(_,id)|*id==state.composition).map_or("Choose one…".to_string(),|(n,_)|n.clone());
// Locked while analyzing, so a finished analysis always matches the selection.
ui.add_enabled_ui(state.busy.is_none(),|ui|{
egui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
craft_ui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
for (name,id) in &state.compositions {
if ui.selectable_label(state.composition==*id,format!("{name} ({id})")).clicked() { state.composition=id.clone(); state.preview=None; }
}
+2 -16
View File
@@ -81,7 +81,6 @@ impl SoundApp {
synthetic_batch: None,
synthetic_pointer_active: false,
cancel_synthetic_pointer: false,
injected_acks: VecDeque::new(),
cancel_synthetic_keys: false,
cancel_synthetic_scroll: false,
input_before_scroll: None,
@@ -112,9 +111,6 @@ impl SoundApp {
system_fonts: true,
theme_applied: None,
docking_context: None,
docks: crate::docking::LiveDocks::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: crate::framework::host(),
sim: None,
record_hint: None,
quit_requested: false,
@@ -129,7 +125,6 @@ impl SoundApp {
frame_ms: 0.0,
last_frame: None,
last_meter_poll: f64::NEG_INFINITY,
last_meter_block: f64::NEG_INFINITY,
video: video_track::VideoPool::default(),
bounce: None,
imports: import::Imports::default(),
@@ -156,12 +151,6 @@ impl SoundApp {
let _language = crate::localization::enter(self.ui.language);
self.ui.undo_levels = self.ui.undo_levels.clamp(1, 64);
self.engine.set_history_limit(self.ui.undo_levels);
// A saved state (a hand-edited `ui.json`) can hold more than the menu keeps: keep the newest
// (the list is newest first) and have the host save the corrected list.
if self.ui.recent_sessions.len() > crate::dialogs::recent::MAX_RECENT {
self.ui.recent_sessions.truncate(crate::dialogs::recent::MAX_RECENT);
self.recent_changed = true;
}
// Fonts set now take effect next frame, so draw only from the frame after.
if !self.fonts_ready {
if self.fonts_installed {
@@ -193,7 +182,7 @@ impl SoundApp {
// Frame pacing and the transport simulation use a monotonic host clock instead.
let dt = self.tick_dt();
self.last_frame = Some(self.uptime);
crate::control::expire_gestures(self, ctx);
crate::control::expire_gestures(self);
crate::control::drain(self, ctx);
self.note_recent_session();
self.apply_editor_edits();
@@ -326,7 +315,7 @@ impl SoundApp {
// Input preparation: remember this pass's real pointer/keyboard state, which `logic` (run
// before `ui` in each pass and alone on hidden ticks) uses for gestures and automation.
self.pointer_down = ctx.input(|i| i.pointer.any_down());
self.wants_keyboard = crate::framework::widget_has_keyboard(&ctx);
self.wants_keyboard = ctx.egui_wants_keyboard_input();
// The integration creates this Ui before logic resolves the current frame's palette.
ui.set_style(ctx.global_style());
if !self.fonts_ready {
@@ -367,11 +356,8 @@ impl SoundApp {
dialogs::show(self, &ctx);
aaf_import::show(self, &ctx);
updates_ui::show(self, &ctx);
self.run_framework_dialogs(ui);
// The sampler's drop rects are current now, so route any captured drop in this pass.
self.route_dropped_files();
// A scripted key (`ui.key`) is acknowledged by the framework's idle signal, not by egui's event list.
crate::control::injected_settled(self, &ctx);
// The pass that actually received the injected events has already dispatched their widget
// side effects, even when it then asks for another layout pass. `received_synthetic` was
// captured before menus and widgets, so a widget that consumed the event from InputState
+3 -186
View File
@@ -27,7 +27,7 @@ impl SoundApp {
// The input reopens on the next record or monitor with the new choice.
self.recorder = None;
self.recorder_failed = false;
let player = reopen(&mut self.player, &self.ui.audio, || soundcraft_playback::Player::with_config(self.engine.session_arc(), &self.ui.audio));
let player = soundcraft_playback::Player::with_config(self.engine.session_arc(), &self.ui.audio);
self.attach_midi(&player);
player.locate(at);
self.player = Some(player);
@@ -127,52 +127,12 @@ impl SoundApp {
}
self.recorder = None;
self.recorder_failed = false;
let player = reopen(&mut self.player, &self.ui.audio, || Player::with_config(self.engine.session_arc(), &self.ui.audio));
let player = Player::with_config(self.engine.session_arc(), &self.ui.audio);
self.attach_midi(&player);
self.player = Some(player);
}
}
/// How long the meters keep the last readings while no audio block arrives. Longer than the
/// longest device buffer (8192 frames at 44.1 kHz, 186 ms) plus the slowest meter poll (50 ms), so
/// a large buffer never reads as silence between its callbacks; once it has passed, the device has
/// stopped calling back (switched off, unplugged, stalled) and the meters fall to silence.
pub(super) const METER_STALE_SECS: f64 = 0.5;
/// After a meter take that `fresh`ly brought new blocks or not, at `now` (uptime, seconds): note
/// when the last block came in `last_block`, and clear `snap`'s readings once none has come for
/// [`METER_STALE_SECS`]. Otherwise the last block's levels would be fed to the meters every frame
/// and never fall.
pub(super) fn age_meters(snap: &mut soundcraft_playback::MeterSnapshot, fresh: bool, now: f64, last_block: &mut f64) {
if fresh {
*last_block = now;
} else if now - *last_block >= METER_STALE_SECS {
snap.clear_levels();
}
}
/// Open the new device of `cfg` with `open` in place of the one in `slot`, and return it; the caller
/// stores it, which closes the old one if it is still there.
///
/// On ASIO the old device closes first: in cpal 0.18.2 a process holds one ASIO driver, and while
/// the old stream keeps it loaded the device list stops at the first other driver, so the new device
/// (even the same driver again) is often not found and the player falls back to the silent clock
/// (#1864). Elsewhere (Core Audio, WASAPI, ALSA, JACK) a device opens whatever else is open, and the
/// old one stays open until the new one is there, as before: closing first there would only make the
/// new device start cold, which on Core Audio holds Apply on the UI thread for about half a second.
fn reopen<T>(slot: &mut Option<T>, cfg: &soundcraft_playback::AudioConfig, open: impl FnOnce() -> T) -> T {
if one_driver_per_process(cfg) {
drop(slot.take());
}
open()
}
/// Whether `cfg`'s audio system opens one driver per process (ASIO in cpal 0.18.2), so the device in
/// use must close before another (or the same one again) can be found.
fn one_driver_per_process(cfg: &soundcraft_playback::AudioConfig) -> bool {
cfg.system.as_deref().is_some_and(|s| s.eq_ignore_ascii_case("ASIO"))
}
pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], gr: f32, dt: f32) {
// Instant attack, ~26 dB/s release, 2 s peak hold.
let fall = 10f32.powf(-26.0 * dt / 20.0);
@@ -183,9 +143,7 @@ pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], gr: f32, dt: f32)
if let Some(x) = d.level.get_mut(c) {
*x = if nv < 1e-5 { 0.0 } else { nv };
}
// Only a signal holds: silence meeting a hold of 0 would restart the shared hold time
// every frame and keep the other channel's hold up for good.
if v > 0.0 && v >= d.hold.get(c).copied().unwrap_or(0.0) {
if v >= d.hold.get(c).copied().unwrap_or(0.0) {
if let Some(h) = d.hold.get_mut(c) {
*h = v;
}
@@ -209,84 +167,6 @@ pub(super) fn wants_audio_input(s: &soundcraft_model::Session) -> bool {
s.tracks.iter().any(|t| !t.kind.is_midi() && (t.mixer.input_monitor || t.mixer.record_arm))
}
#[cfg(test)]
mod reopen_tests {
use super::reopen;
use soundcraft_playback::AudioConfig;
use std::cell::Cell;
use std::rc::Rc;
/// A fake audio system. `one_driver` models ASIO in cpal 0.18.2: while a stream holds the
/// driver, looking a device up by name finds nothing. Without it, any device opens.
#[derive(Default)]
struct FakeHost {
one_driver: bool,
open_streams: Rc<Cell<u32>>,
opened_while_another_was_open: Cell<u32>,
}
/// An open stream; dropping it closes it (and releases an ASIO driver).
struct Stream(Rc<Cell<u32>>);
impl Drop for Stream {
fn drop(&mut self) {
self.0.set(self.0.get() - 1);
}
}
/// A player: its stream when the device was found, else the silent clock (no stream).
struct FakePlayer {
stream: Option<Stream>,
}
impl FakeHost {
fn open(&self) -> FakePlayer {
if self.open_streams.get() > 0 {
self.opened_while_another_was_open.set(self.opened_while_another_was_open.get() + 1);
if self.one_driver {
return FakePlayer { stream: None };
}
}
self.open_streams.set(self.open_streams.get() + 1);
FakePlayer { stream: Some(Stream(Rc::clone(&self.open_streams))) }
}
}
fn config(system: &str) -> AudioConfig {
AudioConfig { system: Some(system.into()), output: Some("ASIO4ALL v2".into()), ..AudioConfig::default() }
}
/// Apply, Apply, Reconnect: each step opens the device of `cfg` in place of the open one, as
/// `apply_audio_config` and `reconnect_audio` do. Returns whether each step found the device.
fn apply_apply_reconnect(host: &FakeHost, cfg: &AudioConfig) -> Vec<bool> {
let mut player = Some(host.open());
assert!(player.as_ref().is_some_and(|p| p.stream.is_some()), "the first open finds the device");
let mut found = Vec::new();
for _ in ["first Apply", "second Apply", "Reconnect"] {
let new = reopen(&mut player, cfg, || host.open());
found.push(new.stream.is_some());
player = Some(new);
}
found
}
#[test]
fn on_asio_every_apply_and_reconnect_finds_the_device() {
let host = FakeHost { one_driver: true, ..FakeHost::default() };
assert_eq!(apply_apply_reconnect(&host, &config("ASIO")), [true, true, true], "no step falls back to the silent clock");
assert_eq!(host.opened_while_another_was_open.get(), 0, "the old stream released the driver before each lookup");
}
#[test]
fn elsewhere_the_old_device_stays_open_until_the_new_one_is_there() {
for system in ["CoreAudio", "WASAPI"] {
let host = FakeHost::default();
assert_eq!(apply_apply_reconnect(&host, &config(system)), [true, true, true]);
assert_eq!(host.opened_while_another_was_open.get(), 3, "{system}: each new device opened before the old one closed, as before");
}
}
}
#[cfg(test)]
mod audio_input_tests {
use super::wants_audio_input;
@@ -309,66 +189,3 @@ mod audio_input_tests {
assert!(wants_audio_input(&s));
}
}
#[cfg(test)]
mod meter_tests {
use super::{METER_STALE_SECS, MeterDisplay, age_meters, feed_meter};
use soundcraft_mix::StripMeter;
use soundcraft_model::TrackId;
use soundcraft_playback::MeterSnapshot;
/// Runs the UI's meter loop for `secs` at 60 frames a second, polling at 20 Hz as the Edit
/// window does; `blocks(prev, now)` says whether a block (with `peak`) arrived since the
/// previous poll.
fn run(secs: f64, peak: [f32; 2], blocks: impl Fn(f64, f64) -> bool) -> (MeterDisplay, f32) {
let t = TrackId(1);
let mut snap = MeterSnapshot::default();
let mut d = MeterDisplay::default();
let (mut last_block, mut last_poll, mut lowest) = (f64::NEG_INFINITY, f64::NEG_INFINITY, f32::INFINITY);
let dt = 1.0 / 60.0;
let mut now = 0.0;
while now < secs {
if now - last_poll >= 1.0 / 20.0 {
let fresh = blocks(last_poll.max(-1e-9), now);
if fresh {
let m = snap.tracks.entry(t).or_insert_with(StripMeter::default);
m.peak = peak;
m.peaks = peak.to_vec();
}
age_meters(&mut snap, fresh, now, &mut last_block);
last_poll = now;
}
let m = snap.tracks.get(&t).map_or([0.0; 2], |m| m.peak);
feed_meter(&mut d, m, 0.0, dt as f32);
if now > 0.0 {
lowest = lowest.min(d.level[0]);
}
now += dt;
}
(d, lowest)
}
#[test]
fn meters_fall_to_silence_when_the_device_stops_calling_back() {
// Blocks come for a second, then the device is switched off: no callback ever again.
let (d, _) = run(6.0, [0.4; 2], |_, now| now < 1.0);
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
}
/// A silent channel does not keep the other channel's peak hold up: 0.0 meets a hold of 0.0
/// every frame, which must not restart the shared hold time.
#[test]
fn a_silent_channel_does_not_keep_the_other_channels_peak_hold() {
let (d, _) = run(6.0, [0.4, 0.0], |_, now| now < 1.0);
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
}
#[test]
fn a_large_device_buffer_keeps_the_meters_up_between_callbacks() {
// 8192 frames at 44.1 kHz: one block every 186 ms, several polls without one.
let period = 8192.0 / 44_100.0;
assert!(period + 1.0 / 20.0 < METER_STALE_SECS);
let (d, lowest) = run(3.0, [0.4; 2], |prev, now| (now / period).floor() > (prev / period).floor());
assert!(lowest >= 0.4 && d.level[0] >= 0.4, "the meter dropped to {lowest} between callbacks");
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ impl SoundApp {
self.note_host_geometry(ctx, raw);
// Expire before injecting: a gesture that can no longer reach a UI pass must not put one
// last copy of its events into this pass after its request was already canceled.
crate::control::expire_gestures(self, ctx);
crate::control::expire_gestures(self);
// A host that could not run a UI pass retains the input this hook mutated (eframe's
// `pending_raw_input`, the web runner's `input.raw`) and hands it back next tick. Strip the
// copy appended last time before appending the still-pending batch again: otherwise a
+7 -79
View File
@@ -1,4 +1,4 @@
use super::audio::{age_meters, feed_meter};
use super::audio::feed_meter;
use super::plugins::failed_plugin_status;
use super::{Gesture, MainWindow, MeterDisplay, Range, Samples, SoundApp, TrackId, TransportRequest, json};
@@ -234,8 +234,6 @@ impl SoundApp {
Ok(dir)
}
/// Ends recording, clears the punch state and places the recorded takes
/// (from the recorder or the take plan when the recorder is already gone).
fn finish_recording(&mut self) {
self.engine.transport.recording = false;
let midi_pass = self.end_midi_pass();
@@ -248,21 +246,13 @@ impl SoundApp {
// The audio input stops taking in first: waiting for the MIDI below would otherwise add
// what the input hears meanwhile to the audio takes. No input device is open when the
// pass was MIDI only.
let (takes, problem) = self.recorder.as_mut().map_or_else(|| (Vec::new(), None), |r| r.finish());
// The audio thread writes down what was played up to the stop; the clips wait for that.
let plan = self.take_plan.take();
self.punch = None;
self.autosaved_rev = 0;
// The recorder can already be gone (tests run headless): the plan still names the takes,
// so place what it holds; with neither, there is nothing to place.
let (takes, problem) = match (&mut self.recorder, &plan) {
(Some(r), _) => r.finish(),
(None, Some(plan)) => (plan.takes.iter().map(|t| (t.track, t.path.clone())).collect(), None),
(None, None) => (Vec::new(), None),
};
let midi_confirmed = self.await_midi_capture(midi_pass);
// Where the pass ended: the audio engine's own position is the freshest.
let engine_at = self.player.as_ref().map(|p| p.position());
let stopped_at = super::midi::pass_stop(engine_at, self.engine.transport.position);
let plan = self.take_plan.take();
let tracks = takes.len().max(1);
let plan = plan.unwrap_or_else(|| soundcraft_engine::io::Recording {
start: self.record_start,
@@ -271,6 +261,8 @@ impl SoundApp {
rate: 0,
takes: Vec::new(),
});
self.punch = None;
self.autosaved_rev = 0;
let ids = soundcraft_engine::io::place_recording(&mut self.engine, &plan, takes);
// The audio engine may have confirmed the pass while the audio takes were finished: the
// stop position and what the user is told go by one answer.
@@ -471,14 +463,7 @@ impl SoundApp {
}
TransportRequest::Record => {
if self.engine.transport.recording {
// Punching out ends the take; while playing, the transport keeps
// running, like QuickPunch. `finish_recording` places the take
// without touching playback.
if self.is_playing() {
self.finish_recording();
} else {
self.stop_play();
}
self.stop_play();
} else {
self.start_recording();
}
@@ -522,8 +507,7 @@ impl SoundApp {
let now = self.uptime;
let meter_interval = if self.ui.window == MainWindow::Mix { 1.0 / 60.0 } else { 1.0 / 20.0 };
if now - self.last_meter_poll >= meter_interval {
let fresh = p.take_meters(&mut self.meter_snapshot);
age_meters(&mut self.meter_snapshot, fresh, now, &mut self.last_meter_block);
p.take_meters(&mut self.meter_snapshot);
self.last_meter_poll = now;
}
let snap = &self.meter_snapshot;
@@ -578,60 +562,4 @@ mod tests {
assert_eq!(app.fallback_take_dir().unwrap(), a, "the same folder for the rest of the run");
let _ = std::fs::remove_dir_all(&a);
}
/// Punching out (Record pressed again mid-take) ends the take and leaves the transport
/// running, like QuickPunch: the punch clears, the take is placed inside the punch range,
/// and playback continues from where it was.
#[test]
fn punching_out_while_playing_keeps_the_transport_running() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.run("track.new", json!({"count": 1, "format": "mono"})).unwrap();
let track = app.engine.session().tracks[0].id;
// A take already recorded over the punch range, so the punch-out has something to place.
let take = std::env::temp_dir().join(format!("soundcraft-punch-out-take-{}.wav", std::process::id()));
let opts = craft_audio::EncodeOptions::new(craft_audio::EncodeFormat::Wav);
std::fs::write(
&take,
craft_audio::encode(&craft_audio::AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 96_000]] }, &opts).unwrap(),
)
.unwrap();
app.record_start = 0;
app.punch = Some(Range { start: 48_000, end: 96_000 });
app.take_plan = Some(soundcraft_engine::io::Recording {
start: 0,
pass: None,
punch: app.punch,
rate: 48_000,
takes: vec![soundcraft_engine::io::Take { track, path: take.clone(), channels: 1 }],
});
// Punch out two seconds in: the playhead must keep its place, not restart from the top.
app.start_play(96_000, None, None);
app.engine.transport.recording = true;
app.engine.transport_requests.push(TransportRequest::Record);
app.handle_transport(1.0 / 60.0);
assert!(!app.engine.transport.recording, "the take ends");
assert!(app.punch.is_none(), "the punch clears");
assert!(app.is_playing(), "playback continues after the punch-out");
assert!(app.engine.transport.position >= 96_000, "the playhead keeps its place instead of restarting");
let clips = app.engine.session().track(track).unwrap().clips().to_vec();
assert_eq!(clips.len(), 1, "the take is placed");
assert_eq!(clips[0].start, 48_000, "the take is trimmed to the punch");
assert_eq!(clips[0].end(), 96_000, "the take covers the punch");
let _ = std::fs::remove_file(&take);
}
/// A Record press while recording but not playing (a player that died mid-take, say)
/// still stops everything, from where it was.
#[test]
fn a_record_press_while_recording_but_stopped_still_stops() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.start_play(96_000, None, None);
app.engine.transport.playing = false;
app.engine.transport.recording = true;
app.engine.transport_requests.push(TransportRequest::Record);
app.handle_transport(1.0 / 60.0);
assert!(!app.engine.transport.recording);
assert!(!app.is_playing());
assert_eq!(app.engine.transport.position, 96_000, "the playhead stays where it stopped");
}
}
+1 -1
View File
@@ -70,7 +70,7 @@ fn slice() -> impl FnMut() -> bool {
/// Shows how far the running bounce got, with Cancel (or Esc).
pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let Some(job) = &app.bounce else { return };
let mut cancel = crate::framework::escape_pressed(ctx);
let mut cancel = ctx.input(|i| i.key_pressed(egui::Key::Escape));
egui::Modal::new(egui::Id::unique("bounce_progress")).show(ctx, |ui| {
ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);
ui.set_width(320.0);
-211
View File
@@ -1,211 +0,0 @@
//! One-shot completion slots for `ui.screenshot` captures.
//!
//! The app keeps request ids, paths, deadlines, settling and budgets in its request record
//! (`control::PendingShot`). A slot only correlates one capture with one record, checks the image against
//! a per-image byte bound, and wakes the owning viewport.
//!
//! [`CaptureSlot::new`] sends nothing: send its callback with [`egui::ViewportCommand::Screenshot`]
//! when the capture is due. The callback holds only a weak reference to the slot, so dropping the
//! slot releases its image and makes a late result inert. Every retry needs a
//! fresh slot and callback.
//!
//! The slot holds a strong [`egui::Context`]: keep it in the app's request record, never in
//! `Context`-owned data, which would form a cycle.
use std::mem::size_of;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use egui::{Color32, ColorImage, Context, ScreenshotCallback, ViewportId};
/// Why a completed screenshot was rejected and released.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CaptureError {
/// The checked pixel count, or its byte count, overflowed `usize`.
DimensionsOverflow { width: usize, height: usize },
/// The pixel buffer does not match the dimensions, or the image has no area.
MalformedImage { width: usize, height: usize, pixels: usize },
/// The image is larger than the slot's per-image byte bound.
ImageTooLarge { bytes: usize, max_bytes: usize },
}
impl core::fmt::Display for CaptureError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::DimensionsOverflow { width, height } => {
write!(f, "screenshot dimensions {width}×{height} overflow the checked pixel or byte count")
}
Self::MalformedImage { width, height, pixels } => write!(f, "screenshot has {pixels} pixels for its {width}×{height} dimensions"),
Self::ImageTooLarge { bytes, max_bytes } => write!(f, "screenshot uses {bytes} bytes, over the {max_bytes}-byte per-image limit"),
}
}
}
impl std::error::Error for CaptureError {}
enum SlotState {
Pending,
Ready(Result<Arc<ColorImage>, CaptureError>),
Taken,
Cancelled,
}
struct Shared {
state: Mutex<SlotState>,
/// The live request owns the strong context; the callback only upgrades it briefly to wake.
context: Context,
viewport: ViewportId,
max_image_bytes: usize,
}
/// The live request side of a capture. Dropping it cancels the completion and releases any
/// retained image.
#[must_use = "the slot must be kept alive to receive and take the screenshot"]
pub(crate) struct CaptureSlot {
shared: Arc<Shared>,
}
impl CaptureSlot {
/// A completion slot for a capture of `viewport` and its one-shot callback. `max_image_bytes`
/// bounds this one image; the app reserves its aggregate budget itself.
pub(crate) fn new(context: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback) {
let shared = Arc::new(Shared { state: Mutex::new(SlotState::Pending), context: context.clone(), viewport, max_image_bytes });
let weak = Arc::downgrade(&shared);
let callback = ScreenshotCallback::new(move |image| complete(&weak, image));
(Self { shared }, callback)
}
/// The completed result, at most once; `None` while pending and after an
/// earlier take. The request record knows which.
pub(crate) fn take(&self) -> Option<Result<Arc<ColorImage>, CaptureError>> {
let mut state = lock(&self.shared.state);
if !matches!(&*state, SlotState::Ready(_)) {
return None;
}
match core::mem::replace(&mut *state, SlotState::Taken) {
SlotState::Ready(result) => Some(result),
_ => None,
}
}
}
impl Drop for CaptureSlot {
fn drop(&mut self) {
close(&self.shared);
}
}
impl core::fmt::Debug for CaptureSlot {
/// The viewport only: logging never holds or dumps screenshot contents.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CaptureSlot").field("viewport", &self.shared.viewport).finish_non_exhaustive()
}
}
/// Locks the slot state, recovering from poisoning. Release the guard before calling into the
/// context: a repaint observer may take or cancel re-entrantly.
fn lock(state: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Marks the slot closed; the retained image drops after the mutex is released.
fn close(shared: &Shared) {
let previous = {
let mut state = lock(&shared.state);
core::mem::replace(&mut *state, SlotState::Cancelled)
};
drop(previous);
}
/// Checks and stores a completed image, then wakes the owning viewport, with the slot lock
/// released. A cancelled, taken or dropped slot stores nothing and does not wake.
fn complete(weak: &Weak<Shared>, image: Arc<ColorImage>) {
let Some(shared) = weak.upgrade() else { return };
let result = checked_image(image, shared.max_image_bytes);
let wake = {
let mut state = lock(&shared.state);
if matches!(&*state, SlotState::Pending) {
*state = SlotState::Ready(result);
true
} else {
false
}
};
if wake {
shared.context.request_repaint_of(shared.viewport);
}
}
/// `image` when it has area, its buffer matches its size, and its byte count (checked) is within
/// `max_image_bytes`.
fn checked_image(image: Arc<ColorImage>, max_image_bytes: usize) -> Result<Arc<ColorImage>, CaptureError> {
let [width, height] = image.size;
if width == 0 || height == 0 {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
let pixels = width.checked_mul(height).ok_or(CaptureError::DimensionsOverflow { width, height })?;
let bytes = pixels.checked_mul(size_of::<Color32>()).ok_or(CaptureError::DimensionsOverflow { width, height })?;
if image.pixels.len() != pixels {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
if bytes > max_image_bytes {
return Err(CaptureError::ImageTooLarge { bytes, max_bytes: max_image_bytes });
}
Ok(image)
}
#[cfg(test)]
mod tests {
use super::*;
fn image(size: [usize; 2]) -> Arc<ColorImage> {
Arc::new(ColorImage::filled(size, Color32::RED))
}
fn observe_repaints(ctx: &Context) -> Arc<Mutex<Vec<ViewportId>>> {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = requests.clone();
ctx.set_repaint_observer(move |info| observed.lock().unwrap().push(info.viewport_id));
requests
}
#[test]
fn a_completion_wakes_its_viewport_and_is_taken_once() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("window");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
assert!(slot.take().is_none(), "pending");
let shot = image([2, 1]);
callback.complete(shot.clone());
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &shot));
assert!(slot.take().is_none(), "taken once");
assert_eq!(*requests.lock().unwrap(), [viewport]);
}
#[test]
fn a_dropped_slot_releases_a_late_image_without_waking() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
drop(slot);
let late = image([2, 2]);
let weak = Arc::downgrade(&late);
callback.complete(late);
assert!(weak.upgrade().is_none());
assert!(requests.lock().unwrap().is_empty());
}
#[test]
fn oversized_malformed_and_overflowing_images_are_errors() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
callback.complete(image([3, 3]));
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![Color32::RED; 3] }));
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [usize::MAX, 2], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { .. }))));
}
}
+10 -59
View File
@@ -17,8 +17,7 @@
//! inspect, command or screenshot after the gesture it follows.
use crate::SoundApp;
use crate::capture::CaptureSlot;
use craft_ui::runtime::windows::WindowHost;
use craft_ui::capture::CaptureSlot;
use serde_json::{Value, json};
use std::sync::mpsc::{Receiver, Sender, channel};
use web_time::Instant;
@@ -37,7 +36,7 @@ impl ControlRequest {
}
/// One admitted `ui.screenshot` request. The app owns the strong completion slot; the callback the
/// renderer receives holds only a weak reference to it (see `crate::capture`).
/// renderer receives holds only a weak reference to it (see `craft_ui::capture`).
pub(crate) struct PendingShot {
token: u64,
/// Taken once the single reply (success, timeout, cancellation or failure) was sent.
@@ -279,32 +278,9 @@ pub(crate) struct GestureAck {
response: Value,
}
/// A `ui.key` request whose reply waits for the framework's injected input to run: the runtime owns the key's path
/// (it takes keys such as Escape out of egui's event list), so only its own idle signal says the key was delivered.
pub(crate) struct InjectedAck {
deadline: Instant,
reply: Option<Sender<Value>>,
response: Value,
}
/// True while a scripted gesture has events waiting or an applied batch still needs acknowledging.
pub(crate) fn gesture_pending(app: &SoundApp) -> bool {
!app.gesture_acks.is_empty() || !app.synthetic.is_empty() || app.synthetic_batch.is_some() || !app.injected_acks.is_empty()
}
/// Reply to every queued `ui.key` once the framework's injected input has run, asked at the end of the pass that ran
/// the key (a pass egui repeats does not count).
pub(crate) fn injected_settled(app: &mut SoundApp, ctx: &egui::Context) {
if app.injected_acks.is_empty() || !WindowHost::of(ctx).injected_idle_at_pass_end() {
return;
}
for mut ack in std::mem::take(&mut app.injected_acks) {
if let Some(tx) = ack.reply.take() {
let _ = tx.send(ack.response);
}
}
// The next request queued behind this key needs a logic tick to be drained now that the barrier is gone.
ctx.request_repaint();
!app.gesture_acks.is_empty() || !app.synthetic.is_empty() || app.synthetic_batch.is_some()
}
/// Count one delivered batch against the front gesture. Batches never straddle requests (a key
@@ -331,16 +307,8 @@ pub(crate) fn synthetic_delivered(app: &mut SoundApp, delivered: usize) {
/// A gesture that cannot reach a UI pass (a host that never paints) must not wedge every later
/// control request. Cancel the whole pending gesture chain: FIFO means no later request can run
/// while an earlier undelivered click is still waiting.
pub(crate) fn expire_gestures(app: &mut SoundApp, ctx: &egui::Context) {
pub(crate) fn expire_gestures(app: &mut SoundApp) {
let now = app.clock_now();
if app.injected_acks.iter().any(|ack| now >= ack.deadline) {
WindowHost::of(ctx).withdraw_injected(egui::ViewportId::ROOT);
for mut ack in std::mem::take(&mut app.injected_acks) {
if let Some(tx) = ack.reply.take() {
let _ = tx.send(err("synthetic input was not delivered"));
}
}
}
if !app.gesture_acks.iter().any(|ack| now >= ack.deadline) {
return;
}
@@ -488,19 +456,6 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
"session.inspect" | "document.inspect" => {
ok(soundcraft_engine::inspect::session(&app.engine, p.get("detail").and_then(Value::as_str) == Some("full")))
}
"audio.health" => match &app.player {
Some(player) => {
let h = if p.get("reset").and_then(Value::as_bool) == Some(true) { player.take_health() } else { player.health() };
ok(json!({
"device": player.device_name,
"silent": player.silent,
"sample_rate": player.device_rate,
"buffer_frames": player.device_buffer,
"health": h,
}))
}
None => err("no audio output"),
},
"ui.inspect" => {
let mut v = app.inspect(ctx);
v["edit_layout"] = json!(app.edit_layout);
@@ -589,16 +544,12 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
"ui.key" => {
let name = p.get("key").and_then(Value::as_str).unwrap_or("");
let Some(key) = key_from(name) else { return Some(err(format!("unknown key `{name}`"))) };
let Some(key) = craft_keymap::Key::from_egui(key) else { return Some(err(format!("key `{name}` has no keymap key"))) };
let mods = craft_keymap::Mods::from_egui(&mods(p), craft_keymap::egui::platform(ctx));
// The framework's injected input carries the key through its own stages and says when it has run.
WindowHost::of(ctx).inject_key(egui::ViewportId::ROOT, key, mods, false);
app.injected_acks.push_back(InjectedAck {
deadline: app.clock_now() + GESTURE_TIMEOUT,
reply: Some(req.reply.clone()),
response: ok(json!({})),
});
return None;
let m = mods(p);
let events = vec![
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m },
egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: m },
];
return queue_reply(app, req, events, json!({}));
}
"ui.text" => {
let t = p.get("text").and_then(Value::as_str).unwrap_or("");
+29 -43
View File
@@ -93,7 +93,6 @@ fn tmp(name: &str) -> PathBuf {
#[test]
fn a_screenshot_completes_once_and_writes_one_file() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("success");
let _ = std::fs::remove_file(&path);
@@ -115,7 +114,6 @@ fn a_screenshot_completes_once_and_writes_one_file() {
#[test]
fn a_callback_after_the_deadline_times_out_without_writing() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("late");
let reply = request(&mut a, Some(&path));
@@ -134,7 +132,6 @@ fn a_callback_after_the_deadline_times_out_without_writing() {
#[test]
fn a_session_change_cancels_the_request_and_releases_its_pixels() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("document");
let reply = request(&mut a, Some(&path));
@@ -153,7 +150,6 @@ fn a_session_change_cancels_the_request_and_releases_its_pixels() {
#[test]
fn admission_rejects_more_than_eight_pending_requests() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
for i in 0..MAX_PENDING_SHOTS {
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
@@ -169,7 +165,6 @@ fn admission_rejects_more_than_eight_pending_requests() {
#[test]
fn admission_rejects_an_image_over_the_per_image_and_aggregate_budgets() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
let mut big = raw_input(5000.0, 5000.0, 8192);
a.raw_input_hook(&ctx, &mut big);
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
@@ -195,7 +190,6 @@ fn admission_rejects_an_image_over_the_per_image_and_aggregate_budgets() {
#[test]
fn a_changed_window_retries_once_instead_of_writing_stale_pixels() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("retry");
let reply = request(&mut a, Some(&path));
@@ -254,7 +248,6 @@ fn a_missing_max_texture_side_uses_the_last_known_limit() {
#[test]
fn a_window_without_geometry_reports_no_capturable_size() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.host_geometry = Some(CaptureGeometry { points: egui::Vec2::ZERO, pixels_per_point: 1.0, max_texture_side: 8192, focused: true });
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
let e = admit(&mut a, &ctx, &req).expect_err("no capturable size");
@@ -266,7 +259,6 @@ fn a_window_without_geometry_reports_no_capturable_size() {
#[test]
fn a_document_replaced_outside_run_cancels_a_pending_capture() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let reply = request(&mut a, None);
let out = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
@@ -286,7 +278,6 @@ fn a_document_replaced_outside_run_cancels_a_pending_capture() {
#[test]
fn a_queued_click_is_applied_before_a_following_inspect_and_screenshot() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let kick = a.engine.session().track_by_name("Kick").expect("demo has Kick").id;
assert!(!a.engine.session().track(kick).expect("kick").mixer.mute);
@@ -347,7 +338,6 @@ fn a_queued_click_is_applied_before_a_following_inspect_and_screenshot() {
#[test]
fn a_capture_slot_is_bounded_by_its_own_reservation() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let (tx, rx) = channel();
let (req, first) = ControlRequest::new("ui.screenshot", json!({}));
@@ -389,7 +379,6 @@ fn png_bytes_checks_its_dimensions_and_allocation() {
#[test]
fn control_input_queues_and_text_are_bounded() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.synthetic = (0..MAX_SYNTHETIC_EVENTS).map(|_| egui::Event::PointerMoved(egui::pos2(0.0, 0.0))).collect();
let (req, _reply) = ControlRequest::new("ui.move", json!({"x": 1.0, "y": 2.0}));
let v = handle(&mut a, &ctx, &req).expect("the refusal replies immediately");
@@ -416,7 +405,6 @@ fn control_input_queues_and_text_are_bounded() {
#[test]
fn a_very_long_screenshot_path_is_refused_before_it_is_retained() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = "x".repeat(MAX_SHOT_PATH_BYTES + 1);
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({"path": path}));
@@ -430,11 +418,10 @@ fn a_very_long_screenshot_path_is_refused_before_it_is_retained() {
#[test]
fn an_undelivered_gesture_is_canceled_without_wedging_the_next_request() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
let (req, reply) = ControlRequest::new("ui.click", json!({"x": 10.0, "y": 10.0}));
assert!(handle(&mut a, &ctx, &req).is_none(), "the click waits for a UI pass");
a.advance_test_clock(Duration::from_secs(16));
expire_gestures(&mut a, &ctx);
expire_gestures(&mut a);
let v = reply.try_recv().expect("the canceled gesture has exactly one reply");
assert_eq!(v["ok"], false, "{v}");
assert!(v["error"].as_str().unwrap_or_default().contains("not delivered"), "{v}");
@@ -453,7 +440,6 @@ fn an_undelivered_gesture_is_canceled_without_wedging_the_next_request() {
fn a_timed_out_consumed_press_cancels_without_clicking_and_the_next_click_works() {
for expires_after_hook in [false, true] {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let kick = a.engine.session().track_by_name("Kick").unwrap().id;
@@ -503,28 +489,48 @@ fn a_timed_out_consumed_press_cancels_without_clicking_and_the_next_click_works(
/// An expired scripted shortcut never reaches widgets or end-of-pass handling, while a simultaneous host shortcut
/// still runs and a later script succeeds.
#[test]
fn a_timed_out_scripted_key_does_not_run_and_the_next_key_works() {
fn a_timed_out_scripted_key_after_the_hook_does_not_run_and_the_next_key_works() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 1, "format": "stereo"})).unwrap();
let depth = a.engine.undo_history().len();
assert!(depth > 0, "the test needs an undoable edit");
let applied = a.synthetic_applied_batches;
let quickpunch = a.engine.session().edit.quickpunch;
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "z", "cmd": true}));
assert!(handle(&mut a, &ctx, &req).is_none());
assert!(gesture_pending(&a), "the key waits for the framework to run it");
let mut raw = raw_input(800.0, 600.0, 8192);
// A real, unrelated shortcut in the same pass must still be dispatched after the expired
// scripted batch is removed.
let command_shift = egui::Modifiers { command: true, shift: true, ..egui::Modifiers::NONE };
raw.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: command_shift });
raw.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: false, repeat: false, modifiers: command_shift });
a.raw_input_hook(&ctx, &mut raw);
assert!(a.synthetic_batch.is_some(), "the key batch waits for a UI pass");
// The deadline crosses before any pass ran the key.
// The deadline crosses after the hook handed the key to egui but before logic and widgets.
a.advance_test_clock(Duration::from_secs(16));
let _ = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
let mut out = ctx.run_ui(raw, |ui| {
a.logic(ui.ctx());
a.ui(ui);
});
out.textures_delta.clear();
let canceled = reply.try_recv().expect("one cancellation reply");
assert_eq!(canceled["ok"], false, "{canceled}");
assert!(!gesture_pending(&a));
assert!(a.synthetic_batch.is_none(), "the expired batch is dropped");
assert_eq!(a.synthetic_applied_batches, applied, "an expired batch is not delivered");
assert_eq!(a.engine.undo_history().len(), depth, "the expired key must not run its shortcut");
assert_eq!(a.engine.session().edit.quickpunch, !quickpunch, "a simultaneous host shortcut still runs");
assert!(!a.cancel_synthetic_keys);
assert!(
ctx.input(|i| !i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Z, .. }))),
"the expired key is gone from the pass, not left for widgets or end-of-pass shortcuts"
);
let _ = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
assert_eq!(a.engine.undo_history().len(), depth, "the expired key must not run its shortcut, now or later");
assert_eq!(a.engine.undo_history().len(), depth, "a later frame must not replay it");
// A fresh key after the timeout still works and runs exactly once.
// A fresh gesture after the timeout still works and runs exactly once.
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "z", "cmd": true}));
assert!(handle(&mut a, &ctx, &req).is_none());
deliver_gestures(&mut a, &ctx);
@@ -532,19 +538,6 @@ fn a_timed_out_scripted_key_does_not_run_and_the_next_key_works() {
assert_eq!(a.engine.undo_history().len(), depth - 1, "a completed key still undoes exactly once");
}
/// The framework takes Escape out of egui's event list; the key is still acknowledged.
#[test]
fn a_scripted_escape_is_acknowledged() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Escape"}));
assert!(handle(&mut a, &ctx, &req).is_none());
deliver_gestures(&mut a, &ctx);
assert_eq!(reply.try_recv().expect("an acknowledgement")["ok"], true);
}
/// Current timeline zoom, horizontal scroll and vertical scroll, compared before and after a gesture.
fn view(a: &SoundApp) -> (f64, i64, f32) {
let zoom = a.engine.session().edit.zoom;
@@ -580,7 +573,6 @@ fn host_line_wheel(dy: f32) -> egui::Event {
#[test]
fn a_timed_out_scripted_scroll_after_the_hook_does_not_scroll_or_keep_smoothing() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
// Make the track area overflow so a real wheel would actually move the view.
@@ -657,7 +649,6 @@ fn a_timed_out_scripted_scroll_after_the_hook_does_not_scroll_or_keep_smoothing(
#[test]
fn a_timed_out_scripted_zoom_after_the_hook_does_not_zoom_and_the_next_zoom_works_once() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let at = timeline_center(&a);
@@ -719,7 +710,6 @@ fn a_timed_out_scripted_zoom_after_the_hook_does_not_zoom_and_the_next_zoom_work
#[test]
fn a_fresh_identical_host_wheel_after_a_drawn_expiry_is_not_swallowed() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 20, "format": "stereo"})).unwrap();
@@ -759,7 +749,6 @@ fn a_fresh_identical_host_wheel_after_a_drawn_expiry_is_not_swallowed() {
#[test]
fn a_host_key_held_across_passes_survives_a_replayed_scroll_cancel() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 20, "format": "stereo"})).unwrap();
@@ -801,7 +790,6 @@ fn a_host_key_held_across_passes_survives_a_replayed_scroll_cancel() {
#[test]
fn an_expiry_in_a_discarded_pass_does_not_replay_host_events() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 1, "format": "stereo"})).unwrap();
@@ -854,7 +842,6 @@ fn an_expiry_in_a_discarded_pass_does_not_replay_host_events() {
#[test]
fn a_timed_out_track_drag_cancels_without_dropping_and_the_next_drag_works() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let before: Vec<_> = a.engine.session().tracks.iter().map(|track| track.id).collect();
@@ -895,7 +882,6 @@ fn a_timed_out_track_drag_cancels_without_dropping_and_the_next_drag_works() {
#[test]
fn scroll_reports_the_wheel_and_trackpad_sources_after_delivery() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let (req, reply) = ControlRequest::new("ui.scroll", json!({"x": 10.0, "y": 10.0, "dy": -30.0, "unit": "line", "steps": 2}));
assert!(handle(&mut a, &ctx, &req).is_none(), "the reply waits for delivery");
+1 -1
View File
@@ -221,7 +221,7 @@ fn contributors_toolbar(ui: &mut egui::Ui, v: &mut View) {
}
ui.separator();
let sort = ui.label(crate::localization::text("Sort"));
let combo = egui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, crate::localization::text(k.label().0)).clicked() {
v.key = k;
+10 -13
View File
@@ -342,8 +342,7 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
/// The path prompt's form; the command to run once it is confirmed.
fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut String, key: &str, enter: bool) -> Option<(String, Value)> {
let label = if key == "dir" { crate::localization::text("Folder path") } else { crate::localization::text("File path") };
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), label);
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("Path"));
let mut picked = None;
// Import Audio picks several files at once; every other open dialog takes one.
let multi = cmd == "file.import_audio" && app.services.pick_open_many.is_some();
@@ -445,9 +444,7 @@ fn strip_silence_form(
mode = Some("separate");
}
// Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked.
// The button is its own string ("Strip Silence"), not the Channel Strip plug-in's
// short name "Strip", so translations can give them different words (#1610).
if buttons(ui, "Strip Silence", enter) && mode.is_none() {
if buttons(ui, "Strip", enter) && mode.is_none() {
mode = Some("strip");
}
// Enter on a focused Rename… also presses Strip, so Rename… goes first.
@@ -515,8 +512,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
// button only when no widget has the keyboard focus or a text field has it. A held Enter's repeats do not press it.
let fresh_enter =
|i: &egui::InputState| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }));
let enter = !first_frame && ctx.input(fresh_enter) && (!crate::framework::widget_has_keyboard(ctx) || ctx.text_edit_focused());
let esc = crate::framework::escape_pressed(ctx);
let enter = !first_frame && ctx.input(fresh_enter) && (ctx.memory(|m| m.focused().is_none()) || ctx.text_edit_focused());
let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape));
egui::Window::new(egui::RichText::new(crate::localization::text(&title)).font(bold(13.0)))
.id(egui::Id::unique(&title))
.collapsible(false)
@@ -539,7 +536,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
ui.label(crate::localization::text("Name"));
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
});
egui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
for r in soundcraft_time::SampleRate::COMMON {
ui.selectable_value(sample_rate, r, format!("{r} Hz"));
}
@@ -555,12 +552,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::Bounce { path, format, bit_depth, normalize, dither } => {
bounce_file_row(app, ui, path, format);
ui.horizontal(|ui| {
egui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
for &f in EncodeFormat::ALL {
ui.selectable_value(format, f, f.container().name());
}
});
egui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
for b in ["16", "24", "32f"] {
ui.selectable_value(bit_depth, b.to_string(), crate::localized_format!("{b}-bit", b = b));
}
@@ -704,12 +701,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
}
Dialog::Session { frame_rate, bit_depth } => {
egui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
for r in soundcraft_time::FrameRate::ALL {
ui.selectable_value(frame_rate, r.label().to_string(), crate::localization::text(r.label()));
}
});
egui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
for b in ["16", "24", "32f"] {
ui.selectable_value(bit_depth, b.to_string(), crate::localization::text(b));
}
@@ -722,7 +719,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let s = app.engine.session();
ui.horizontal(|ui| {
let count_label = ui.radio_value(by, LoopBy::Count, crate::localization::text("Number of Loops"));
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=1000)).labelled_by(count_label.id);
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=512)).labelled_by(count_label.id);
});
ui.horizontal(|ui| {
let length_label = ui.radio_value(by, LoopBy::Length, crate::localization::text("Loop Length"));
+4 -4
View File
@@ -183,7 +183,7 @@ impl NewTracks {
ui.label(crate::localization::text("new"));
let format = if has_format(&row.kind) {
Some(
egui::ComboBox::from_id_salt("nt_fmt")
craft_ui::ComboBox::from_id_salt("nt_fmt")
.width(widths.format)
.selected_text(crate::localization::text(&row.format))
.show_ui(ui, |ui| {
@@ -198,7 +198,7 @@ impl NewTracks {
ui.allocate_space(vec2(widths.format, ui.spacing().interact_size.y));
None
};
let kind = egui::ComboBox::from_id_salt("nt_kind")
let kind = craft_ui::ComboBox::from_id_salt("nt_kind")
.width(widths.kind)
.selected_text(crate::localization::text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label())))
.show_ui(ui, |ui| {
@@ -213,7 +213,7 @@ impl NewTracks {
let timebase = if has_timebase(&row.kind) {
ui.label(crate::localization::text("in"));
Some(
egui::ComboBox::from_id_salt("nt_tb")
craft_ui::ComboBox::from_id_salt("nt_tb")
.width(widths.timebase)
.selected_text(crate::localization::text(if row.timebase == "ticks" { "Ticks" } else { "Samples" }))
.show_ui(ui, |ui| {
@@ -360,7 +360,7 @@ mod tests {
fn harness() -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
assert!(app.dialogs.open_for_command(&app.engine, "track.new"));
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
app.ui(ui);
+14 -17
View File
@@ -162,14 +162,13 @@ fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) {
.open(&mut open)
.default_size(vec2(360.0, 200.0))
.show(ctx, |ui| {
egui::ComboBox::from_label(crate::localization::text("Curve")).selected_text(crate::localization::text(&app.ops.tempo_curve)).show_ui(
ui,
|ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Curve"))
.selected_text(crate::localization::text(&app.ops.tempo_curve))
.show_ui(ui, |ui| {
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), crate::localization::text(c));
}
},
);
});
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix(crate::localization::text("start bpm ")))
.accessible_name(crate::localization::text("Start tempo (BPM)"));
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix(crate::localization::text("end bpm ")))
@@ -201,21 +200,20 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) {
.open(&mut open)
.default_size(vec2(360.0, 200.0))
.show(ctx, |ui| {
egui::ComboBox::from_label(crate::localization::text("Operation")).selected_text(crate::localization::text(&app.ops.time_op)).show_ui(
ui,
|ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
.selected_text(crate::localization::text(&app.ops.time_op))
.show_ui(ui, |ui| {
for c in ["insert", "cut", "change meter", "move song start"] {
ui.selectable_value(&mut app.ops.time_op, c.to_string(), crate::localization::text(c));
}
},
);
});
match app.ops.time_op.as_str() {
"change meter" => {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64))
.accessible_name(crate::localization::text("Meter numerator"));
ui.label(crate::localization::text("/"));
let den = egui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
for d in [2u32, 4, 8, 16] {
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
}
@@ -255,17 +253,16 @@ fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) {
.open(&mut open)
.default_size(vec2(360.0, 220.0))
.show(ctx, |ui| {
egui::ComboBox::from_label(crate::localization::text("Operation")).selected_text(crate::localization::text(&app.ops.midi_op)).show_ui(
ui,
|ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
.selected_text(crate::localization::text(&app.ops.midi_op))
.show_ui(ui, |ui| {
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), crate::localization::text(c));
}
},
);
});
match app.ops.midi_op.as_str() {
"quantize" => {
egui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
}
-15
View File
@@ -159,19 +159,4 @@ mod tests {
let ui: crate::UiState = serde_json::from_str("{}").unwrap();
assert!(ui.recent_sessions.is_empty());
}
/// A saved state with more entries than the menu keeps (a hand-edited `ui.json`) is cut to
/// the newest [`MAX_RECENT`] on the first frame, and a list within the limit is left alone.
/// Cutting it tells the host to save, so the file is corrected without waiting for a clean exit.
#[test]
fn an_oversized_saved_list_is_capped_on_the_first_frame() {
let paths = |count: usize| (0..count).map(|i| format!("{i}.scraft")).collect::<Vec<_>>();
for (saved, kept) in [(1000, MAX_RECENT), (MAX_RECENT + 1, MAX_RECENT), (MAX_RECENT, MAX_RECENT), (3, 3), (0, 0)] {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.ui = serde_json::from_value(json!({"recent_sessions": paths(saved)})).unwrap();
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut SoundApp| app.logic(&ui.ctx().clone()), app);
assert_eq!(harness.state().ui.recent_sessions, paths(kept), "{saved} saved entries");
assert_eq!(harness.state_mut().take_recent_changed(), saved > kept, "{saved} saved entries: save only when entries were cut");
}
}
}
+6 -5
View File
@@ -155,11 +155,12 @@ fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples)
pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
egui::Grid::new("spot").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
let scale = ui.label(crate::localization::text("Time Scale"));
let time_scale = egui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
for f in TimeFormat::ALL {
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
}
});
let time_scale =
craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
for f in TimeFormat::ALL {
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
}
});
time_scale.response.labelled_by(scale.id);
ui.end_row();
for (i, label) in FIELDS.into_iter().enumerate() {
+175 -448
View File
@@ -1,21 +1,11 @@
//! Application panel identities and persistence around craft-ui's `DockArea`. Document contents remain owned by
//! their existing view implementations.
//!
//! `UiState::docking` and `UiState::mix_docking` are the saved workspaces and the source of truth. The dock shows an
//! `Arc` of each ([`LiveDocks`]), kept while the saved workspace is unchanged; every change the dock reports goes
//! through [`command_for`] like a `ui.dock` command.
//! Application panel identities and persistence around the shared docking renderer.
//! Document contents remain owned by their existing view implementations.
use std::sync::Arc;
use craft_behavior::DockSide;
use craft_behavior::dock::{
Action, Column, DockEdge, DockError, DockPlacement, Floating, Group, Layout, Location, Node, Permissions, SplitSize, Target,
use craft_ui::docking::{
Action, Column, DockArea, DockCommand, DockError, DockOperation, DockStyle, FloatSpace, Floating, Group, Layout, Location, Node, PanelLimits,
Permissions, Placement, Side, Target, UiDock, Zone, ZoneName,
};
use craft_behavior::flow::Axis;
use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use egui::{Rect, pos2, vec2};
use craft_ui::layout::{SplitAxis, SplitSize};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -52,41 +42,48 @@ pub const CLIPS_WIDTH: f32 = 230.0;
pub const MIDI_HEIGHT: f32 = 320.0;
/// An Edit or Mix panel arrangement, saved with the UI preferences.
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
pub type Workspace = craft_ui::docking::Workspace<Panel>;
/// The height the MIDI editor's tab adds above its body in the default layout.
const MIDI_TAB_HEIGHT: f32 = 28.0;
const MIDI_TAB_HEIGHT: f32 = 26.0;
/// The document view stays docked and open, and panels open in splits beside it.
fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Canvas { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
if *panel == Panel::Canvas { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
}
fn tabs(panel: Panel) -> Node<Panel> {
Node::tabs(vec![panel], 0)
Node::Tabs { panels: vec![panel], active: 0 }
}
/// The id the Edit or Mix dock area is drawn under.
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
}
/// The dock area that draws the Edit or Mix workspace.
pub fn area_id(window: crate::MainWindow) -> egui::Id {
egui::Id::unique(("soundcraft-docking", window == crate::MainWindow::Edit))
}
/// A dock on `side` with one column holding `panel`.
fn dock(side: DockEdge, panel: Panel, width: f32) -> Node<Panel> {
Node::dock(side, vec![Column::new(vec![Group::new(vec![panel], 0)]).with_width(width)])
fn area(edit: bool) -> egui::Id {
area_id(if edit { crate::MainWindow::Edit } else { crate::MainWindow::Mix })
}
const MEMORY_RECT: Rect = Rect::from_min_max(pos2(160.0, 120.0), pos2(640.0, 400.0));
const HISTORY_RECT: Rect = Rect::from_min_max(pos2(680.0, 120.0), pos2(940.0, 420.0));
/// A dock on `side` with one column holding `panel`.
fn dock(side: Side, panel: Panel, width: f32) -> Node<Panel> {
Node::Dock { side, columns: vec![Column::new(vec![Group::new(vec![panel], 0)], width)] }
}
const MEMORY_RECT: [f32; 4] = [160.0, 120.0, 480.0, 280.0];
const HISTORY_RECT: [f32; 4] = [680.0, 120.0, 260.0, 300.0];
/// The floating windows both windows start with. Fixed ids: the default is rebuilt every frame
/// and must stay the same windows.
fn default_floating() -> Vec<Floating<Panel>> {
vec![Floating::single(1, vec![Panel::Memory], 0, MEMORY_RECT), Floating::single(2, vec![Panel::History], 0, HISTORY_RECT)]
vec![Floating::single(vec![Panel::Memory], 0, MEMORY_RECT).with_id(1), Floating::single(vec![Panel::History], 0, HISTORY_RECT).with_id(2)]
}
/// Where a panel that floats in the default layouts floats.
fn default_float(panel: Panel) -> Option<Rect> {
fn default_float(panel: Panel) -> Option<[f32; 4]> {
match panel {
Panel::Memory => Some(MEMORY_RECT),
Panel::History => Some(HISTORY_RECT),
@@ -95,10 +92,10 @@ fn default_float(panel: Panel) -> Option<Rect> {
}
/// The dock side and column width a panel opens in when it has no recorded place.
fn default_dock(panel: Panel) -> Option<(DockEdge, f32)> {
fn default_dock(panel: Panel) -> Option<(Side, f32)> {
match panel {
Panel::Tracks => Some((DockEdge::Start, TRACKS_WIDTH)),
Panel::Clips => Some((DockEdge::End, CLIPS_WIDTH)),
Panel::Tracks => Some((Side::Start, TRACKS_WIDTH)),
Panel::Clips => Some((Side::End, CLIPS_WIDTH)),
_ => None,
}
}
@@ -106,21 +103,30 @@ fn default_dock(panel: Panel) -> Option<(DockEdge, f32)> {
/// The Edit window's built-in arrangement: Tracks and Groups in a full-height start dock,
/// Clips in a full-height end dock, and the MIDI editor under the session view between them.
pub fn edit_default() -> Workspace {
let session = Node::split(Axis::Y, SplitSize::FixedSecond(MIDI_HEIGHT + MIDI_TAB_HEIGHT), tabs(Panel::Canvas), tabs(Panel::Midi));
let root = Node::split(
Axis::X,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH),
Node::split(Axis::X, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(DockEdge::End, Panel::Clips, CLIPS_WIDTH)),
);
Workspace::new(Layout::new(Some(root), default_floating()))
let session = split(SplitAxis::Vertical, SplitSize::FixedSecond(MIDI_HEIGHT + MIDI_TAB_HEIGHT), tabs(Panel::Canvas), tabs(Panel::Midi));
Workspace::new(Layout {
root: Some(split(
SplitAxis::Horizontal,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
split(SplitAxis::Horizontal, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(Side::End, Panel::Clips, CLIPS_WIDTH)),
)),
floating: default_floating(),
})
}
/// The Mix window's built-in arrangement: Tracks and Groups in a start dock beside the mixer.
/// The timeline-only Clips and MIDI panels stay in Edit.
pub fn mix_default() -> Workspace {
let root = Node::split(Axis::X, SplitSize::FixedFirst(TRACKS_WIDTH), dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH), tabs(Panel::Canvas));
Workspace::new(Layout::new(Some(root), default_floating()))
Workspace::new(Layout {
root: Some(split(
SplitAxis::Horizontal,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
tabs(Panel::Canvas),
)),
floating: default_floating(),
})
}
/// The version of the saved panel layouts, kept in [`crate::UiState::docking_version`]. Version 1
@@ -148,7 +154,7 @@ fn canvas_placement(node: &Node<Panel>) -> Option<Result<(), &'static str>> {
Node::Tabs { panels, .. } if panels.contains(&Panel::Canvas) => {
Some(if panels.len() == 1 { Ok(()) } else { Err("The document view cannot share a tab group") })
}
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => Some(Err("The document view cannot be collapsed")),
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => Some(Err("The document view cannot be collapsed")),
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Canvas)) => {
Some(Err("The document view cannot join a dock column"))
}
@@ -156,24 +162,23 @@ fn canvas_placement(node: &Node<Panel>) -> Option<Result<(), &'static str>> {
}
}
/// Check a workspace against craft-behavior's rules and SoundCraft's own: saved settings cannot
/// Check a workspace against craft-ui's rules and SoundCraft's own: saved settings cannot
/// float, hide, collapse or share the protected document view.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = workspace.layout();
if !layout.contains(&Panel::Canvas) || workspace.hidden().len() > Panel::ALL.len() {
let layout = &workspace.layout;
if !layout.contains(&Panel::Canvas) || workspace.hidden.len() > Panel::ALL.len() {
return Err("The panel layout must contain its document view and bounded hidden panels".into());
}
if layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
return Err("The document view cannot float".into());
}
layout.root.as_ref().and_then(canvas_placement).unwrap_or(Err("The document view cannot float"))?;
for (panel, location) in workspace.hidden() {
for (panel, location) in &workspace.hidden {
if *panel == Panel::Canvas {
return Err("A hidden panel has an invalid or duplicate identity".into());
}
if location.anchor == Some(Panel::Canvas) && matches!(location.placement, DockPlacement::Tab { .. } | DockPlacement::Split(DockSide::Center))
{
if location.anchor == Some(Panel::Canvas) && matches!(location.placement, Placement::Tab { .. } | Placement::Split(Zone::Center)) {
return Err("A hidden panel cannot restore over the document view".into());
}
let mut probe = layout.clone();
@@ -189,7 +194,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
/// [`validate`] plus the Mix window's rule: Clips and MIDI stay in Edit.
pub fn validate_mix(workspace: &Workspace) -> Result<(), String> {
validate(workspace)?;
if workspace.layout().contains(&Panel::Clips) || workspace.layout().contains(&Panel::Midi) {
if workspace.layout.contains(&Panel::Clips) || workspace.layout.contains(&Panel::Midi) {
return Err("Clips and MIDI panels belong to the Edit window".into());
}
Ok(())
@@ -206,17 +211,17 @@ fn checked(workspace: &mut Workspace, change: impl FnOnce(&mut Workspace) -> Res
}
fn apply(workspace: &mut Workspace, action: Action<Panel>) -> Result<(), String> {
checked(workspace, |next| next.apply(action, false, permissions).map(drop))
checked(workspace, |next| next.apply(action, permissions).map(drop))
}
/// Whether [`Workspace::set_visible`] can actually put `panel` back at its recorded place.
/// It follows the recorded location and the chain of hidden anchors; when none of that
/// restores, craft-behavior falls back to an unanchored open, which chooses a dock group or
/// right edge instead of reporting the missing anchor. Probe each chain location with the
/// public [`Layout::restore`] on a clone, so a deleted anchor is recognized before calling in;
/// craft-behavior still performs the restore and rewrites the chain itself.
/// restores, craft-ui falls back to an unanchored open, which since craft-ui 650b1c0b chooses
/// a dock group or right edge instead of reporting the missing anchor. Probe each chain
/// location with the public [`Layout::restore`] on a clone, so a deleted anchor is recognized
/// before calling in; craft-ui still performs the restore and rewrites the chain itself.
fn restores(workspace: &Workspace, panel: Panel) -> bool {
let recorded = |p: &Panel| workspace.hidden().iter().find(|(q, _)| q == p).map(|(_, location)| location.clone());
let recorded = |p: &Panel| workspace.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location.clone());
let mut chain: Vec<Location<Panel>> = Vec::new();
let mut seen = vec![panel];
let mut current = panel;
@@ -229,14 +234,13 @@ fn restores(workspace: &Workspace, panel: Panel) -> bool {
}
// Like the chain itself, the panel's own group/column state applies to every attempt.
let group = chain.first().and_then(|location| location.group.clone());
// Revisit this eligibility probe when updating the pinned craft-behavior restore algorithm.
// Revisit this eligibility probe when updating the pinned craft-ui restore algorithm.
chain
.iter()
.rev()
.find_map(|location| {
let mut location = location.clone();
location.group = group.clone().or(location.group);
let mut probe = workspace.layout().clone();
let location = Location { group: group.clone().or_else(|| location.group.clone()), ..location.clone() };
let mut probe = workspace.layout.clone();
match probe.restore(panel, &location) {
Err(DockError::MissingTarget) => None,
result => Some(result.is_ok()),
@@ -246,10 +250,10 @@ fn restores(workspace: &Workspace, panel: Panel) -> bool {
}
/// The first panel of the dock on `side`, when that dock is shown.
fn dock_panel(node: &Node<Panel>, side: DockEdge) -> Option<Panel> {
fn dock_panel(node: &Node<Panel>, side: Side) -> Option<Panel> {
match node {
Node::Split { first, second, .. } => dock_panel(first, side).or_else(|| dock_panel(second, side)),
Node::Dock { side: found, columns, .. } if *found == side => {
Node::Dock { side: found, columns } if *found == side => {
columns.iter().flat_map(|column| &column.groups).find_map(|group| group.panels.first().copied())
}
_ => None,
@@ -260,187 +264,47 @@ fn dock_panel(node: &Node<Panel>, side: DockEdge) -> Option<Panel> {
/// in their docks (joining the dock's first group when the dock is shown, else making the dock
/// again), the MIDI editor under the session view and the others floating.
fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result<(), String> {
if workspace.layout().contains(&panel) == visible {
if workspace.layout.contains(&panel) == visible {
return Ok(());
}
checked(workspace, |next| {
if !visible {
return next.apply(Action::close(panel), false, permissions).map(drop);
return next.apply(Action::Close { panel }, permissions).map(drop);
}
let dock = default_dock(panel);
if let Some((side, _)) = dock
&& let Some(anchor) = next.layout().root.as_ref().and_then(|root| dock_panel(root, side))
&& let Some(anchor) = next.layout.root.as_ref().and_then(|root| dock_panel(root, side))
{
return next.set_visible(panel, true, Some(anchor), false, permissions);
return next.set_visible(panel, true, Some(anchor), permissions);
}
// Without an anchor, craft-behavior would open a panel it has no record of, or whose record no
// Without an anchor, craft-ui would open a panel it has no record of, or whose record no
// longer restores, in some other panel's group, so the default place is applied here.
if next.hidden().iter().any(|(hidden, _)| *hidden == panel)
&& restores(next, panel)
&& next.set_visible(panel, true, None, false, permissions).is_ok()
if next.hidden.iter().any(|(hidden, _)| *hidden == panel) && restores(next, panel) && next.set_visible(panel, true, None, permissions).is_ok()
{
return Ok(());
}
let open = Action::open(panel, None);
let open = Action::Open { panel, anchor: None };
let actions = match (dock, default_float(panel)) {
(Some((side, width)), _) => vec![open, Action::move_panel(panel, Target::new_dock(side)), Action::resize_column(panel, width)],
(None, Some(rect)) => vec![open, Action::float(panel, rect)],
(None, None) => vec![Action::open_at(panel, Panel::Canvas, DockPlacement::Split(DockSide::Bottom))],
(Some((side, width)), _) => vec![open, Action::MovePanel { panel, to: Target::NewDock { side } }, Action::ResizeColumn { panel, width }],
(None, Some(rect)) => vec![open, Action::Float { panel, rect }],
(None, None) => vec![Action::OpenAt { panel, anchor: Panel::Canvas, placement: Placement::Split(Zone::Bottom) }],
};
next.apply_all(actions, false, permissions)?;
next.apply(Action::activate(panel), false, permissions).map(drop)
next.apply_all(actions, permissions)?;
next.apply(Action::Activate { panel }, permissions).map(drop)
})
}
/// A drop zone by name, as `ui.dock` writes it. PascalCase names also parse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ZoneName {
Tab,
#[serde(alias = "Center")]
Center,
#[serde(alias = "Left")]
Left,
#[serde(alias = "Right")]
Right,
#[serde(alias = "Top")]
Top,
#[serde(alias = "Bottom")]
Bottom,
Above,
Below,
}
/// A present field, `null` included: `Some(None)` for `null`, `None` when absent.
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
/// A required field that may be `null`.
fn required<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> {
T::deserialize(deserializer)
}
/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone`
/// (default `center`) and `before`, which only applies to a center move. Rects are `[x, y, width, height]`.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "operation", rename_all = "camelCase")]
enum DockOperation {
/// Show a panel at its last location and select it.
Open {
panel: Panel,
},
Close {
panel: Panel,
},
Activate {
panel: Panel,
},
Float {
panel: Panel,
rect: [f32; 4],
},
MoveFloating {
panel: Panel,
rect: [f32; 4],
},
Move {
panel: Panel,
target: Panel,
#[serde(default)]
zone: Option<ZoneName>,
#[serde(default, deserialize_with = "present")]
before: Option<Option<Panel>>,
},
SetStackOpen {
panel: Panel,
open: bool,
},
/// `height` is required; `null` clears it.
ResizeStack {
panel: Panel,
#[serde(deserialize_with = "required")]
height: Option<f32>,
},
ResizeSplit {
path: Vec<bool>,
size: SplitSize,
},
}
/// What `ui.dock` and `ui.dock.reset` ask of the front window's workspace, and the changes the dock reports.
#[derive(Clone, Debug, PartialEq)]
enum DockCommand {
/// A raw layout action: `ui.dock` with `{action}`, or a change made in the dock.
Layout(Action<Panel>),
/// `ui.dock` with `{operation, …}`.
Operation(DockOperation),
/// `ui.dock.reset`: the built-in arrangement.
Reset,
}
/// `[x, y, width, height]` as a rect.
fn rect_of([x, y, width, height]: [f32; 4]) -> Rect {
Rect::from_min_size(pos2(x, y), vec2(width, height))
}
/// Where a `move` puts the panel relative to `anchor`: `zone` (default `center`) and `before`,
/// with side zones mapped onto the anchor's container by [`DockPlacement::for_zone`].
fn placement(
layout: &Layout<Panel>,
anchor: &Panel,
zone: Option<ZoneName>,
before: Option<Option<Panel>>,
) -> Result<DockPlacement<Panel>, DockError> {
let side = |side| DockPlacement::for_zone(layout, anchor, side);
Ok(match (zone.unwrap_or(ZoneName::Center), before) {
(ZoneName::Tab | ZoneName::Center, Some(before)) => DockPlacement::tab(before),
(ZoneName::Tab, None) => DockPlacement::tab(None),
(ZoneName::Center, None) => DockPlacement::Split(DockSide::Center),
(_, Some(_)) => return Err(DockError::InvalidPlacement),
(ZoneName::Left, None) => side(DockSide::Start)?,
(ZoneName::Right, None) => side(DockSide::End)?,
(ZoneName::Top, None) => side(DockSide::Top)?,
(ZoneName::Bottom, None) => side(DockSide::Bottom)?,
(ZoneName::Above, None) => DockPlacement::group(false, None),
(ZoneName::Below, None) => DockPlacement::group(true, None),
})
}
impl DockOperation {
/// The layout action this operation makes on `layout`. A panel that is not shown is
/// [`DockError::MissingPanel`] for Open and Activate, which show it first ([`run`]).
fn action(&self, layout: &Layout<Panel>) -> Result<Action<Panel>, DockError> {
Ok(match self {
Self::Open { panel } | Self::Activate { panel } => {
if !layout.contains(panel) {
return Err(DockError::MissingPanel);
}
Action::activate(*panel)
}
Self::Close { panel } => Action::close(*panel),
Self::Float { panel, rect } => Action::float(*panel, rect_of(*rect)),
Self::MoveFloating { panel, rect } => Action::move_floating(*panel, rect_of(*rect)),
Self::Move { panel, target, zone, before } => Action::move_beside(*panel, *target, placement(layout, target, *zone, *before)?),
Self::SetStackOpen { panel, open } => Action::set_stack_open(*panel, *open),
Self::ResizeStack { panel, height } => Action::resize_stack(*panel, *height),
Self::ResizeSplit { path, size } => Action::resize_split(path.clone(), *size),
})
}
}
/// Run a docking command. A hidden panel that is opened or activated comes back with
/// Run a shared docking command. A hidden panel that is opened or activated comes back with
/// [`set_visible`], so it gets SoundCraft's default place when it has no recorded one.
fn run(workspace: &mut Workspace, command: &DockCommand) -> Result<(), String> {
let action = match command {
DockCommand::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel }) if !workspace.layout().contains(panel) => {
return set_visible(workspace, *panel, true);
}
DockCommand::Operation(operation) => operation.action(workspace.layout()).map_err(|error| error.to_string())?,
DockCommand::Layout(action) => action.clone(),
DockCommand::Reset => return Err("Reset is applied by the window, not the layout".into()),
};
apply(workspace, action)
fn run(workspace: &mut Workspace, command: &DockCommand<Panel>) -> Result<(), String> {
if let DockCommand::Activate { panel } | DockCommand::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) =
command
&& !workspace.layout.contains(panel)
{
return set_visible(workspace, *panel, true);
}
// Only `window.panel.float` reads the float space, and SoundCraft does not register it.
checked(workspace, |next| command.apply(next, false, &FloatSpace::new(egui::Rect::NOTHING), permissions).map(drop))
}
fn sync(workspace: &mut Workspace, app: &crate::SoundApp, edit: bool) -> Result<(), String> {
@@ -455,13 +319,12 @@ fn sync(workspace: &mut Workspace, app: &crate::SoundApp, edit: bool) -> Result<
}
fn publish_visibility(app: &mut crate::SoundApp, workspace: &Workspace, edit: bool) {
let layout = workspace.layout();
app.ui.show_tracks_list = layout.contains(&Panel::Tracks);
app.ui.show_memory_locations = layout.contains(&Panel::Memory);
app.ui.show_undo_history = layout.contains(&Panel::History);
app.ui.show_tracks_list = workspace.layout.contains(&Panel::Tracks);
app.ui.show_memory_locations = workspace.layout.contains(&Panel::Memory);
app.ui.show_undo_history = workspace.layout.contains(&Panel::History);
if edit {
app.ui.show_clip_list = layout.contains(&Panel::Clips);
app.ui.show_midi_editor = layout.contains(&Panel::Midi);
app.ui.show_clip_list = workspace.layout.contains(&Panel::Clips);
app.ui.show_midi_editor = workspace.layout.contains(&Panel::Midi);
}
}
@@ -473,8 +336,9 @@ fn store(app: &mut crate::SoundApp, workspace: Workspace, edit: bool) {
}
}
/// A `ui.dock` operation. Panels and zones are checked first so an error names the field.
fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation, String> {
/// A `ui.dock` operation. Panels and zones are checked first so an error names the field;
/// parsed through the untagged [`UiDock`], every mistake reads "did not match any variant".
fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation<Panel>, String> {
let name = fields.get("operation").ok_or("operation is required")?.as_str().ok_or("operation must be a string")?;
if name != "resizeSplit" && !fields.contains_key("panel") {
return Err("panel is required".into());
@@ -493,48 +357,52 @@ fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation, S
serde_json::from_value(Value::Object(fields.clone())).map_err(|error| error.to_string())
}
/// `ui.dock` and `ui.dock.reset`, applied to the front window's workspace.
/// `ui.dock` and `ui.dock.reset`: the shared [`DockCommand`] vocabulary, applied to the
/// front window's workspace.
pub fn command(app: &mut crate::SoundApp, id: &str, params: &Value) -> Result<Value, String> {
let edit = app.ui.window == crate::MainWindow::Edit;
if !edit && ["panel", "target"].iter().any(|field| matches!(params.get(*field).and_then(Value::as_str), Some("clips" | "midi"))) {
return Err("Clips and MIDI panels belong to the Edit window".into());
}
let fields = match params {
let mut fields = match params {
Value::Object(fields) => fields.clone(),
Value::Null => serde_json::Map::new(),
_ => return Err("Docking params must be an object".into()),
};
let command = match (id, fields.get("action")) {
("ui.dock.reset", _) => DockCommand::Reset,
(_, Some(action)) => DockCommand::Layout(serde_json::from_value(action.clone()).map_err(|error| error.to_string())?),
(_, None) => DockCommand::Operation(operation(&fields)?),
let command = if id == "ui.dock" && !fields.contains_key("action") {
DockCommand::UiDock(UiDock::Operation(operation(&fields)?))
} else {
fields.insert("command".into(), json!(id));
serde_json::from_value(Value::Object(fields)).map_err(|error| error.to_string())?
};
let previous = if edit { app.ui.docking.clone() } else { app.ui.mix_docking.clone() };
let result = command_for(app, &command, edit)?;
let next = if edit { &app.ui.docking } else { &app.ui.mix_docking };
cancel_replaced_workspace(app, &previous, next);
cancel_replaced_workspace(app, &previous, next, edit);
Ok(result)
}
/// Ends a running panel drag when the workspace it started on is replaced or changed by something else
/// than the dock.
fn cancel_replaced_workspace(app: &crate::SoundApp, previous: &Workspace, next: &Workspace) {
fn cancel_replaced_workspace(app: &crate::SoundApp, previous: &Workspace, next: &Workspace, edit: bool) {
if previous != next
&& let Some(ctx) = &app.docking_context
{
craft_ui::runtime::drag::cancel(ctx, craft_behavior::CancelReason::HostChanged);
craft_ui::docking::cancel_drag::<Panel>(ctx, area(edit));
}
}
/// Restoring complete preferences/configurations uses the same ownership boundary as commands.
pub(crate) fn cancel_replaced_state(app: &crate::SoundApp, next: &crate::UiState) {
cancel_replaced_workspace(app, &app.ui.docking, &next.docking);
cancel_replaced_workspace(app, &app.ui.mix_docking, &next.mix_docking);
cancel_replaced_workspace(app, &app.ui.docking, &next.docking, true);
cancel_replaced_workspace(app, &app.ui.mix_docking, &next.mix_docking, false);
}
fn command_for(app: &mut crate::SoundApp, command: &DockCommand, edit: bool) -> Result<Value, String> {
fn command_for(app: &mut crate::SoundApp, command: &DockCommand<Panel>, edit: bool) -> Result<Value, String> {
let mut workspace = if edit { app.ui.docking.clone() } else { app.ui.mix_docking.clone() };
if *command == DockCommand::Reset {
if command.is_app_owned() {
// Reset is the only application-owned command SoundCraft registers.
if !matches!(command, DockCommand::ResetWorkspace {}) {
return Err("Named panel workspaces are not supported".into());
}
workspace = if edit { edit_default() } else { mix_default() };
sync(&mut workspace, app, edit)?;
} else {
@@ -563,189 +431,22 @@ pub(crate) fn arrange(app: &mut crate::SoundApp) -> Result<(), String> {
validate_mix(&workspace)?;
}
let previous = workspace.clone();
let floating: Vec<_> =
workspace.layout().floating.iter().filter_map(|window| window.panels().next().map(|panel| (*panel, window.rect))).collect();
for (index, (panel, rect)) in floating.into_iter().enumerate() {
let at = pos2(32.0 + index as f32 * 28.0, 80.0 + index as f32 * 28.0);
apply(&mut workspace, Action::move_floating(panel, Rect::from_min_size(at, rect.size())))?;
let floating: Vec<_> = workspace.layout.floating.iter().filter_map(|window| window.panels().next().map(|panel| (*panel, window.rect))).collect();
for (index, (panel, mut rect)) in floating.into_iter().enumerate() {
rect[0] = 32.0 + index as f32 * 28.0;
rect[1] = 80.0 + index as f32 * 28.0;
apply(&mut workspace, Action::MoveFloating { panel, rect })?;
}
cancel_replaced_workspace(app, &previous, &workspace);
cancel_replaced_workspace(app, &previous, &workspace, edit);
store(app, workspace, edit);
Ok(())
}
/// The workspaces the Edit and Mix docks show, the panels' specs and the session views' keyboard focus.
#[derive(Default)]
pub(crate) struct LiveDocks {
edit: Option<Arc<Workspace>>,
mix: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
edit_focus: ViewFocus,
mix_focus: ViewFocus,
}
impl LiveDocks {
/// The `Arc` the dock shows for `workspace`: the last one while its arrangement is the same, so an idle pass
/// keeps the workspace's revision and the dock reads no spec.
fn shown(&mut self, edit: bool, workspace: &Workspace) -> Arc<Workspace> {
let slot = if edit { &mut self.edit } else { &mut self.mix };
if let Some(shown) = slot.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
*slot = Some(Arc::clone(&shown));
shown
}
}
/// What the dock reads of the panels: their names in the interface language.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
struct DockSpecs {
/// The tab names, in [`Panel::ALL`] order.
labels: Vec<String>,
}
impl PanelSpecs<Panel> for DockSpecs {
fn spec(&self, panel: &Panel) -> PanelSpec {
let label = Panel::ALL.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
// Every panel is SoundCraft's own egui code: the dock runs it with the window's style.
let spec = PanelSpec::new(label).limits(panel_limits(panel)).host_body();
if *panel == Panel::Canvas { spec.canvas() } else { spec }
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// Reads the panel names in the interface language, moving the specs' revision only when one changed.
fn refresh_specs(app: &mut crate::SoundApp) {
let labels: Vec<String> = Panel::ALL.iter().map(|panel| crate::localization::text(panel.label()).to_owned()).collect();
if app.docks.specs.labels != labels {
app.docks.specs.labels = labels;
}
}
/// What a session view knows of its keyboard focus from the pass that drew it last.
#[derive(Default)]
struct ViewFocus {
/// That pass's number and the document the view showed (`SoundApp::doc_epoch`).
shown: Option<(u64, u64)>,
/// The view opened or was pressed and has yet to ask for the focus.
wanted: bool,
/// The view had the focus, and no other widget has taken it.
returns: bool,
/// An overlay ([`crate::framework::overlay_open`]) was up.
overlay: bool,
/// The view kept Tab.
kept_tab: bool,
}
impl LiveDocks {
fn view_focus(&mut self, edit: bool) -> &mut ViewFocus {
if edit { &mut self.edit_focus } else { &mut self.mix_focus }
}
}
/// Gives the session view, drawn in `rect`, the keyboard focus on a press in it, when it opens or shows another
/// document, and when its focus went nowhere (a dialog that closed). It waits for
/// a modal dialog, menu or popup to close. A press leaves the focus with the text field it landed on; a view that opens
/// leaves it with any text field and with a widget of another layer. Called after the view's widgets, so that the field
/// under a press has taken the focus already.
fn focus_session_view(app: &mut crate::SoundApp, ui: &egui::Ui, edit: bool, rect: Rect) {
let ctx = ui.ctx();
let id = crate::framework::session_view_id(edit);
let focused = ctx.memory(|memory| memory.focused());
let pressed = ui.rect_contains_pointer(rect) && ui.input(|input| input.pointer.any_pressed());
let overlay = crate::framework::overlay_open(app, ctx);
let (pass, document) = (ctx.cumulative_pass_nr(), app.doc_epoch);
let state = app.docks.view_focus(edit);
let stayed = state.shown.is_some_and(|(last, shown)| shown == document && (last == pass || last + 1 == pass));
state.shown = Some((pass, document));
state.wanted |= pressed || !stayed;
state.returns |= focused == Some(id);
// egui keeps the focus on a widget of a closed overlay for the pass after the last one that drew it.
if std::mem::replace(&mut state.overlay, overlay) || overlay {
if !overlay {
ctx.request_repaint();
}
return;
}
let wanted = std::mem::take(&mut state.wanted);
state.returns &= focused.is_none_or(|focused| focused == id);
let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id);
let field_pressed =
|| ctx.text_edit_focused() && focused.and_then(|field| ctx.read_response(field)).is_some_and(|field| field.is_pointer_button_down_on());
let takes = if pressed {
focused != Some(id) && !field_pressed()
} else if wanted {
focused != Some(id) && !ctx.text_edit_focused() && focused.is_none_or(|focused| layer(focused) == layer(id))
} else {
state.returns && focused.is_none()
};
if takes {
crate::framework::focus_session_view(ctx, id);
}
}
/// The dock's panels over the app in one pass.
struct Panels<'a> {
app: &'a mut crate::SoundApp,
edit: bool,
}
impl DockPanels<Panel> for Panels<'_> {
fn body(&mut self, panel: &Panel, ui: &mut egui::Ui, _: &mut BodyCx<'_>) {
let app = &mut *self.app;
match panel {
// The session view is its group's `group_view`.
Panel::Canvas => {}
Panel::Tracks => crate::panels::tracks_and_groups(app, ui),
Panel::Clips => crate::panels::clip_list(app, ui),
Panel::Midi => {
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("soundcraft-midi-body"), ui.max_rect()));
minimum_body(ui, vec2(420.0, 260.0), |ui| crate::midi_editor::show(app, ui));
}
Panel::Memory => crate::panels::memory_locations(app, ui),
Panel::History => crate::panels::undo_history(app, ui),
}
}
/// The session view: the Edit window's tracks and timeline, or the mixer.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Canvas) {
return None;
}
let id = crate::framework::session_view_id(self.edit);
let view = ui.interact(rect, id, egui::Sense::focusable_noninteractive());
view.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Canvas, true, crate::localization::text(Panel::Canvas.label())));
// The shortcuts read the root window's keys only, so a Mix window of its own leaves Tab to the focus. A press of
// Tab is the view's to its release: the repeats of the one that reached the last stop stay here.
let shortcuts_run = ui.ctx().viewport_id() == egui::ViewportId::ROOT;
let held = self.app.docks.view_focus(self.edit).kept_tab && ui.input(|input| input.key_down(egui::Key::Tab));
let keeps_tab = |app: &crate::SoundApp| shortcuts_run && (held || crate::shortcuts::tab_has_work(app));
// Declared before the widgets drawn over it, for its place in Tab order, and again after this pass's input has
// changed what Tab has to do.
crate::framework::host_canvas(ui.ctx(), id, keeps_tab(self.app));
ui.painter().rect_filled(rect, 0.0, crate::theme::Tokens::current().window_bg);
if self.edit {
crate::edit_window::main_area(self.app, ui);
} else {
crate::mix_window::content(self.app, ui);
}
focus_session_view(self.app, ui, self.edit, rect);
let kept_tab = keeps_tab(self.app);
self.app.docks.view_focus(self.edit).kept_tab = kept_tab;
crate::framework::host_canvas(ui.ctx(), id, kept_tab);
Some(rect.height())
}
}
/// Draw and edit the dock layout for the requested window, falling back to the default layout if validation or panel
/// sync fails, then publish panel visibility, store the workspace and apply the pass's layout actions.
/// sync fails, then publish panel visibility, store the workspace and apply the frame's layout actions.
pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWindow) {
app.docking_context = Some(ui.ctx().clone());
let t = crate::theme::Tokens::current();
let edit = window == crate::MainWindow::Edit;
let mut workspace =
if edit { std::mem::replace(&mut app.ui.docking, edit_default()) } else { std::mem::replace(&mut app.ui.mix_docking, mix_default()) };
@@ -755,31 +456,58 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
workspace = if edit { edit_default() } else { mix_default() };
let _ = sync(&mut workspace, app, edit);
}
cancel_replaced_workspace(app, &before_sync, &workspace);
cancel_replaced_workspace(app, &before_sync, &workspace, edit);
let mut style = DockStyle::from_ui(ui);
style.min_pane = 96.0;
style.tab_height = MIDI_TAB_HEIGHT;
style.background = t.panel_bg;
style.tab_background = t.panel_bg2;
style.active_background = t.row_selected;
style.text = t.text;
style.inactive_text = t.text_dim;
style.border = egui::Stroke::new(1.0, t.border);
style.accent = t.accent;
style.font = crate::theme::regular(11.5);
// Free docking: a panel dropped at an empty window edge makes a dock there, and the top
// and bottom edges take frames (`drop_edges` keeps its default).
style.new_dock_zones = true;
style.side_edge_zones = false;
// The MIDI body's rect stands for a piano roll on screen (the arrow keys go to it), so only a
// frame that draws the panel records one: open behind another tab, the old rect is gone.
if edit {
ui.ctx().data_mut(|data| data.remove::<egui::Rect>(egui::Id::unique("soundcraft-midi-body")));
}
refresh_specs(app);
let shown = app.docks.shown(edit, &workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.docks.specs);
// Floating windows stay inside the app window; a drop at an empty window edge makes a dock there, and the top and
// bottom edges take frames (`DockConfig::default()`).
let config = DockConfig::default().native_windows(false);
let output = ui
.push_id(area_id(window), |ui| {
let mut panels = Panels { app: &mut *app, edit };
DockArea::new("Panels", Bind::given(shown), &specs, &mut panels, config).show(ui)
})
.inner;
app.docks.specs = specs;
let output = DockArea::new(area(edit)).show_with_limits(
ui,
&workspace.layout,
&style,
|panel| crate::localization::text(panel.label()).into(),
permissions,
panel_limits,
|ui, panel| match panel {
Panel::Canvas => {
ui.painter().rect_filled(ui.max_rect(), 0.0, t.window_bg);
if edit {
crate::edit_window::main_area(app, ui);
} else {
crate::mix_window::content(app, ui);
}
}
Panel::Tracks => crate::panels::tracks_and_groups(app, ui),
Panel::Clips => crate::panels::clip_list(app, ui),
Panel::Midi => {
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("soundcraft-midi-body"), ui.max_rect()));
minimum_body(ui, egui::vec2(420.0, 260.0), |ui| crate::midi_editor::show(app, ui));
}
Panel::Memory => crate::panels::memory_locations(app, ui),
Panel::History => crate::panels::undo_history(app, ui),
},
);
let _ = sync(&mut workspace, app, edit);
publish_visibility(app, &workspace, edit);
store(app, workspace, edit);
for action in output.actions.into_iter().chain(output.requested) {
if let Err(error) = command_for(app, &DockCommand::Layout(action), edit) {
for action in output.actions {
if let Err(error) = command_for(app, &DockCommand::Layout { action }, edit) {
app.ui.status = crate::localized_format!("Panel move was not applied: {error}", error = error);
}
}
@@ -801,15 +529,14 @@ pub(crate) fn minimum_body(ui: &mut egui::Ui, minimum: egui::Vec2, body: impl Fn
});
}
/// The panels' body limits: a minimum size and, for side panels, a maximum width.
fn panel_limits(panel: &Panel) -> SizeLimits {
fn panel_limits(panel: &Panel) -> PanelLimits {
let (min, max_width) = match panel {
Panel::Canvas => (vec2(300.0, 240.0), SizeLimits::BOUND),
Panel::Tracks => (vec2(140.0, 120.0), 520.0),
Panel::Clips => (vec2(180.0, 120.0), 720.0),
Panel::Midi => (vec2(420.0, 260.0), SizeLimits::BOUND),
Panel::Memory => (vec2(260.0, 160.0), SizeLimits::BOUND),
Panel::History => (vec2(200.0, 160.0), 720.0),
Panel::Canvas => (egui::vec2(300.0, 240.0), 1_000_000.0),
Panel::Tracks => (egui::vec2(140.0, 120.0), 520.0),
Panel::Clips => (egui::vec2(180.0, 120.0), 720.0),
Panel::Midi => (egui::vec2(420.0, 260.0), 1_000_000.0),
Panel::Memory => (egui::vec2(260.0, 160.0), 1_000_000.0),
Panel::History => (egui::vec2(200.0, 160.0), 720.0),
};
SizeLimits::new(min, vec2(max_width, SizeLimits::BOUND))
PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) }
}
+1 -1
View File
@@ -283,7 +283,7 @@ fn harness(n: usize) -> Harness<'static, SoundApp> {
fn harness_with(engine: soundcraft_engine::Engine) -> Harness<'static, SoundApp> {
let app = SoundApp::new(engine, None, crate::Services::default());
let builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).with_context_setup(crate::framework::install_headless);
let builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0);
let builder = if std::env::var_os("SOUNDCRAFT_FADE_SHOTS").is_some() { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut SoundApp| {
+1 -34
View File
@@ -135,18 +135,8 @@ pub fn definitions(system_fonts: bool) -> FontDefinitions {
fonts
}
/// Gives the context [`definitions`] through the framework runtime, which keeps its font providers and layout memory in
/// step with them. The framework's chrome draws in three families besides the monospace one: the signature family
/// (follows the proportional one) and the semibold family, which titles and strong text use because the stack the
/// runtime started with has it; SoundCraft's own bold family serves as that one. A family left out draws missing-glyph
/// boxes.
pub fn install(ctx: &egui::Context, system_fonts: bool) {
let mut fonts = definitions(system_fonts);
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
let bold = fonts.families.get(&FontFamily::Name("bold".into())).cloned().unwrap_or_else(|| proportional.clone());
fonts.families.entry(craft_ui::fonts::FontRef::signature().family()).or_insert(proportional);
fonts.families.entry(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into())).or_insert(bold);
craft_ui::fonts::load(ctx, fonts);
ctx.set_fonts(definitions(system_fonts));
}
#[cfg(test)]
@@ -185,29 +175,6 @@ mod tests {
}
}
/// Every family the framework's chrome draws in has a face after `install`, with and without system fonts: the
/// dialog title once drew boxes because the semibold family was missing.
#[test]
fn install_gives_every_chrome_family_a_face() {
for system_fonts in [false, true] {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
install(&ctx, system_fonts);
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
output.textures_delta.clear();
let families = [
FontFamily::Proportional,
FontFamily::Monospace,
craft_ui::fonts::FontRef::signature().family(),
FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()),
];
for family in families {
let font = egui::FontId::new(14.0, family.clone());
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "Check for Updates")), "{family:?} has no Latin face (system fonts {system_fonts})");
}
}
}
/// Korean names draw in every family, not as boxes; skipped when the system has no Korean font.
#[test]
fn every_family_draws_hangul_with_a_system_korean_font() {
-182
View File
@@ -1,182 +0,0 @@
//! The craft-ui runtime, hosted from SoundCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`SoundApp::before_input`] in `raw_input_hook`, [`SoundApp::close_path`]
//! last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`].
//! [`SoundApp::run_framework_dialogs`] runs the framework dialogs after SoundCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of SoundCraft's own
//! egui widgets has the keyboard. The window's Escape is read with [`escape_pressed`]; the session view is declared
//! to the runtime with [`host_canvas`], which keeps the edit chords and the clipboard events in egui's input for
//! SoundCraft's shortcuts, and Tab while the focused view has work for it. A focused view leaves the keyboard to the
//! shortcuts ([`widget_has_keyboard`]).
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::{Chord, Key, Mods, Overrides};
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet, NavCommand, QuitCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, FocusTarget, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::runtime::overlay::{self, OpenFilter};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::system::WindowSystem;
use crate::SoundApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. SoundCraft's own definitions
/// ([`crate::fonts::install`]) replace it on the first frame, before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. `forced_x11` when the app
/// opens its window through XWayland. SoundCraft keeps the system's title bar on every platform.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, forced_x11: bool) -> Result<(), String> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
install_with(ctx, ShellInfo::default().backend(backend), Arc::new(craft_window::system::SystemWindows))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
log::warn!("{error}");
}
}
/// Who SoundCraft is to the framework's dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "soundcraft", name: "SoundCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.soundcraft.png"))
.build(),
)
}
/// The runtime's default keys SoundCraft's own shortcuts use: F6 and Shift+F6 move between panes by default, and F6
/// is the Trim tool in SoundCraft; Cmd+Q (Ctrl+Q) is the runtime's Quit, and SoundCraft quits through its own
/// `app.quit`, which keeps its recording and recovery rules. Overrides are keyed by command id, which the command set
/// gives.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
overrides.insert(NavCommand::NextPane.id(), Vec::new());
overrides.insert(NavCommand::PreviousPane.id(), Vec::new());
overrides.insert(QuitCommand::Quit.id(), Vec::new());
Arc::new(overrides)
})
.clone()
}
impl SoundApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(output));
}
/// The root values of this frame. SoundCraft registers no commands with the runtime and lets it toggle no
/// chrome, so the output carries nothing it acts on. The interface scale is the one SoundCraft applied last
/// (`extra_windows`), so the runtime's zoom and SoundCraft's agree.
fn frame_input(&mut self, _output: FrameOutput) -> FrameInput {
let mode = if crate::theme::is_light() { craft_theme::Mode::Light } else { craft_theme::Mode::Dark };
// SoundCraft zooms with Cmd/Ctrl+scroll itself, so a smooth Ctrl+wheel stays a wheel event.
let root = RootEnv::new().mode(mode).scale(Scale::new(self.extra.applied_scale())).ctrl_wheel_pinch(false);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host))
}
/// The framework's part of `App::logic`, after SoundCraft's own: the root window's close path. A close the app
/// asked for itself goes through; otherwise unsaved changes hold the window open while Save Changes asks, and
/// its answer quits the app.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || {
if self.quit_requested || !crate::dialogs::ask_to_save(self, "app.quit", &serde_json::json!({})) {
CloseDecision::Close
} else {
CloseDecision::Hold
}
});
}
/// The framework dialogs open on [`SoundApp::framework_dialogs`], once per pass after SoundCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
}
}
/// The edit-mode keys (Alt+1 to Alt+4, Pro Tools' Shuffle, Slip, Spot and Grid) the session view claims, so Alt-code
/// entry leaves them to SoundCraft's shortcuts.
const EDIT_MODE_KEYS: [Chord; 4] =
[Chord::new(Mods::ALT, Key::Num1), Chord::new(Mods::ALT, Key::Num2), Chord::new(Mods::ALT, Key::Num3), Chord::new(Mods::ALT, Key::Num4)];
/// The widget of the session view: the Edit window's tracks and timeline (`edit`) or the Mix window's strips.
pub fn session_view_id(edit: bool) -> egui::Id {
egui::Id::unique(("soundcraft-session-view", edit))
}
/// Declares the session view `id`, drawn in this pass, as the window's document canvas. With nothing focused it is
/// the window's key target: the edit chords, the clipboard events and the edit-mode keys stay in egui's input for
/// SoundCraft's shortcuts, as do the arrows, Enter and the page keys. Tab and Shift+Tab stop at the view; with
/// `keeps_tab` the focused view keeps them in egui's input, else they move on from it.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id, keeps_tab: bool) {
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL).with_claims(&EDIT_MODE_KEYS);
let keys = if keeps_tab { KEYS.with_keep(KeepKeys::Tab) } else { KEYS };
craft_ui::runtime::focus::host_canvas(ctx, id, keys);
}
/// Gives the session view `id`, declared in this pass, the keyboard focus.
pub(crate) fn focus_session_view(ctx: &egui::Context, id: egui::Id) {
craft_ui::runtime::focus::request(ctx, FocusTarget::Id(id));
}
/// Whether a widget other than the session view has the keyboard. A focused session view leaves it to SoundCraft's
/// shortcuts, as with nothing focused.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
ctx.memory(|memory| memory.focused()).is_some_and(|focused| ![true, false].map(session_view_id).contains(&focused))
}
/// Whether a modal dialog, SoundCraft's, egui's or the framework's, or an egui menu or popup is up. A framework menu
/// holds the focus in its own layer.
pub(crate) fn overlay_open(app: &SoundApp, ctx: &egui::Context) -> bool {
app.dialogs.open.is_some()
|| app.ui.show_preferences
|| app.ui.show_search
|| egui::Popup::is_any_open(ctx)
|| ctx.memory(|memory| memory.top_modal_layer()).is_some()
|| overlay::any_open(ctx, OpenFilter::Modal)
}
/// Whether Escape was pressed in this pass: from egui while one of SoundCraft's own widgets or popups has the
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel_pending(ctx)
}
/// Whether the window's cancel (an Escape while nothing has framework focus) is there and untaken.
fn window_cancel_pending(ctx: &egui::Context) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = intents.untaken(&Intent::Cancel);
false
});
pending
}
-15
View File
@@ -23,7 +23,6 @@ pub mod dialogs;
pub mod docking;
pub mod edit_window;
pub mod fonts;
pub mod framework;
pub mod icons;
pub mod import;
pub mod localization;
@@ -63,7 +62,6 @@ pub use panels::video_window;
pub use panels::windows;
mod app;
mod capture;
mod services;
mod state;
@@ -149,8 +147,6 @@ pub struct UiState {
pub preferences_window_pos: Option<[f32; 2]>,
pub reduce_visual_effects: preferences::ReduceVisualEffects,
pub undo_levels: usize,
/// The level a send made in the Mix window starts at (Preferences › Mixing).
pub sends_default: preferences::SendsDefault,
/// The audio device choice (Setup › Playback Engine), kept with the preferences: per machine.
pub audio: soundcraft_playback::AudioConfig,
/// The Mix window lives in its own native window (Window › Mix in Separate Window); the main
@@ -229,7 +225,6 @@ impl Default for UiState {
preferences_window_pos: None,
reduce_visual_effects: preferences::ReduceVisualEffects::default(),
undo_levels: 64,
sends_default: preferences::SendsDefault::default(),
audio: soundcraft_playback::AudioConfig::default(),
mix_separate: false,
show_io_setup: false,
@@ -383,8 +378,6 @@ pub struct SoundApp {
synthetic_pointer_active: bool,
/// Cancel that press before the next egui input pass, without a release click/drop.
cancel_synthetic_pointer: bool,
/// `ui.key` requests waiting for the framework's injected input to run.
injected_acks: VecDeque<control::InjectedAck>,
/// A key/text batch crossed its deadline after [`Self::raw_input_hook`] had already appended it
/// to the pass. Do not dispatch that stale copy through shortcuts or widgets.
cancel_synthetic_keys: bool,
@@ -454,12 +447,6 @@ pub struct SoundApp {
theme_applied: Option<bool>,
/// Last panel host context, used to cancel renderer-owned gestures on explicit replacement.
pub(crate) docking_context: Option<egui::Context>,
/// The workspaces and panel specs the Edit and Mix docks show.
pub(crate) docks: docking::LiveDocks,
/// The framework dialogs (update check and prompt); they run once per pass after the app's own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who SoundCraft is to the framework's components.
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
/// Transport simulation when there is no player (tests, offscreen renders).
sim: Option<(Samples, Option<Samples>, Option<Range>)>,
/// When Record last found nothing to record on, and why: the Record buttons show it for a moment.
@@ -484,8 +471,6 @@ pub struct SoundApp {
pub frame_ms: f32,
last_frame: Option<f64>,
last_meter_poll: f64,
/// When a meter take last brought new audio blocks (uptime, seconds).
last_meter_block: f64,
/// Movies for the Video window and Video track (decoded in the background).
pub video: video_track::VideoPool,
/// The Bounce Mix in progress, rendered a slice per frame.
+16 -68
View File
@@ -1,9 +1,5 @@
//! Language selection and source-language fallback for UI strings.
#[path = "../locales/es/mod.rs"]
mod es;
#[path = "../locales/fr/mod.rs"]
mod fr;
#[path = "../locales/pt-BR/mod.rs"]
mod pt_br;
@@ -21,23 +17,17 @@ pub enum Language {
English,
#[serde(rename = "pt-BR")]
PortugueseBrazil,
#[serde(rename = "fr")]
French,
#[serde(rename = "es")]
Spanish,
}
impl Language {
/// All supported languages, in the order they are shown in the language menu.
pub const ALL: [Self; 4] = [Self::English, Self::PortugueseBrazil, Self::French, Self::Spanish];
pub const ALL: [Self; 2] = [Self::English, Self::PortugueseBrazil];
/// Stable language tag used in preferences and control commands.
pub const fn id(self) -> &'static str {
match self {
Self::English => "en",
Self::PortugueseBrazil => "pt-BR",
Self::French => "fr",
Self::Spanish => "es",
}
}
@@ -46,8 +36,6 @@ impl Language {
match self {
Self::English => "English",
Self::PortugueseBrazil => "Portuguese (Brazil)",
Self::French => "French",
Self::Spanish => "Spanish",
}
}
@@ -59,7 +47,7 @@ impl Language {
pub fn localize_decimal(self, number: &str) -> String {
match self {
Self::English => number.to_owned(),
Self::PortugueseBrazil | Self::French | Self::Spanish => number.replace('.', ","),
Self::PortugueseBrazil => number.replace('.', ","),
}
}
@@ -68,8 +56,6 @@ impl Language {
match self {
Self::English => source,
Self::PortugueseBrazil => pt_br::translate(source).unwrap_or(source),
Self::French => fr::translate(source).unwrap_or(source),
Self::Spanish => es::translate(source).unwrap_or(source),
}
}
}
@@ -103,8 +89,6 @@ fn error_text_in(language: Language, message: &str, depth: usize) -> String {
let templates: &[(&str, &str)] = match language {
Language::English => &[],
Language::PortugueseBrazil => pt_br::ERROR_TEMPLATES,
Language::French => fr::ERROR_TEMPLATES,
Language::Spanish => es::ERROR_TEMPLATES,
};
let mut best: Option<(usize, &str, Vec<(String, String)>)> = None;
for (template, translation) in templates {
@@ -370,8 +354,7 @@ mod tests {
assert_eq!(decoded, language);
}
assert_eq!(Language::parse(" PT-br "), Some(Language::PortugueseBrazil));
assert_eq!(Language::parse(" FR "), Some(Language::French));
assert_eq!(Language::parse("de"), None);
assert_eq!(Language::parse("fr"), None);
}
#[test]
@@ -379,10 +362,6 @@ mod tests {
assert_ne!(Language::PortugueseBrazil.text("Appearance"), "Appearance");
assert_eq!(Language::PortugueseBrazil.text("A source string with no catalog entry"), "A source string with no catalog entry");
assert_eq!(Language::English.text("Appearance"), "Appearance");
for language in [Language::French, Language::Spanish] {
assert_ne!(language.text("Appearance"), "Appearance", "{language:?}");
assert_eq!(language.text("A source string with no catalog entry"), "A source string with no catalog entry");
}
}
#[test]
@@ -409,15 +388,6 @@ mod tests {
}
}
#[test]
fn spanish_catalog_covers_every_menu_label() {
for path in include_str!("../../engine/catalog/menus.txt").lines() {
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
assert!(super::es::translate(label).is_some(), "missing es menu label: {label}");
}
}
}
#[test]
fn engine_errors_are_translated_with_their_values() {
assert_eq!(error_text("select a clip"), "select a clip");
@@ -490,17 +460,9 @@ mod tests {
None
}
type Lookup = fn(&str) -> Option<&'static str>;
/// Every catalog: its tag, source file and lookup.
const CATALOGS: [(&str, &str, Lookup); 3] = [
("pt-BR", include_str!("../locales/pt-BR/mod.rs"), super::pt_br::translate),
("fr", include_str!("../locales/fr/mod.rs"), super::fr::translate),
("es", include_str!("../locales/es/mod.rs"), super::es::translate),
];
/// Every `"source" => "translation"` pair of a catalog, read from its source file.
fn catalog_entries(text: &str) -> Vec<(String, String)> {
/// Every `"source" => "translation"` pair of the catalog, read from its source file.
fn catalog_entries() -> Vec<(String, String)> {
let text = include_str!("../locales/pt-BR/mod.rs");
let mut lines = text.lines().map(str::trim);
let mut entries = Vec::new();
while let Some(line) = lines.next() {
@@ -533,37 +495,23 @@ mod tests {
#[test]
fn catalog_entries_are_parsed_and_unique() {
for (tag, text, _) in CATALOGS {
let entries = catalog_entries(text);
assert!(entries.len() > 1000, "{tag}: parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "{tag}: duplicate catalog keys");
}
let entries = catalog_entries();
assert!(entries.len() > 1000, "parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "duplicate catalog keys");
}
#[test]
fn catalog_translations_keep_the_english_placeholders() {
for (tag, text, translate) in CATALOGS {
for (source, translation) in catalog_entries(text) {
assert_eq!(placeholders(&source), placeholders(&translation), "{tag}: placeholders differ for {source:?}");
assert_eq!(translate(&source), Some(translation.as_str()), "{tag}: lookup differs for {source:?}");
}
for (source, translation) in catalog_entries() {
assert_eq!(placeholders(&source), placeholders(&translation), "placeholders differ for {source:?}");
assert_eq!(super::pt_br::translate(&source), Some(translation.as_str()), "lookup differs for {source:?}");
}
}
/// The Strip Silence dialog's action button and the Channel Strip plug-in's short name are
/// different strings ("remove" vs a channel strip): the button keeps the dialog's own key,
/// so a translation gives each its word (#1610).
#[test]
fn strip_button_translates_as_its_own_key() {
let pt = Language::PortugueseBrazil;
assert_eq!(pt.text("Strip Silence"), "Remover silêncio", "the dialog's action button");
assert_eq!(pt.text("Strip"), "Canal", "the Channel Strip plug-in's short name keeps its own key");
}
#[test]
fn every_localized_source_string_has_a_catalog_entry() {
fn visit(dir: &std::path::Path, missing: &mut Vec<String>) {
-114
View File
@@ -82,7 +82,6 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
("ui.theme", "Appearance", "", None),
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
("ui.undo_levels", "Levels of Undo", "", None),
("ui.sends_default", "Sends Default to", "", None),
];
/// Extra catalog mappings handled by the UI layer.
@@ -850,20 +849,6 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
}
json!({"levels": app.ui.undo_levels})
}
"ui.sends_default" => {
// No `level` reads the value back; a `level` that is not a string is an error, so
// `{"level": 0}` cannot look like it set 0 dB while changing nothing.
let level = match p.get("level") {
None => return Some(Ok(json!({"level": app.ui.sends_default.id()}))),
Some(Value::String(level)) => level.as_str(),
Some(other) => return Some(Err(format!("send default must be the string \"-inf\" or \"0\", not {other}"))),
};
let Some(level) = crate::preferences::SendsDefault::parse(level) else {
return Some(Err(format!("unknown send default `{level}` (-inf or 0)")));
};
app.ui.sends_default = level;
json!({"level": level.id()})
}
"ui.set" => match serde_json::to_value(&app.ui) {
Ok(mut cur) => {
if let (Some(obj), Some(patch)) = (cur.as_object_mut(), p.as_object()) {
@@ -881,8 +866,6 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
app.ui = ns;
app.ui.undo_levels = app.ui.undo_levels.clamp(1, 64);
app.engine.set_history_limit(app.ui.undo_levels);
// The list is newest first, so this keeps the newest, as `recent::note` does.
app.ui.recent_sessions.truncate(crate::dialogs::recent::MAX_RECENT);
if closed_preferences {
app.preferences.discard_draft();
}
@@ -968,103 +951,6 @@ mod tests {
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (64, 64));
}
/// The Sends Default to preference reads back, takes -inf or 0, and rejects anything else.
#[test]
fn sends_default_sets_reads_and_rejects_unknown_levels() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
assert_eq!(app.run("ui.sends_default", json!({})).unwrap(), json!({"level": "-inf"}));
assert_eq!(app.run("ui.sends_default", json!({"level": "0"})).unwrap(), json!({"level": "0"}));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(app.run("ui.sends_default", json!({"level": "-6"})).is_err());
assert_eq!(app.ui.sends_default, SendsDefault::Unity, "a rejected level changes nothing");
assert_eq!(app.run("ui.sends_default", json!({"level": "-inf"})).unwrap(), json!({"level": "-inf"}));
assert_eq!(app.ui.sends_default, SendsDefault::NegativeInfinity, "switching back to −∞ dB works");
assert!(!app.engine.is_dirty(), "a preference is not a document edit");
}
/// A `level` that is present but not a string is an error, not a read-back: `{"level": 0}` must
/// not look like it set 0 dB while changing nothing.
#[test]
fn sends_default_rejects_a_non_string_level() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for bad in [json!(0), json!(null), json!(false), json!(["0"])] {
assert!(app.run("ui.sends_default", json!({"level": bad})).is_err(), "{bad} accepted");
assert_eq!(app.ui.sends_default, SendsDefault::NegativeInfinity, "{bad} changed the setting");
}
}
/// `ui.set` takes the same `-inf` and `0` as `ui.sends_default`, and a bad value changes nothing.
#[test]
fn ui_set_takes_the_same_sends_default_levels() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let result = app.run("ui.set", json!({"sends_default": "0"})).unwrap();
assert_eq!((result["ui"]["sends_default"].clone(), app.ui.sends_default), (json!("0"), SendsDefault::Unity));
let result = app.run("ui.set", json!({"sends_default": "-inf"})).unwrap();
assert_eq!((result["ui"]["sends_default"].clone(), app.ui.sends_default), (json!("-inf"), SendsDefault::NegativeInfinity));
app.run("ui.set", json!({"sends_default": "0"})).unwrap();
for bad in [json!("unity"), json!("-6"), json!(0)] {
assert!(app.run("ui.set", json!({"sends_default": bad})).is_err(), "{bad} accepted");
assert_eq!(app.ui.sends_default, SendsDefault::Unity, "{bad} changed the setting");
}
}
fn recent_paths(count: usize) -> Vec<String> {
(0..count).map(|i| format!("{i}.scraft")).collect()
}
/// `ui.set` keeps the newest `MAX_RECENT` recent sessions, in order, and answers with that list.
#[test]
fn ui_set_keeps_at_most_ten_recent_sessions() {
use crate::dialogs::recent::MAX_RECENT;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for count in [MAX_RECENT + 1, 1000] {
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(count)})).unwrap();
assert_eq!(app.ui.recent_sessions, recent_paths(MAX_RECENT), "{count} entries: the first ten, in order");
assert_eq!(result["ui"]["recent_sessions"], json!(recent_paths(MAX_RECENT)), "{count} entries: the answer shows the kept list");
}
}
/// A list within the limit, an empty one included, is stored as given.
#[test]
fn ui_set_leaves_a_recent_list_within_the_limit_alone() {
use crate::dialogs::recent::MAX_RECENT;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for count in [MAX_RECENT, MAX_RECENT - 1, 1, 0] {
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(count)})).unwrap();
assert_eq!(app.ui.recent_sessions, recent_paths(count), "{count} entries");
assert_eq!(result["ui"]["recent_sessions"], json!(recent_paths(count)), "{count} entries");
}
}
/// Capping the list does not drop the other fields of the same call.
#[test]
fn ui_set_applies_other_fields_beside_a_capped_recent_list() {
use crate::dialogs::recent::MAX_RECENT;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(25), "undo_levels": 7})).unwrap();
assert_eq!((app.ui.recent_sessions.len(), app.ui.undo_levels, app.engine.history_limit), (MAX_RECENT, 7, 7));
assert_eq!(result["ui"]["undo_levels"], 7);
// A call that does not name the list leaves it as it was.
app.run("ui.set", json!({"undo_levels": 9})).unwrap();
assert_eq!(app.ui.recent_sessions, recent_paths(MAX_RECENT));
}
/// A list that is not an array of strings is refused, however long, and nothing changes.
#[test]
fn ui_set_refuses_a_recent_list_of_the_wrong_type() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.run("ui.set", json!({"recent_sessions": recent_paths(3), "undo_levels": 7})).unwrap();
let numbers: Vec<u32> = (0..25).collect();
for bad in [json!("a.scraft"), json!(5), json!(null), json!({"0": "a.scraft"}), json!(["a.scraft", 5]), json!(numbers)] {
let error = app.run("ui.set", json!({"recent_sessions": bad, "undo_levels": 20})).unwrap_err();
assert!(error.starts_with("bad ui state"), "{bad}: {error}");
assert_eq!((app.ui.recent_sessions.clone(), app.ui.undo_levels), (recent_paths(3), 7), "{bad} changed the state");
}
}
#[test]
fn mix_view_aliases_are_allocated_once() {
let first = ui_aliases();
+2 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn output_window(app: &mut SoundApp, ctx: &egui::Context) {
// last frame, because egui closes them before this runs.
let busy_id = egui::Id::unique("output_window_escape");
let busy = ctx.data(|d| d.get_temp(busy_id)).unwrap_or(false) || app.dialogs.open.is_some() || app.ui.show_search;
if !busy && crate::framework::escape_pressed(ctx) {
if !busy && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
app.ui.output_window = None;
}
output_window_contents(app, ctx);
@@ -147,7 +147,7 @@ mod tests {
app.run("view.edit_io", json!({})).unwrap();
app.run("track.height", json!({"tracks": ["Kick"], "height": "medium"})).unwrap();
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
app.ui(ui);

Some files were not shown because too many files have changed in this diff Show More