mirror of
https://github.com/storytold/soundcraft.git
synced 2026-11-06 10:20:26 -06:00
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7bf178835f | ||
|
|
e66a5e7c67 | ||
|
|
87f46cf23b | ||
|
|
54cb247e12 | ||
|
|
73eeb692fe | ||
|
|
bd75fe691b | ||
|
|
6c8a9dd300 | ||
|
|
d393730b02 | ||
|
|
4240ffda42 | ||
|
|
c046c3bb1b | ||
|
|
e6cbf76148 | ||
|
|
1db9563379 | ||
|
|
341a112757 | ||
|
|
594d0ade4f | ||
|
|
92e6973640 | ||
|
|
2b03df3ad4 | ||
|
|
5fabf28c31 | ||
|
|
fa34e0c182 | ||
|
|
ccebb8ff93 | ||
|
|
dbcbcbac00 | ||
|
|
c692648200 | ||
|
|
bf274560ae | ||
|
|
087978a4a0 | ||
|
|
9b5554e312 | ||
|
|
e1f10ccdc8 | ||
|
|
627bbbf9cc | ||
|
|
84baa5debc | ||
|
|
468bec487c | ||
|
|
71f899baac | ||
|
|
ccbeec6680 | ||
|
|
381832447c | ||
|
|
d7c194d728 | ||
|
|
f92150c64e | ||
|
|
66f305b747 | ||
|
|
b9accf92a8 | ||
|
|
d33cac774a | ||
|
|
93ac4f2913 | ||
|
|
352d90a24a | ||
|
|
b48a939d64 | ||
|
|
7849e8cf51 |
@@ -0,0 +1,28 @@
|
||||
name: House rules
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: house-rules-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
house-rules:
|
||||
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
|
||||
with:
|
||||
rust: true
|
||||
@@ -41,3 +41,4 @@ jobs:
|
||||
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 }}
|
||||
|
||||
@@ -1,11 +1,62 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## House rules
|
||||
|
||||
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
|
||||
|
||||
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
|
||||
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
|
||||
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
|
||||
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
|
||||
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
|
||||
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
|
||||
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
|
||||
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
|
||||
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
|
||||
10. **Keep secrets and personal details out** of the repository, logs and requests.
|
||||
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
|
||||
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
|
||||
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
|
||||
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
|
||||
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## Rust Craft repositories
|
||||
|
||||
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
|
||||
|
||||
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
|
||||
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
|
||||
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
|
||||
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
|
||||
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
|
||||
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
|
||||
|
||||
## Licence allowlist
|
||||
|
||||
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
|
||||
|
||||
- `ISC`
|
||||
- `MIT`
|
||||
- `BSD-2-Clause`
|
||||
- `BSD-3-Clause`
|
||||
- `Apache-2.0`
|
||||
- `OFL-1.1`
|
||||
- `Ubuntu-font-1.0`
|
||||
- `Bitstream-Vera`
|
||||
- `CC0-1.0`
|
||||
- `CC-BY-4.0`
|
||||
- `CC-BY-SA-4.0`
|
||||
- `LicenseRef-Public-Domain`
|
||||
|
||||
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# SoundCraft — instructions for agents
|
||||
|
||||
SoundCraft is a clean-room, open-source, pure-Rust digital audio workstation targeting Avid Pro Tools parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign).
|
||||
|
||||
## Start every session here
|
||||
1. Read `plan/STATUS.md` (current milestone, next task) and `plan/execution-plan.md`. `plan/` is gitignored (local only). Behaviour reference: `plan/protools/` (observed menu tree `menus-clean.txt` and screenshots; never committed).
|
||||
2. Read `ROADMAP.md` (committed) for stage, status and the parity numbers; pick work from `docs/gaps.md`. The progress docs are `docs/target-app-parity.md` (assessment), `docs/gaps.md`, `docs/roadmap.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/plugin-parity.md`, `docs/localization-parity.md`; `docs/parity-checklist.md` is generated. Update their timestamps and revision history when you change them.
|
||||
3. Work autonomously; don't stop to ask unless a decision is genuinely the user's.
|
||||
Read `ROADMAP.md` for stage, status and the parity numbers, and pick work from `docs/gaps.md`. The progress docs are `docs/target-app-parity.md` (assessment), `docs/gaps.md`, `docs/roadmap.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/plugin-parity.md`, `docs/localization-parity.md`; `docs/parity-checklist.md` is generated. Update their timestamps and revision history when you change them. `plan/` is an optional gitignored notebook (`plan/protools/` holds an observed menu tree and screenshots, never committed). Do not ask for it and do not stop when it is absent.
|
||||
|
||||
## ⚠️ Assets: the absolute rule
|
||||
**No Avid, Pro Tools, Adobe or other proprietary iconography, images, sounds, presets or artwork — ever.** This is not negotiable.
|
||||
@@ -30,7 +81,6 @@ People trust SoundCraft with their recordings; a crash loses takes. **This outra
|
||||
- The audio callback never blocks, allocates in steady state, or panics.
|
||||
- Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
|
||||
- `Engine::execute` catches escaped panics and restores the document. Every crash fix lands with a regression test.
|
||||
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
|
||||
|
||||
|
||||
## Architecture (layers enforced by `cargo xtask layers`)
|
||||
@@ -89,3 +139,5 @@ Push to the `release` branch to build signed installers for macOS (universal DMG
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
|
||||
|
||||
@@ -1,10 +1 @@
|
||||
Read `AGENTS.md`: it is the entry point for agents in this repo.
|
||||
|
||||
New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit
|
||||
`[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes
|
||||
before modules or other crate items; crate-level `//!` documentation may precede them.
|
||||
|
||||
## CI workflows
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
@AGENTS.md
|
||||
|
||||
Generated
+34
-5
@@ -1422,6 +1422,19 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
"enum-map",
|
||||
"itertools 0.15.0",
|
||||
"log",
|
||||
"profiling",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
@@ -1475,6 +1488,26 @@ version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
|
||||
|
||||
[[package]]
|
||||
name = "enum-map"
|
||||
version = "3.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06"
|
||||
dependencies = [
|
||||
"enum-map-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enum-map-derive"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enumflags2"
|
||||
version = "0.7.12"
|
||||
@@ -4490,6 +4523,7 @@ dependencies = [
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"egui",
|
||||
"egui_extras",
|
||||
"egui_kittest",
|
||||
"image",
|
||||
"log",
|
||||
@@ -6510,11 +6544,6 @@ name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
|
||||
@@ -60,6 +60,8 @@ craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-l
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
|
||||
egui = { version = "0.37" }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
# Monotonic clock on native and the browser (the `web_time::Instant` panics-free equivalent).
|
||||
web-time = "1.1"
|
||||
|
||||
@@ -228,7 +228,8 @@ soundcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
|
||||
See [`docs/cli.md`](docs/cli.md) for the command-line tool (subcommands, exit codes, environment
|
||||
variables, man pages and completions), [`docs/control-protocol.md`](docs/control-protocol.md) and
|
||||
[`docs/mcp.md`](docs/mcp.md). `soundcraft-cli commands` lists every command.
|
||||
[`docs/mcp.md`](docs/mcp.md). `soundcraft-cli commands` lists every command (`--json` for each
|
||||
one's parameters and details, as JSON).
|
||||
|
||||
Open **SoundCraft › Session Audio Health** to check loaded audio availability, sample-rate
|
||||
mismatches and clip source bounds across all playlists, including alternate takes. The report
|
||||
|
||||
@@ -168,6 +168,12 @@ pub(crate) struct CommandsArgs {
|
||||
/// Only the commands whose id, or label in any case, contains this text
|
||||
#[arg(value_parser = NonEmptyStringValueParser::new())]
|
||||
pub(crate) filter: Option<String>,
|
||||
/// Print a JSON array of each command's details, as describe prints them
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
/// One line of JSON instead of pretty-printed
|
||||
#[arg(long, requires = "json")]
|
||||
pub(crate) compact: bool,
|
||||
}
|
||||
|
||||
/// Print one engine command's details as JSON
|
||||
|
||||
@@ -7,11 +7,15 @@ use std::io::Write;
|
||||
pub(crate) fn commands(args: &CommandsArgs, out: &mut dyn Write) {
|
||||
let filter = args.filter.clone().unwrap_or_default();
|
||||
let e = Engine::default();
|
||||
for c in soundcraft_engine::command_specs() {
|
||||
if !filter.is_empty() && !c.id.contains(&filter) && !c.label.to_ascii_lowercase().contains(&filter.to_ascii_lowercase()) {
|
||||
continue;
|
||||
}
|
||||
let i = c.info(&e);
|
||||
let infos = soundcraft_engine::command_specs()
|
||||
.iter()
|
||||
.filter(|c| filter.is_empty() || c.id.contains(&filter) || c.label.to_ascii_lowercase().contains(&filter.to_ascii_lowercase()))
|
||||
.map(|c| c.info(&e));
|
||||
if args.json {
|
||||
print_json(out, &infos.collect::<Vec<_>>(), args.compact);
|
||||
return;
|
||||
}
|
||||
for i in infos {
|
||||
outln!(out, "{:<36} {:<34} {}", i.id, i.label, i.menu.join(" > "));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,3 +253,31 @@ fn script_bounce_without_range_covers_the_session() {
|
||||
assert!((secs - 19.2).abs() < 0.01, "bounced {secs} s: {stdout}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `commands --json` lists every command with the details `describe` prints for one (#744).
|
||||
#[test]
|
||||
fn commands_json_lists_what_describe_prints() {
|
||||
let json = |o: &Output| -> Value {
|
||||
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
serde_json::from_slice(&o.stdout).unwrap()
|
||||
};
|
||||
let all = json(&run(&["commands", "--json"]));
|
||||
let all = all.as_array().unwrap();
|
||||
let table = run(&["commands"]);
|
||||
assert_eq!(all.len(), String::from_utf8_lossy(&table.stdout).lines().count());
|
||||
let bounce = json(&run(&["describe", "file.bounce_mix"]));
|
||||
assert!(all.contains(&bounce), "{bounce}");
|
||||
assert!(all.iter().all(|c| c["id"].is_string() && c["params"].is_string() && c["menu"].is_array()));
|
||||
// The filter applies, and --compact prints one line.
|
||||
let compact = run(&["commands", "bounce", "--json", "--compact"]);
|
||||
assert_eq!(String::from_utf8_lossy(&compact.stdout).lines().count(), 1);
|
||||
let some = json(&compact);
|
||||
let some = some.as_array().unwrap();
|
||||
assert!(some.contains(&bounce) && some.len() < all.len(), "{some:?}");
|
||||
// No match is an empty list, still JSON.
|
||||
assert_eq!(json(&run(&["commands", "zzzzqq", "--json"])), Value::Array(Vec::new()));
|
||||
// --compact shapes JSON output only.
|
||||
let bad = run(&["commands", "--compact"]);
|
||||
assert_eq!(bad.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&bad.stderr).contains("--json"), "{}", String::from_utf8_lossy(&bad.stderr));
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ fn every_subcommand_has_help_listing_its_arguments() {
|
||||
),
|
||||
("run", "run [OPTIONS]", &["--cmd <ID[=JSON]>"]),
|
||||
("script", "script [OPTIONS] <FILE>", &["<FILE>", "--keep-going"]),
|
||||
("commands", "commands [FILTER]", &["[FILTER]"]),
|
||||
("commands", "commands [OPTIONS] [FILTER]", &["[FILTER]", "--json", "--compact"]),
|
||||
("describe", "describe [OPTIONS] <ID>", &["<ID>", "--compact"]),
|
||||
(
|
||||
"app",
|
||||
|
||||
@@ -33,6 +33,7 @@ impl NativeMenu {
|
||||
let mut native = Self { menu, entries: Vec::new(), events, last_sync: None };
|
||||
let app_menu = Submenu::new("SoundCraft", true);
|
||||
native.add_item(app, &app_menu, "About SoundCraft", "", Some("window.about".into()))?;
|
||||
native.add_item(app, &app_menu, "Preferences...", "", Some("setup.preferences".into()))?;
|
||||
native.add_item(app, &app_menu, "Session Info", "", Some("window.session_info".into()))?;
|
||||
native.add_item(app, &app_menu, "Session Audio Health", "", Some("window.audio_health".into()))?;
|
||||
app_menu.append(&PredefinedMenuItem::separator())?;
|
||||
@@ -94,8 +95,8 @@ impl NativeMenu {
|
||||
&& let Some(command) = &entry.command
|
||||
&& menus::item_state(app, &entry.path, Some(command)).0
|
||||
{
|
||||
if entry.path.is_empty() && command.starts_with("window.") {
|
||||
// The application menu's About / Session Info open their window (never close it).
|
||||
if entry.path.is_empty() && (command.starts_with("window.") || command == "setup.preferences") {
|
||||
// Application-menu window entries open their window rather than toggling it.
|
||||
let _ = app.run(command, serde_json::json!({"value": true}));
|
||||
} else {
|
||||
menus::invoke_menu(app, command, &entry.path);
|
||||
|
||||
@@ -17,9 +17,11 @@ pub(crate) fn on_main_thread() -> bool {
|
||||
unsafe { pthread_main_np() == 1 }
|
||||
}
|
||||
|
||||
/// True on the process's main thread: Rust names it "main", and the app runs its UI there (the
|
||||
/// rule `hostwin` and the VST3 host use). CLAP makes `clap.gui` main-thread only on every platform.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fn on_main_thread() -> bool {
|
||||
true
|
||||
std::thread::current().name() == Some("main")
|
||||
}
|
||||
|
||||
/// The windowing API of this platform.
|
||||
|
||||
@@ -150,7 +150,9 @@ mod tests {
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("soundcraft-clap-scan-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
// Created exclusively: a folder still there after the cleanup (someone else's) would
|
||||
// let a link inside it redirect the test's writes.
|
||||
std::fs::create_dir(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
mod common;
|
||||
|
||||
use soundcraft_dsp::Plugin;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const GAIN: &str = "clap:org.soundcraft.test.gain";
|
||||
|
||||
@@ -14,12 +15,31 @@ fn block(p: &mut Box<dyn Plugin>) -> Vec<Vec<f32>> {
|
||||
io
|
||||
}
|
||||
|
||||
/// The warnings logged, to tell which way the host went.
|
||||
static WARNINGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
|
||||
struct Warnings;
|
||||
|
||||
impl log::Log for Warnings {
|
||||
fn enabled(&self, m: &log::Metadata) -> bool {
|
||||
m.level() <= log::Level::Warn
|
||||
}
|
||||
fn log(&self, r: &log::Record) {
|
||||
if self.enabled(r.metadata()) {
|
||||
WARNINGS.lock().unwrap().push(r.args().to_string());
|
||||
}
|
||||
}
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// nextest lists custom-harness tests with `--list`; each binary here is one test.
|
||||
if std::env::args().any(|a| a == "--list") {
|
||||
println!("editor_main_thread: test");
|
||||
return;
|
||||
}
|
||||
log::set_logger(&Warnings).expect("logger");
|
||||
log::set_max_level(log::LevelFilter::Warn);
|
||||
common::fixture_dir();
|
||||
let mut p = soundcraft_clap_host::create(GAIN).expect("fixture");
|
||||
p.prepare(48_000.0, 64, 2);
|
||||
@@ -32,6 +52,26 @@ fn main() {
|
||||
// block and is reported (in SoundCraft units) by idle.
|
||||
let io = block(&mut p);
|
||||
assert!((io[0][10] - 0.25).abs() < 1e-6, "{}", io[0][10]);
|
||||
// Only the main thread drives the editor, on every platform (#901). Another thread, named or
|
||||
// not, is refused: it neither takes the edit idle reports nor closes or reopens the editor.
|
||||
for name in [None, Some("soundcraft-ui")] {
|
||||
let mut other = p.editor().expect("editor handle");
|
||||
let thread = match name {
|
||||
Some(n) => std::thread::Builder::new().name(n.to_string()),
|
||||
None => std::thread::Builder::new(),
|
||||
};
|
||||
let seen = thread
|
||||
.spawn(move || {
|
||||
let edits = other.idle();
|
||||
other.close();
|
||||
(edits, other.open().map_err(|e| e.contains("main thread")))
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("no panic");
|
||||
assert_eq!(seen, (Vec::new(), Err(true)), "{name:?}");
|
||||
assert!(ed.is_open(), "{name:?}");
|
||||
}
|
||||
assert_eq!(ed.idle(), vec![("7".to_string(), 0.25)]);
|
||||
assert!(ed.idle().is_empty(), "drained");
|
||||
ed.close();
|
||||
@@ -49,5 +89,17 @@ fn main() {
|
||||
assert!(ed.open().is_err());
|
||||
assert!(ed.idle().is_empty());
|
||||
ed.close();
|
||||
// #901: a plugin dropped on another thread with its editor open (an audio callback dropped
|
||||
// by the device's thread) does not destroy the editor there, clap.gui being main-thread only:
|
||||
// it warns and leaves it.
|
||||
let mut p = soundcraft_clap_host::create(GAIN).expect("fixture");
|
||||
p.prepare(48_000.0, 64, 2);
|
||||
let mut ed = p.editor().expect("editor handle");
|
||||
ed.open().expect("open on the main thread");
|
||||
std::thread::Builder::new().name("audio".into()).spawn(move || drop(p)).expect("spawn").join().expect("no panic");
|
||||
let left = "clap: editor still open while its plugin is destroyed off the main thread";
|
||||
assert!(WARNINGS.lock().unwrap().iter().any(|w| w == left), "{:?}", WARNINGS.lock().unwrap());
|
||||
assert!(!ed.is_open());
|
||||
assert!(ed.open().is_err());
|
||||
println!("editor_main_thread: ok");
|
||||
}
|
||||
|
||||
@@ -102,6 +102,8 @@ struct Fx {
|
||||
active: bool,
|
||||
processing: bool,
|
||||
gui_created: bool,
|
||||
/// The thread that created the GUI (the host's main thread).
|
||||
gui_thread: Option<std::thread::ThreadId>,
|
||||
gui_visible: bool,
|
||||
gui_edit_pending: bool,
|
||||
/// `clap.render` set the offline mode (wide fixtures only).
|
||||
@@ -130,7 +132,10 @@ unsafe extern "C" fn init(p: *const clap_plugin) -> bool {
|
||||
}
|
||||
|
||||
unsafe extern "C" fn destroy(p: *const clap_plugin) {
|
||||
assert!(!unsafe { fx(p) }.gui_created, "plugin destroyed with its GUI alive");
|
||||
let f = unsafe { fx(p) };
|
||||
// A host destroying the plugin off the GUI's thread can't destroy the GUI there (clap.gui is
|
||||
// main-thread only), so it may leave it; on the GUI's thread it must destroy it first.
|
||||
assert!(!f.gui_created || f.gui_thread != Some(std::thread::current().id()), "plugin destroyed with its GUI alive");
|
||||
let data = unsafe { (*p).plugin_data } as *mut Fx;
|
||||
drop(unsafe { Box::from_raw(data) });
|
||||
}
|
||||
@@ -492,6 +497,7 @@ unsafe extern "C" fn gui_create(p: *const clap_plugin, _api: *const c_char, floa
|
||||
let f = unsafe { fx(p) };
|
||||
assert!(floating && !f.gui_created, "create");
|
||||
f.gui_created = true;
|
||||
f.gui_thread = Some(std::thread::current().id());
|
||||
true
|
||||
}
|
||||
|
||||
@@ -638,6 +644,7 @@ unsafe extern "C" fn factory_create(_f: *const clap_plugin_factory, host: *const
|
||||
active: false,
|
||||
processing: false,
|
||||
gui_created: false,
|
||||
gui_thread: None,
|
||||
gui_visible: false,
|
||||
gui_edit_pending: false,
|
||||
offline: false,
|
||||
|
||||
@@ -215,14 +215,12 @@ fn state_reader_reads_while_another_thread_processes() {
|
||||
#[test]
|
||||
fn editors_refuse_to_open_off_the_main_thread() {
|
||||
fixture_dir();
|
||||
// Test threads are never the process main thread.
|
||||
// Test threads are never the process main thread, on any platform (#901).
|
||||
let mut p = soundcraft_clap_host::create(GAIN).unwrap();
|
||||
let mut ed = p.editor().expect("the gain fixture has clap.gui");
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(ed.open().unwrap_err().contains("main thread"));
|
||||
assert!(p.open_editor().is_err());
|
||||
assert!(!ed.is_open());
|
||||
}
|
||||
assert!(ed.open().unwrap_err().contains("main thread"));
|
||||
assert!(p.open_editor().is_err());
|
||||
assert!(!ed.is_open());
|
||||
ed.close();
|
||||
p.close_editor();
|
||||
}
|
||||
|
||||
+144
-11
@@ -212,6 +212,11 @@ impl Autosave {
|
||||
let audio_dir = self.dir.join("Audio Files");
|
||||
let mut s = session.clone();
|
||||
let mut copies = BTreeMap::new();
|
||||
// Copies made in this write, by the audio they hold: sources sharing one decoded buffer
|
||||
// (a session may name one file under many ids) share one file.
|
||||
let mut written: BTreeMap<*const SourceAudio, String> = BTreeMap::new();
|
||||
// Copies still to make, written once the size is checked; their numbers are taken then too.
|
||||
let (mut fresh, mut next) = (Vec::new(), self.next);
|
||||
for src in &mut s.sources {
|
||||
let file = if Path::new(&src.path).is_absolute() { Some(PathBuf::from(&src.path)) } else { base.as_ref().map(|b| b.join(&src.path)) };
|
||||
let audio = s.pool.get(src.id);
|
||||
@@ -222,26 +227,37 @@ impl Autosave {
|
||||
continue;
|
||||
}
|
||||
let Some(audio) = audio else { continue };
|
||||
let name = match self.copies.remove(&src.id) {
|
||||
Some((copy, name)) if copy.upgrade().is_some_and(|a| Arc::ptr_eq(&a, audio)) => name,
|
||||
let name = match self.copies.get(&src.id) {
|
||||
Some((copy, name)) if copy.upgrade().is_some_and(|a| Arc::ptr_eq(&a, audio)) => name.clone(),
|
||||
_ if written.contains_key(&Arc::as_ptr(audio)) => written.get(&Arc::as_ptr(audio)).cloned().unwrap_or_default(),
|
||||
_ => {
|
||||
let name = format!("{} {}.wav", sanitize_name(&src.name), self.next);
|
||||
self.next += 1;
|
||||
let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None };
|
||||
let bytes = soundcraft_audio_io::encode(&audio.buffer, &opts).map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
create_folder(&audio_dir).and_then(|()| write_synced(&audio_dir.join(&name), &bytes)).map_err(|err| io_error(&audio_dir, err))?;
|
||||
let name = format!("{} {}.wav", sanitize_name(&src.name), next);
|
||||
next += 1;
|
||||
fresh.push((name.clone(), Arc::clone(audio)));
|
||||
name
|
||||
}
|
||||
};
|
||||
src.path = audio_dir.join(&name).to_string_lossy().into_owned();
|
||||
src.unsaved = true;
|
||||
written.insert(Arc::as_ptr(audio), name.clone());
|
||||
copies.insert(src.id, (Arc::downgrade(audio), name));
|
||||
}
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
// An autosave too large to recover is not written, nor its new copies: the last autosave
|
||||
// stays as it was, and the failure is reported (#892).
|
||||
crate::io::session_size("the autosave", text.len() as u64, true)?;
|
||||
self.next = next;
|
||||
for (name, audio) in &fresh {
|
||||
let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None };
|
||||
let bytes = soundcraft_audio_io::encode(&audio.buffer, &opts).map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
create_folder(&audio_dir).and_then(|()| write_synced(&audio_dir.join(name), &bytes)).map_err(|err| io_error(&audio_dir, err))?;
|
||||
}
|
||||
write_atomically(&self.dir.join(ORIGIN), origin.unwrap_or_default().as_bytes())?;
|
||||
write_atomically(&self.dir.join(SESSION), text.as_bytes())?;
|
||||
for (_, name) in std::mem::replace(&mut self.copies, copies).into_values() {
|
||||
let _ = std::fs::remove_file(audio_dir.join(name));
|
||||
if !self.copies.values().any(|(_, kept)| *kept == name) {
|
||||
let _ = std::fs::remove_file(audio_dir.join(name));
|
||||
}
|
||||
}
|
||||
if let Some(r) = recording {
|
||||
let plan = serde_json::to_string(r).map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
@@ -290,9 +306,7 @@ pub fn leftovers(root: &Path) -> Vec<Leftover> {
|
||||
drop(lock);
|
||||
match saved {
|
||||
Ok(saved) if recording || origin_saved.is_none_or(|o| saved > o) => {
|
||||
let text = std::fs::read_to_string(dir.join(SESSION)).unwrap_or_default();
|
||||
let named = serde_json::from_str::<serde_json::Value>(&text).ok().and_then(|v| v.get("name")?.as_str().map(str::to_string));
|
||||
let name = named.unwrap_or_else(|| dir.file_name().unwrap_or_default().to_string_lossy().into_owned());
|
||||
let name = saved_name(&dir.join(SESSION)).unwrap_or_else(|| dir.file_name().unwrap_or_default().to_string_lossy().into_owned());
|
||||
out.push(Leftover { dir, name, origin, saved, recording });
|
||||
}
|
||||
_ => {
|
||||
@@ -304,6 +318,21 @@ pub fn leftovers(root: &Path) -> Vec<Leftover> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The name of the session saved in `file`, read without keeping the rest of it; `None` when the
|
||||
/// file is missing, not a session, or too large to open (#892).
|
||||
fn saved_name(file: &Path) -> Option<String> {
|
||||
use std::io::Read as _;
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Named {
|
||||
name: String,
|
||||
}
|
||||
if std::fs::metadata(file).ok()?.len() > crate::io::session_limit() {
|
||||
return None;
|
||||
}
|
||||
let read = std::fs::File::open(file).ok()?.take(crate::io::session_limit());
|
||||
serde_json::from_reader::<_, Named>(std::io::BufReader::new(read)).ok().map(|n| n.name)
|
||||
}
|
||||
|
||||
/// Open `left` as an unsaved version of the session it came from, so Save writes it back there,
|
||||
/// with the takes of a recording that never finished placed as Stop would have. Returns the
|
||||
/// media that couldn't be loaded.
|
||||
@@ -451,6 +480,27 @@ mod tests {
|
||||
use soundcraft_audio_io::AudioBuffer;
|
||||
use soundcraft_model::{ChannelFormat, Clip, TrackKind};
|
||||
|
||||
/// Recovery loads document edits without re-enabling live inputs from an autosave.
|
||||
#[test]
|
||||
fn recovered_live_input_states_start_disabled() {
|
||||
let root = folder("live-input-recovery");
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({})).unwrap();
|
||||
let track = e.session().tracks[0].id;
|
||||
e.execute("mix.record_arm", &json!({"tracks": [track.0], "value": true})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [track.0], "value": true})).unwrap();
|
||||
e.execute("mix.volume", &json!({"tracks": [track.0], "db": -6.0})).unwrap();
|
||||
let mut autosave = Autosave::create(&root, "Live inputs").unwrap();
|
||||
autosave.write(e.session(), None, None).unwrap();
|
||||
drop(autosave);
|
||||
let mut recovered = Engine::default();
|
||||
recover(&mut recovered, &leftovers(&root)[0]).unwrap();
|
||||
let mixer = &recovered.session().track(track).unwrap().mixer;
|
||||
assert!(!mixer.record_arm && !mixer.input_monitor);
|
||||
assert_eq!(mixer.volume_db, -6.0);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -507,6 +557,25 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources_sharing_one_buffer_share_one_copy() {
|
||||
let dir = folder("autosave-aliases");
|
||||
let mut e = Engine::default();
|
||||
record(&mut e, 0.5);
|
||||
// Nine more source ids over the same decoded audio, as a session file may declare.
|
||||
let s = e.session_mut();
|
||||
let (src, audio) = (s.sources[0].clone(), s.pool.get(s.sources[0].id).cloned().unwrap());
|
||||
for _ in 0..9 {
|
||||
let id = SourceId(s.alloc());
|
||||
s.sources.push(soundcraft_model::Source { id, ..src.clone() });
|
||||
s.pool.insert(id, audio.clone());
|
||||
}
|
||||
let mut a = Autosave::create(&dir.join("Autosave"), "Song").unwrap();
|
||||
a.write(e.session(), None, None).unwrap();
|
||||
assert_eq!(std::fs::read_dir(a.dir.join("Audio Files")).unwrap().count(), 1, "one file for the ten ids");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_take_recorded_after_undo_gets_its_own_copy() {
|
||||
let dir = folder("autosave-undo");
|
||||
@@ -673,6 +742,70 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A test folder, removed when the test ends, passed or not.
|
||||
struct Gone(PathBuf);
|
||||
|
||||
impl Drop for Gone {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_autosave_too_large_to_open_writes_nothing_and_keeps_the_last() {
|
||||
// #892, with the limit lowered for this test: a refused autosave makes no audio copies
|
||||
// and keeps the last autosave and its copies as they were.
|
||||
let dir = Gone(folder("autosave-too-large"));
|
||||
let mut e = Engine::default();
|
||||
record(&mut e, 0.5);
|
||||
let mut a = Autosave::create(&dir.0.join("Autosave"), "Song").unwrap();
|
||||
a.write(e.session(), None, None).unwrap();
|
||||
let state = |a: &Autosave| {
|
||||
let mut files: Vec<String> =
|
||||
std::fs::read_dir(a.dir.join("Audio Files")).unwrap().map(|f| f.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
files.sort();
|
||||
let copies: Vec<(SourceId, String)> = a.copies.iter().map(|(id, (_, name))| (*id, name.clone())).collect();
|
||||
(files, copies, a.next, std::fs::read_to_string(a.dir.join(SESSION)).unwrap())
|
||||
};
|
||||
let before = state(&a);
|
||||
record(&mut e, 0.25);
|
||||
{
|
||||
let _limit = crate::io::SessionLimit::set(before.3.len() as u64);
|
||||
for _ in 0..2 {
|
||||
let err = a.write(e.session(), None, None).unwrap_err().to_string();
|
||||
assert!(err.starts_with("the autosave is too large to save"), "{err}");
|
||||
assert!(state(&a) == before);
|
||||
}
|
||||
// The writer thread reports it as it reports any failed autosave.
|
||||
let failure = Arc::new(Mutex::new(None));
|
||||
let pending = Some((e.session_arc(), None, None));
|
||||
let mut w = Writer { root: dir.0.join("Writer"), failure: Arc::clone(&failure), folder: None, pending, last: None, written: Ok(()) };
|
||||
w.write_pending();
|
||||
let reported = failure.lock().unwrap().take().unwrap_or_default();
|
||||
assert!(reported.starts_with("the autosave is too large to save"), "{reported}");
|
||||
}
|
||||
a.write(e.session(), None, None).unwrap();
|
||||
let after = state(&a);
|
||||
assert_eq!((after.0.len(), after.1.len()), (2, 2));
|
||||
assert!(after.0.contains(&before.0[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leftover_is_named_from_its_session_without_reading_a_huge_one() {
|
||||
// #892: the name is read on its own, and an autosave too large to open is not read.
|
||||
let dir = Gone(folder("autosave-names"));
|
||||
std::fs::create_dir_all(&dir.0).unwrap();
|
||||
let file = dir.0.join(SESSION);
|
||||
let s = Session { name: "Song".into(), ..Session::default() };
|
||||
std::fs::write(&file, s.to_json().unwrap()).unwrap();
|
||||
assert_eq!(saved_name(&file).as_deref(), Some("Song"));
|
||||
std::fs::write(&file, r#"{"name": 5}"#).unwrap();
|
||||
assert_eq!(saved_name(&file), None);
|
||||
std::fs::File::create(&file).unwrap().set_len(crate::io::MAX_SESSION_BYTES + 1).unwrap();
|
||||
assert_eq!(saved_name(&file), None);
|
||||
assert_eq!(saved_name(&dir.0.join("none")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sessions_started_together_get_folders_of_their_own() {
|
||||
// #579: the folder name has millisecond resolution, so two sessions created back to back
|
||||
|
||||
@@ -347,7 +347,10 @@ pub fn clip_id(p: &Value, cmd: &str) -> Result<ClipId> {
|
||||
|
||||
pub fn clip_ids_param(e: &Engine, p: &Value) -> Vec<ClipId> {
|
||||
if let Some(arr) = p.get("clips").and_then(Value::as_array) {
|
||||
return arr.iter().filter_map(Value::as_u64).map(ClipId).collect();
|
||||
// Each clip once, in the order given: a repeated id would otherwise be processed (and,
|
||||
// for a render, re-rendered into another source) once per repeat.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
return arr.iter().filter_map(Value::as_u64).map(ClipId).filter(|id| seen.insert(*id)).collect();
|
||||
}
|
||||
if let Some(n) = p.get("clip").and_then(Value::as_u64) {
|
||||
return vec![ClipId(n)];
|
||||
|
||||
@@ -425,7 +425,7 @@ fn quantize_to_grid(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let ids = clip_ids_param(e, p);
|
||||
let s = e.session();
|
||||
let moves: Vec<(soundcraft_model::ClipId, i64)> =
|
||||
ids.iter().filter_map(|id| s.find_clip(*id).map(|(_, c)| (*id, crate::edit::grid_delta(s, c, 0, false)))).collect();
|
||||
ids.iter().filter_map(|id| s.find_clip(*id).map(|(_, c)| (*id, crate::edit::grid_delta(s, c, 0, false, &ids)))).collect();
|
||||
let s = e.session_mut();
|
||||
for (id, d) in &moves {
|
||||
crate::edit::move_clips(s, &[*id], *d, &[]);
|
||||
|
||||
@@ -301,6 +301,7 @@ fn cut_copy(e: &mut Engine, p: &Value, cut: bool, id: &str) -> Result<Value> {
|
||||
cut_track(s, *t, range, sh, follow);
|
||||
}
|
||||
s.edit.selection = soundcraft_time::Range::point(range.start);
|
||||
cb.cut_from = Some(range.start);
|
||||
}
|
||||
let n: usize = cb.tracks.iter().map(Vec::len).sum();
|
||||
e.clipboard = cb;
|
||||
@@ -328,6 +329,7 @@ pub(super) fn clipboard_for_paste(e: &mut Engine) -> Clipboard {
|
||||
cb
|
||||
}
|
||||
|
||||
/// Pastes the clipboard at an explicit position or at the current edit insertion point.
|
||||
fn paste(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "edit.paste", p)?;
|
||||
let given = position_param(e, "edit.paste", p, "at")?;
|
||||
@@ -335,9 +337,10 @@ fn paste(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let s = e.session();
|
||||
let at = match given {
|
||||
Some(at) => at,
|
||||
None if s.edit.edit_mode == EditMode::GridRelative => {
|
||||
s.edit.grid.line_at_or_before(s.edit.selection.start, s.sample_rate, &s.tempo, s.frame_rate).saturating_add(cb.grid_offset)
|
||||
None if s.edit.edit_mode == EditMode::GridRelative && s.edit.selection.is_empty() && cb.cut_from == Some(s.edit.selection.start) => {
|
||||
s.edit.selection.start
|
||||
}
|
||||
None if s.edit.edit_mode == EditMode::GridRelative => s.grid_line_at_or_before(s.edit.selection.start).saturating_add(cb.grid_offset),
|
||||
None => s.edit.selection.start,
|
||||
};
|
||||
let sh = shuffle(s) && !cb.automation_only;
|
||||
@@ -668,11 +671,16 @@ fn separate(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"separated": n}))
|
||||
}
|
||||
|
||||
/// Separates selected clips at every active Grid boundary in the requested range.
|
||||
fn separate_on_grid(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "edit.separate_on_grid", p)?;
|
||||
let r = range_param(e, "edit.separate_on_grid", p)?;
|
||||
let s = e.session_mut();
|
||||
let lines = s.edit.grid.lines(r.start, r.end, s.sample_rate, &s.tempo, s.frame_rate, 10_000);
|
||||
let max = if s.edit.grid_clips_markers { usize::MAX } else { 10_001 };
|
||||
let lines = s.grid_lines(r.start, r.end, max);
|
||||
if lines.len() > 10_000 {
|
||||
return Err(bad("edit.separate_on_grid", "the range contains more than 10,000 grid boundaries"));
|
||||
}
|
||||
let mut n = 0;
|
||||
for t in &tracks {
|
||||
for at in &lines {
|
||||
@@ -956,6 +964,7 @@ fn nudge(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"moved": n, "by": step}))
|
||||
}
|
||||
|
||||
/// Same-track placement at the existing start is a no-op; quantization is a separate command.
|
||||
fn move_clips(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let ids = clip_ids_param(e, p);
|
||||
if ids.is_empty() {
|
||||
@@ -978,17 +987,21 @@ fn move_clips(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mode = s.edit.edit_mode;
|
||||
let delta = match first {
|
||||
Some(c) if mode.is_grid() && p.get("to").is_some() => ops::grid_delta(s, c, delta, mode == EditMode::GridRelative),
|
||||
Some(_) if mode.is_grid() && p.get("to").is_some() && delta == 0 && dest.iter().all(|(from, to)| from == to) => 0,
|
||||
Some(c) if mode.is_grid() && p.get("to").is_some() => ops::grid_delta(s, c, delta, mode == EditMode::GridRelative, &ids),
|
||||
_ => delta,
|
||||
};
|
||||
let effective_delta = first.map_or(delta, |clip| delta.max(clip.start.saturating_neg()));
|
||||
let s = e.session_mut();
|
||||
let n = if mode == EditMode::Shuffle {
|
||||
ops::shuffle_clips(s, &ids, delta, &dest).map_err(|why| bad("edit.move_clips", why))?
|
||||
} else if effective_delta == 0 && dest.iter().all(|(from, to)| from == to) {
|
||||
0
|
||||
} else {
|
||||
ops::move_clips(s, &ids, delta, &dest)
|
||||
ops::move_clips(s, &ids, effective_delta, &dest)
|
||||
};
|
||||
s.edit.selected_clips = ids;
|
||||
Ok(json!({"moved": n, "by": delta}))
|
||||
Ok(json!({"moved": n, "by": if mode == EditMode::Shuffle { delta } else { effective_delta }}))
|
||||
}
|
||||
|
||||
fn trim_clip(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -45,6 +45,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
s.sources.clear();
|
||||
s.videos.clear();
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
// A template too large to open is not saved (#892).
|
||||
crate::io::session_size(file.display(), text.len() as u64, true)?;
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
crate::io::write_file(&file.to_string_lossy(), text.as_bytes())?;
|
||||
} else {
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::{Engine, EngineError, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{AutoParam, AutomationMode, INSERT_SLOTS, Insert, SEND_SLOTS, SendSlot, Session, TrackId};
|
||||
|
||||
/// Commands for mixer controls, with live input toggles kept outside document history.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("mix.volume", "Set Volume", [], None, "{tracks?, db: -144..12 | delta_db}", has_selection, volume),
|
||||
@@ -42,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
Ok(json!({}))
|
||||
}),
|
||||
cmd!("mix.record_arm", "Record Enable", [], Some("Shift+R"), "{tracks?, value?: bool}", has_selection, |e, p| toggle(
|
||||
cmd!(noundo "mix.record_arm", "Record Enable", [], Some("Shift+R"), "{tracks?, value?: bool}", has_selection, |e, p| toggle_runtime(
|
||||
e,
|
||||
p,
|
||||
"mix.record_arm",
|
||||
@@ -51,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}),
|
||||
|tr| tr.mixer.record_arm
|
||||
)),
|
||||
cmd!("mix.input_monitor", "Input Monitoring", [], Some("Shift+I"), "{tracks?, value?: bool}", has_selection, |e, p| toggle(
|
||||
cmd!(noundo "mix.input_monitor", "Input Monitoring", [], Some("Shift+I"), "{tracks?, value?: bool}", has_selection, |e, p| toggle_runtime(
|
||||
e,
|
||||
p,
|
||||
"mix.input_monitor",
|
||||
@@ -218,6 +219,23 @@ fn toggle(e: &mut Engine, p: &Value, cmd: &str, set: fn(&mut Session, TrackId, b
|
||||
Ok(json!({"value": v}))
|
||||
}
|
||||
|
||||
/// Toggle live input flags without marking the saved document as changed.
|
||||
fn toggle_runtime(
|
||||
e: &mut Engine,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
set: fn(&mut Session, TrackId, bool),
|
||||
get: fn(&soundcraft_model::Track) -> bool,
|
||||
) -> Result<Value> {
|
||||
let tracks = tracks_required(e, cmd, p)?;
|
||||
let s = e.runtime_session_mut();
|
||||
let v = p.get("value").and_then(Value::as_bool).unwrap_or_else(|| !tracks.iter().all(|t| s.track(*t).is_some_and(get)));
|
||||
for t in &tracks {
|
||||
set(s, *t, v);
|
||||
}
|
||||
Ok(json!({"value": v}))
|
||||
}
|
||||
|
||||
fn volume(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "mix.volume", p)?;
|
||||
let abs = p.get("db").and_then(Value::as_f64);
|
||||
|
||||
@@ -378,3 +378,109 @@ fn clip_gain_to_volume_with_a_large_envelope_stays_fast() {
|
||||
let lane = e.session().track(t).unwrap().lane(&AutoParam::Volume).unwrap();
|
||||
assert!(lane.points.len() as i64 >= n);
|
||||
}
|
||||
|
||||
/// Live input toggles stay outside document history in both enabled and disabled states.
|
||||
#[test]
|
||||
fn live_input_states_are_transient_and_survive_document_history() {
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({})).unwrap();
|
||||
let track = e.session().tracks[0].id;
|
||||
e.mark_clean();
|
||||
let history = e.undo_history();
|
||||
|
||||
e.execute("mix.record_arm", &json!({"tracks": [track.0], "value": true})).unwrap();
|
||||
e.execute("track.set_record_to_input_only", &json!({})).unwrap();
|
||||
let mixer = &e.session().track(track).unwrap().mixer;
|
||||
assert!(mixer.record_arm && mixer.input_monitor);
|
||||
assert!(!e.is_dirty(), "live input state is not a document change");
|
||||
assert_eq!(e.undo_history(), history, "live input state has no Undo entry");
|
||||
|
||||
// A later document edit captures a full Session snapshot. Undoing or redoing it must not
|
||||
// resurrect the live state that happened to be present when that snapshot was taken.
|
||||
e.execute("mix.volume", &json!({"tracks": [track.0], "db": -6.0})).unwrap();
|
||||
e.execute("mix.record_arm", &json!({"tracks": [track.0], "value": false})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [track.0], "value": false})).unwrap();
|
||||
assert!(e.is_dirty());
|
||||
|
||||
assert!(e.undo());
|
||||
let mixer = &e.session().track(track).unwrap().mixer;
|
||||
assert!(!mixer.record_arm && !mixer.input_monitor);
|
||||
assert!(!e.is_dirty(), "undo returned to the saved document");
|
||||
|
||||
assert!(e.redo());
|
||||
let mixer = &e.session().track(track).unwrap().mixer;
|
||||
assert!(!mixer.record_arm && !mixer.input_monitor);
|
||||
assert!(e.is_dirty());
|
||||
|
||||
// Live states that are enabled after another document edit survive both directions too.
|
||||
e.execute("mix.volume", &json!({"tracks": [track.0], "db": -12.0})).unwrap();
|
||||
e.execute("mix.record_arm", &json!({"tracks": [track.0], "value": true})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [track.0], "value": true})).unwrap();
|
||||
|
||||
assert!(e.undo());
|
||||
let mixer = &e.session().track(track).unwrap().mixer;
|
||||
assert!(mixer.record_arm && mixer.input_monitor);
|
||||
|
||||
assert!(e.redo());
|
||||
let mixer = &e.session().track(track).unwrap().mixer;
|
||||
assert!(mixer.record_arm && mixer.input_monitor);
|
||||
}
|
||||
|
||||
/// Returning to a saved point stays clean with independently enabled live flags on each track.
|
||||
#[test]
|
||||
fn live_input_states_keep_saved_history_points_clean() {
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({"count": 2})).unwrap();
|
||||
let (a, b) = (e.session().tracks[0].id, e.session().tracks[1].id);
|
||||
e.mark_clean();
|
||||
e.execute("mix.volume", &json!({"tracks": [a.0], "db": -6.0})).unwrap();
|
||||
e.execute("mix.record_arm", &json!({"tracks": [a.0], "value": true})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [b.0], "value": true})).unwrap();
|
||||
assert!(e.undo());
|
||||
assert!(!e.is_dirty(), "live flags cannot dirty the saved point reached by Undo");
|
||||
for redo in [true, false, true] {
|
||||
assert!(if redo { e.redo() } else { e.undo() });
|
||||
let a = &e.session().track(a).unwrap().mixer;
|
||||
let b = &e.session().track(b).unwrap().mixer;
|
||||
assert!(a.record_arm && !a.input_monitor);
|
||||
assert!(!b.record_arm && b.input_monitor);
|
||||
assert_eq!(e.is_dirty(), redo);
|
||||
}
|
||||
e.mark_clean();
|
||||
e.execute("mix.record_arm", &json!({"tracks": [a.0], "value": false})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [b.0], "value": false})).unwrap();
|
||||
assert!(!e.is_dirty());
|
||||
assert!(e.undo());
|
||||
assert!(e.is_dirty());
|
||||
assert!(e.redo());
|
||||
assert!(!e.is_dirty(), "Redo to a saved armed snapshot stays clean after disarming");
|
||||
}
|
||||
|
||||
/// Restoring a missing track never resurrects its historical arm or monitoring flags.
|
||||
#[test]
|
||||
fn live_input_states_of_restored_tracks_start_disabled() {
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({"count": 2})).unwrap();
|
||||
let (a, b) = (e.session().tracks[0].id, e.session().tracks[1].id);
|
||||
e.execute("mix.record_arm", &json!({"tracks": [a.0], "value": true})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [b.0], "value": true})).unwrap();
|
||||
e.execute("track.delete", &json!({"tracks": [a.0]})).unwrap();
|
||||
assert!(e.undo());
|
||||
let mixer = &e.session().track(a).unwrap().mixer;
|
||||
assert!(!mixer.record_arm && !mixer.input_monitor);
|
||||
assert!(e.session().track(b).unwrap().mixer.input_monitor);
|
||||
assert!(e.redo());
|
||||
assert!(e.undo());
|
||||
assert!(!e.session().track(a).unwrap().mixer.record_arm);
|
||||
|
||||
e.execute("track.new", &json!({})).unwrap();
|
||||
let c = e.session().tracks.last().unwrap().id;
|
||||
e.execute("mix.record_arm", &json!({"tracks": [c.0], "value": true})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"tracks": [c.0], "value": true})).unwrap();
|
||||
assert!(e.undo());
|
||||
assert!(e.session().track(c).is_none());
|
||||
assert!(e.redo());
|
||||
let mixer = &e.session().track(c).unwrap().mixer;
|
||||
assert!(!mixer.record_arm && !mixer.input_monitor);
|
||||
assert!(e.session().track(b).unwrap().mixer.input_monitor);
|
||||
}
|
||||
|
||||
@@ -472,7 +472,7 @@ fn midi_inputs(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
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_text(&path)?;
|
||||
let text_v = crate::io::read_session_text(&path)?;
|
||||
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());
|
||||
|
||||
@@ -100,8 +100,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("track.bounce", "Bounce...", ["Track"], Some("Cmd+Alt+Shift+B"), "{tracks?}", has_selection, commit),
|
||||
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!("track.set_record_to_input_only", "Set Record Tracks to Input Only", ["Track"], Some("Alt+K"), "{}", always, |e, _| {
|
||||
let s = e.session_mut();
|
||||
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;
|
||||
for t in &mut s.tracks {
|
||||
if t.mixer.record_arm {
|
||||
|
||||
@@ -267,6 +267,7 @@ fn save_preset(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"path": path, "track": first}))
|
||||
}
|
||||
|
||||
/// Load persistent mixer settings while retaining destination routing and live input flags.
|
||||
fn load_preset(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "track.load_preset";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(id, "`path` required"))?.to_string();
|
||||
@@ -283,15 +284,17 @@ fn load_preset(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let s = e.session_mut();
|
||||
for t in &tracks {
|
||||
if let Some(tr) = s.track_mut(*t) {
|
||||
// Routing is session-specific: keep the track's own input/output, VCA and arm state.
|
||||
let keep = (tr.mixer.input.clone(), tr.mixer.output.clone(), tr.mixer.vca, tr.mixer.record_arm, tr.mixer.pan.clone());
|
||||
// Routing and live input state are track-specific: a preset must not replace them.
|
||||
let keep =
|
||||
(tr.mixer.input.clone(), tr.mixer.output.clone(), tr.mixer.vca, tr.mixer.record_arm, tr.mixer.input_monitor, tr.mixer.pan.clone());
|
||||
tr.mixer = mixer.clone();
|
||||
tr.mixer.input = keep.0;
|
||||
tr.mixer.output = keep.1;
|
||||
tr.mixer.vca = keep.2;
|
||||
tr.mixer.record_arm = keep.3;
|
||||
if tr.mixer.pan.len() != keep.4.len() {
|
||||
tr.mixer.pan = keep.4;
|
||||
tr.mixer.input_monitor = keep.4;
|
||||
if tr.mixer.pan.len() != keep.5.len() {
|
||||
tr.mixer.pan = keep.5;
|
||||
}
|
||||
if tr.kind == TrackKind::Instrument && instrument.is_some() {
|
||||
tr.instrument = instrument.clone();
|
||||
@@ -602,6 +605,7 @@ mod tests {
|
||||
assert_eq!(e.session().track(pad).unwrap().folder, Some(verb));
|
||||
}
|
||||
|
||||
/// A preset transfers persistent mix settings without replacing live destination states.
|
||||
#[test]
|
||||
fn preset_round_trip() {
|
||||
let dir = std::env::temp_dir().join(format!("sc-preset-{}", std::process::id()));
|
||||
@@ -611,10 +615,13 @@ mod tests {
|
||||
e.execute("edit.select", &json!({"tracks": ["Bass"]})).unwrap();
|
||||
e.execute("track.save_preset", &json!({"path": path})).unwrap();
|
||||
e.execute("edit.select", &json!({"tracks": ["Hats"]})).unwrap();
|
||||
e.execute("mix.record_arm", &json!({"value": true})).unwrap();
|
||||
e.execute("mix.input_monitor", &json!({"value": true})).unwrap();
|
||||
e.execute("track.load_preset", &json!({"path": path})).unwrap();
|
||||
let hats = e.session().track_by_name("Hats").unwrap();
|
||||
assert_eq!(hats.mixer.inserts[0].as_ref().map(|i| i.plugin.as_str()), Some("compressor"));
|
||||
assert_eq!(hats.mixer.volume_db, -5.0);
|
||||
assert!(hats.mixer.record_arm && hats.mixer.input_monitor, "loading a preset keeps live input state");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
+166
-13
@@ -3,9 +3,9 @@ use super::{CommandSpec, always, bad, bool_or, f32_or, f64_or, i64_or, position_
|
||||
|
||||
use crate::{Engine, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_time::TimeFormat;
|
||||
use soundcraft_time::{GridValue, MAX_POSITION, NoteValue};
|
||||
use soundcraft_time::{FeetFramesValue, GridScale, GridValue, MAX_POSITION, NoteValue, TimeFormat, TimecodeValue};
|
||||
|
||||
/// Returns commands that control saved view, counter, Grid, and Nudge state.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(view "view.zoom_in", "Zoom In", [], Some("Cmd+]"), "{}", always, |e, _| zoom(e, 0.5, None)),
|
||||
@@ -65,7 +65,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(noundo "view.ruler", "Rulers", ["View", "Rulers"], None, "{ruler: bars_beats|min_secs|timecode|feet_frames|samples|tempo|meter|markers|key|chords, visible?: bool}", always, ruler),
|
||||
cmd!(noundo "view.main_counter", "Main Counter", ["View", "Main Counter"], None, "{format: bars_beats|min_secs|timecode|feet_frames|samples}", always, |e, p| {
|
||||
let f = str_param(p, "format").and_then(TimeFormat::from_id).ok_or_else(|| bad("view.main_counter", "unknown format"))?;
|
||||
e.session_mut().edit.main_counter = f;
|
||||
let edit = &mut e.session_mut().edit;
|
||||
edit.main_counter = f;
|
||||
let scale = grid_scale(f);
|
||||
if edit.grid_follow_main && edit.grid.scale() != scale {
|
||||
edit.grid = GridValue::for_scale(scale);
|
||||
}
|
||||
if edit.grid_follow_main {
|
||||
edit.grid_clips_markers = false;
|
||||
}
|
||||
if edit.nudge_follow_main && edit.nudge.scale() != scale {
|
||||
edit.nudge = GridValue::for_scale(scale);
|
||||
}
|
||||
Ok(json!({"format": f}))
|
||||
}),
|
||||
cmd!(noundo "view.sub_counter", "Sub Counter", [], None, "{format?: … | null}", always, |e, p| {
|
||||
@@ -73,23 +84,58 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
e.session_mut().edit.sub_counter = f;
|
||||
Ok(json!({"format": f}))
|
||||
}),
|
||||
cmd!(noundo "view.grid", "Grid Value", [], Some("Shift+=/-"), "{value: '1/16' | '1 bar' | '1/8t' | '1/4.' | {seconds} | {frames} | {samples}, or step: ±n values larger or smaller; lines?: bool}", always, |e, p| {
|
||||
let g = value_or_step(p, e.session().edit.grid).ok_or_else(|| bad("view.grid", "unknown grid value"))?;
|
||||
cmd!(noundo "view.grid", "Grid Value", [], Some("Shift+=/-"), "{value?, step?, format?: bars_beats|min_secs|timecode|feet_frames|samples|clips_markers, follow_main?: bool, lines?: bool}", always, |e, p| {
|
||||
let current = e.session().edit.grid;
|
||||
let requested_scale = str_param(p, "format").and_then(GridScale::from_id);
|
||||
let mut g = requested_grid_value(p, current).ok_or_else(|| bad("view.grid", "unknown grid value or format"))?;
|
||||
let lines = p.get("lines").and_then(Value::as_bool);
|
||||
let follow = p.get("follow_main").and_then(Value::as_bool);
|
||||
if follow == Some(true) {
|
||||
let scale = grid_scale(e.session().edit.main_counter);
|
||||
if g.scale() != scale {
|
||||
g = GridValue::for_scale(scale);
|
||||
}
|
||||
}
|
||||
let s = e.session_mut();
|
||||
s.edit.grid = g;
|
||||
if p.get("value").is_some() || p.get("step").is_some() {
|
||||
s.edit.grid_clips_markers = false;
|
||||
}
|
||||
if let Some(scale) = requested_scale {
|
||||
s.edit.grid_clips_markers = scale == GridScale::ClipsMarkers;
|
||||
}
|
||||
if follow == Some(true) {
|
||||
s.edit.grid_clips_markers = false;
|
||||
}
|
||||
s.edit.grid_follow_main = follow.unwrap_or(
|
||||
s.edit.grid_follow_main && !s.edit.grid_clips_markers && g.scale() == grid_scale(s.edit.main_counter),
|
||||
);
|
||||
if let Some(l) = lines { s.edit.grid_lines = l }
|
||||
Ok(json!({"grid": g.label()}))
|
||||
let format = if s.edit.grid_clips_markers { GridScale::ClipsMarkers } else { g.scale() };
|
||||
Ok(json!({"grid": g.label(), "format": format.id(), "follow_main": s.edit.grid_follow_main}))
|
||||
}),
|
||||
cmd!(noundo "view.grid_lines", "Show Grid Lines", [], None, "{value?: bool}", always, |e, p| {
|
||||
let s = e.session_mut();
|
||||
s.edit.grid_lines = p.get("value").and_then(Value::as_bool).unwrap_or(!s.edit.grid_lines);
|
||||
Ok(json!({"value": s.edit.grid_lines}))
|
||||
}),
|
||||
cmd!(noundo "view.nudge", "Nudge Value", [], Some("Alt+Shift+=/-"), "{value or step: like grid}", always, |e, p| {
|
||||
let g = value_or_step(p, e.session().edit.nudge).ok_or_else(|| bad("view.nudge", "unknown nudge value"))?;
|
||||
e.session_mut().edit.nudge = g;
|
||||
Ok(json!({"nudge": g.label()}))
|
||||
cmd!(noundo "view.nudge", "Nudge Value", [], Some("Alt+Shift+=/-"), "{value?, step?, format?: bars_beats|min_secs|timecode|feet_frames|samples, follow_main?: bool}", always, |e, p| {
|
||||
let current = e.session().edit.nudge;
|
||||
if str_param(p, "format").and_then(GridScale::from_id) == Some(GridScale::ClipsMarkers) {
|
||||
return Err(bad("view.nudge", "Clips/Markers is available only for Grid"));
|
||||
}
|
||||
let mut g = requested_grid_value(p, current).ok_or_else(|| bad("view.nudge", "unknown nudge value or format"))?;
|
||||
let follow = p.get("follow_main").and_then(Value::as_bool);
|
||||
if follow == Some(true) {
|
||||
let scale = grid_scale(e.session().edit.main_counter);
|
||||
if g.scale() != scale {
|
||||
g = GridValue::for_scale(scale);
|
||||
}
|
||||
}
|
||||
let edit = &mut e.session_mut().edit;
|
||||
edit.nudge = g;
|
||||
edit.nudge_follow_main = follow.unwrap_or(edit.nudge_follow_main && g.scale() == grid_scale(edit.main_counter));
|
||||
Ok(json!({"nudge": g.label(), "format": g.scale().id(), "follow_main": edit.nudge_follow_main}))
|
||||
}),
|
||||
]
|
||||
}
|
||||
@@ -137,7 +183,33 @@ fn value_or_step(p: &Value, current: GridValue) -> Option<GridValue> {
|
||||
Some((0..step.unsigned_abs().min(16)).fold(current, |g, _| g.stepped(step > 0)))
|
||||
}
|
||||
|
||||
/// Parse grid/nudge values.
|
||||
/// Maps a counter format to the corresponding Grid/Nudge scale.
|
||||
fn grid_scale(format: TimeFormat) -> GridScale {
|
||||
match format {
|
||||
TimeFormat::BarsBeats => GridScale::BarsBeats,
|
||||
TimeFormat::MinSecs => GridScale::MinSecs,
|
||||
TimeFormat::Timecode => GridScale::Timecode,
|
||||
TimeFormat::FeetFrames => GridScale::FeetFrames,
|
||||
TimeFormat::Samples => GridScale::Samples,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves an explicit value, a step, or a scale change while preserving the current increment.
|
||||
fn requested_grid_value(p: &Value, current: GridValue) -> Option<GridValue> {
|
||||
if p.get("value").is_some() || p.get("step").is_some() {
|
||||
return value_or_step(p, current);
|
||||
}
|
||||
let scale = str_param(p, "format").and_then(GridScale::from_id);
|
||||
match scale {
|
||||
Some(GridScale::ClipsMarkers) => Some(current),
|
||||
Some(scale) if current.scale() == scale => Some(current),
|
||||
Some(scale) => Some(GridValue::for_scale(scale)),
|
||||
None if p.get("follow_main").is_some() || p.get("lines").is_some() => Some(current),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse grid/nudge values; legacy `1` and `1/1` mean a bar, while `whole` means four quarter notes.
|
||||
pub fn grid_param(p: &Value, key: &str) -> Option<GridValue> {
|
||||
let v = p.get(key)?;
|
||||
if let Some(sec) = v.get("seconds").and_then(Value::as_f64) {
|
||||
@@ -146,15 +218,23 @@ pub fn grid_param(p: &Value, key: &str) -> Option<GridValue> {
|
||||
if let Some(f) = v.get("frames").and_then(Value::as_i64) {
|
||||
return Some(GridValue::Frames(f.clamp(1, 100_000)));
|
||||
}
|
||||
if let Some(value) = v.get("timecode").and_then(Value::as_str).and_then(TimecodeValue::from_id) {
|
||||
return Some(GridValue::Timecode(value));
|
||||
}
|
||||
if let Some(value) = v.get("feet_frames").and_then(Value::as_str).and_then(FeetFramesValue::from_id) {
|
||||
return Some(GridValue::FeetFrames(value));
|
||||
}
|
||||
if let Some(n) = v.get("samples").and_then(Value::as_i64) {
|
||||
return Some(GridValue::Samples(n.clamp(1, i64::from(u32::MAX))));
|
||||
}
|
||||
let s = v.as_str()?.trim().to_ascii_lowercase();
|
||||
let triplet = s.ends_with('t') || s.contains("triplet");
|
||||
let dotted = s.ends_with('.') || s.contains("dotted");
|
||||
let core: String = s.chars().take_while(|c| c.is_ascii_digit() || *c == '/' || *c == ' ' || c.is_ascii_alphabetic() && *c != 't').collect();
|
||||
let core = s.replace("triplet", "").replace("dotted", "");
|
||||
let core = core.trim().trim_end_matches(['t', '.']);
|
||||
let value = match core.trim() {
|
||||
"1 bar" | "bar" | "1/1" | "1" => NoteValue::Bar,
|
||||
"1" | "1/1" | "1 bar" | "bar" => NoteValue::Bar,
|
||||
"whole" | "whole note" => NoteValue::Whole,
|
||||
"1/2" => NoteValue::Half,
|
||||
"1/4" => NoteValue::Quarter,
|
||||
"1/8" => NoteValue::Eighth,
|
||||
@@ -170,15 +250,59 @@ pub fn grid_param(p: &Value, key: &str) -> Option<GridValue> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use soundcraft_time::Samples;
|
||||
/// Grid values accept compact and word-form musical modifiers plus every absolute scale.
|
||||
#[test]
|
||||
fn grid_values_parse() {
|
||||
assert_eq!(grid_param(&json!({"v": "1/16"}), "v"), Some(GridValue::Note { value: NoteValue::Sixteenth, dotted: false, triplet: false }));
|
||||
assert_eq!(grid_param(&json!({"v": "1/8t"}), "v"), Some(GridValue::Note { value: NoteValue::Eighth, dotted: false, triplet: true }));
|
||||
assert_eq!(grid_param(&json!({"v": "1/8 triplet"}), "v"), Some(GridValue::Note { value: NoteValue::Eighth, dotted: false, triplet: true }));
|
||||
assert_eq!(grid_param(&json!({"v": "1/4."}), "v"), Some(GridValue::Note { value: NoteValue::Quarter, dotted: true, triplet: false }));
|
||||
for alias in ["1", "1/1"] {
|
||||
assert_eq!(grid_param(&json!({"v": alias}), "v"), Some(GridValue::Note { value: NoteValue::Bar, dotted: false, triplet: false }));
|
||||
}
|
||||
assert_eq!(grid_param(&json!({"v": "whole"}), "v"), Some(GridValue::Note { value: NoteValue::Whole, dotted: false, triplet: false }));
|
||||
assert_eq!(grid_param(&json!({"v": "whole note"}), "v"), Some(GridValue::Note { value: NoteValue::Whole, dotted: false, triplet: false }));
|
||||
assert_eq!(grid_param(&json!({"v": {"seconds": 0.5}}), "v"), Some(GridValue::Seconds(0.5)));
|
||||
assert_eq!(grid_param(&json!({"v": {"timecode": "quarter_frame"}}), "v"), Some(GridValue::Timecode(TimecodeValue::QuarterFrame)));
|
||||
assert_eq!(grid_param(&json!({"v": {"feet_frames": "foot"}}), "v"), Some(GridValue::FeetFrames(FeetFramesValue::Foot)));
|
||||
assert_eq!(grid_param(&json!({"v": "nonsense"}), "v"), None);
|
||||
}
|
||||
|
||||
/// Explicit values and formats retain Follow Main only when the selected scale still matches.
|
||||
#[test]
|
||||
fn explicit_grid_and_nudge_scales_keep_follow_state_consistent() {
|
||||
for command in ["view.grid", "view.nudge"] {
|
||||
let mut e = Engine::default();
|
||||
e.execute("view.main_counter", &json!({"format": "min_secs"})).unwrap();
|
||||
e.execute(command, &json!({"follow_main": true})).unwrap();
|
||||
let result = e.execute(command, &json!({"value": {"seconds": 0.1}})).unwrap();
|
||||
assert_eq!(result["follow_main"], true);
|
||||
let result = e.execute(command, &json!({"value": {"feet_frames": "foot"}})).unwrap();
|
||||
assert_eq!(result["follow_main"], false);
|
||||
e.execute(command, &json!({"follow_main": true})).unwrap();
|
||||
let result = e.execute(command, &json!({"format": "bars_beats"})).unwrap();
|
||||
assert_eq!(result["follow_main"], false);
|
||||
}
|
||||
let mut e = Engine::default();
|
||||
e.execute("view.grid", &json!({"format": "clips_markers"})).unwrap();
|
||||
assert!(!e.session().edit.grid_follow_main);
|
||||
e.execute("view.grid", &json!({"value": {"samples": 100}})).unwrap();
|
||||
assert!(!e.session().edit.grid_clips_markers);
|
||||
assert_eq!(e.session().edit.grid, GridValue::Samples(100));
|
||||
}
|
||||
|
||||
/// Historical bar aliases retain meter-dependent duration; the explicit whole note remains distinct.
|
||||
#[test]
|
||||
fn legacy_bar_aliases_and_whole_notes_remain_distinct_in_odd_meter() {
|
||||
let mut e = Engine::default();
|
||||
e.session_mut().tempo = soundcraft_time::TempoMap::new(120.0, 3, 4).unwrap();
|
||||
for (value, expected) in [("1", 72_000), ("1/1", 72_000), ("whole", 96_000)] {
|
||||
e.execute("view.grid", &json!({"value": value, "follow_main": false})).unwrap();
|
||||
let s = e.session();
|
||||
assert_eq!(s.edit.grid.step_samples(0, s.sample_rate, &s.tempo, s.frame_rate), expected);
|
||||
}
|
||||
}
|
||||
|
||||
fn view(e: &Engine) -> (f64, Samples) {
|
||||
(e.session().edit.zoom.samples_per_px, e.session().edit.zoom.scroll)
|
||||
}
|
||||
@@ -241,6 +365,7 @@ mod tests {
|
||||
assert_eq!(state(&e), before);
|
||||
}
|
||||
|
||||
/// Grid and Nudge steps drive edit movement while preserving their selected increments.
|
||||
#[test]
|
||||
fn grid_and_nudge_values_step_and_nudges_can_use_the_next_value() {
|
||||
let mut e = Engine::default();
|
||||
@@ -262,4 +387,32 @@ mod tests {
|
||||
assert_eq!(e.session().edit.selection.start, 6_000);
|
||||
assert_eq!(e.session().edit.nudge.label(), "1/16 note");
|
||||
}
|
||||
|
||||
/// Grid and Nudge expose independent scale-following state, while Clips/Markers remains Grid-only.
|
||||
#[test]
|
||||
fn grid_and_nudge_choose_scales_follow_the_main_counter_and_keep_clips_markers_grid_only() {
|
||||
let mut e = Engine::default();
|
||||
e.execute("view.grid", &json!({"format": "timecode", "follow_main": false})).unwrap();
|
||||
assert_eq!(e.session().edit.grid, GridValue::Timecode(TimecodeValue::Frame));
|
||||
e.execute("view.grid", &json!({"value": {"timecode": "quarter_frame"}})).unwrap();
|
||||
e.execute("view.grid", &json!({"format": "clips_markers", "follow_main": false})).unwrap();
|
||||
assert_eq!(e.session().edit.grid, GridValue::Timecode(TimecodeValue::QuarterFrame));
|
||||
assert!(e.session().edit.grid_clips_markers);
|
||||
assert!(e.execute("view.nudge", &json!({"format": "clips_markers"})).is_err());
|
||||
|
||||
e.execute("view.grid", &json!({"follow_main": true})).unwrap();
|
||||
e.execute("view.nudge", &json!({"follow_main": true})).unwrap();
|
||||
assert_eq!((e.session().edit.grid, e.session().edit.nudge), (GridValue::Seconds(1.0), GridValue::Seconds(1.0)));
|
||||
assert!(!e.session().edit.grid_clips_markers);
|
||||
e.execute("view.main_counter", &json!({"format": "samples"})).unwrap();
|
||||
assert_eq!((e.session().edit.grid, e.session().edit.nudge), (GridValue::Samples(100), GridValue::Samples(100)));
|
||||
assert!(e.session().edit.grid_follow_main && e.session().edit.nudge_follow_main);
|
||||
|
||||
e.execute("view.grid", &json!({"format": "bars_beats", "follow_main": false})).unwrap();
|
||||
assert_eq!(e.session().edit.grid, GridValue::default());
|
||||
assert!(!e.session().edit.grid_follow_main);
|
||||
e.execute("view.main_counter", &json!({"format": "timecode"})).unwrap();
|
||||
assert_eq!(e.session().edit.grid, GridValue::default());
|
||||
assert_eq!(e.session().edit.nudge, GridValue::Timecode(TimecodeValue::Frame));
|
||||
}
|
||||
}
|
||||
|
||||
+127
-6
@@ -1,12 +1,15 @@
|
||||
//! Borrowed document equality for the saved-state indicator.
|
||||
|
||||
use soundcraft_model::{EditState, Session};
|
||||
use soundcraft_model::{EditState, Mixer, Session, Track};
|
||||
|
||||
/// Equal apart from the selection, playhead and zoom, without copying document data.
|
||||
/// Equal apart from navigation and live input flags, without copying document data.
|
||||
pub(super) fn same_document(saved: &Session, doc: &Session) -> bool {
|
||||
document_values(saved, &saved.edit) == document_values(doc, &saved.edit)
|
||||
&& saved.tracks.len() == doc.tracks.len()
|
||||
&& saved.tracks.iter().zip(&doc.tracks).all(|(saved, doc)| track_values(saved) == track_values(doc))
|
||||
}
|
||||
|
||||
/// Borrow persistent session fields; track fields are compared separately.
|
||||
fn document_values<'a>(s: &'a Session, navigation: &'a EditState) -> impl PartialEq + 'a {
|
||||
// No `..`: adding a document field must also decide how it affects saved-state equality.
|
||||
let Session {
|
||||
@@ -18,7 +21,7 @@ fn document_values<'a>(s: &'a Session, navigation: &'a EditState) -> impl Partia
|
||||
timecode_start,
|
||||
tempo,
|
||||
key_signatures,
|
||||
tracks,
|
||||
tracks: _,
|
||||
sources,
|
||||
videos,
|
||||
busses,
|
||||
@@ -35,11 +38,66 @@ fn document_values<'a>(s: &'a Session, navigation: &'a EditState) -> impl Partia
|
||||
} = s;
|
||||
// Tuples implement PartialEq up to twelve elements. These contain only borrowed fields.
|
||||
(
|
||||
(format_version, name, sample_rate, bit_depth, frame_rate, timecode_start, tempo, key_signatures, tracks, sources, videos, busses),
|
||||
(format_version, name, sample_rate, bit_depth, frame_rate, timecode_start, tempo, key_signatures, sources, videos, busses),
|
||||
(outputs, markers, groups, auto_names, edit_values(edit, navigation), next_id, comments, midi_originals, pool, folder),
|
||||
)
|
||||
}
|
||||
|
||||
/// Borrow persistent track fields without allocating or copying media.
|
||||
fn track_values(track: &Track) -> impl PartialEq + '_ {
|
||||
let Track {
|
||||
id,
|
||||
name,
|
||||
kind,
|
||||
format,
|
||||
color,
|
||||
height,
|
||||
playlists,
|
||||
active_playlist,
|
||||
mixer,
|
||||
automation,
|
||||
view,
|
||||
hidden,
|
||||
inactive,
|
||||
frozen,
|
||||
comments,
|
||||
folder,
|
||||
folder_open,
|
||||
instrument,
|
||||
ticks_timebase,
|
||||
elastic,
|
||||
pinned,
|
||||
} = track;
|
||||
(
|
||||
(id, name, kind, format, color, height, playlists, active_playlist, mixer_values(mixer), automation, view),
|
||||
(hidden, inactive, frozen, comments, folder, folder_open, instrument, ticks_timebase, elastic, pinned),
|
||||
)
|
||||
}
|
||||
|
||||
/// Borrow persistent mixer fields without allocating or copying media.
|
||||
fn mixer_values(mixer: &Mixer) -> impl PartialEq + '_ {
|
||||
let Mixer {
|
||||
volume_db,
|
||||
pan,
|
||||
mute,
|
||||
solo,
|
||||
solo_safe,
|
||||
record_arm: _,
|
||||
input_monitor: _,
|
||||
phase_invert,
|
||||
input,
|
||||
output,
|
||||
inserts,
|
||||
sends,
|
||||
automation_mode,
|
||||
trim_db,
|
||||
vca,
|
||||
surround,
|
||||
} = mixer;
|
||||
((volume_db, pan, mute, solo, solo_safe, phase_invert, input, output, inserts, sends, automation_mode), (trim_db, vca, surround))
|
||||
}
|
||||
|
||||
/// Borrow edit settings while normalizing transient navigation to the saved values.
|
||||
fn edit_values<'a>(edit: &'a EditState, navigation: &'a EditState) -> impl PartialEq + 'a {
|
||||
let EditState {
|
||||
tool,
|
||||
@@ -52,6 +110,9 @@ fn edit_values<'a>(edit: &'a EditState, navigation: &'a EditState) -> impl Parti
|
||||
grid,
|
||||
nudge,
|
||||
grid_lines,
|
||||
grid_follow_main,
|
||||
nudge_follow_main,
|
||||
grid_clips_markers,
|
||||
main_counter,
|
||||
sub_counter,
|
||||
zoom: _,
|
||||
@@ -130,7 +191,17 @@ fn edit_values<'a>(edit: &'a EditState, navigation: &'a EditState) -> impl Parti
|
||||
scrolling,
|
||||
solo_mode,
|
||||
),
|
||||
(pre_fader_metering, delay_compensation, keyboard_focus, &navigation.timeline_selection, flags, values),
|
||||
(
|
||||
grid_follow_main,
|
||||
nudge_follow_main,
|
||||
grid_clips_markers,
|
||||
pre_fader_metering,
|
||||
delay_compensation,
|
||||
keyboard_focus,
|
||||
&navigation.timeline_selection,
|
||||
flags,
|
||||
values,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -141,7 +212,7 @@ mod tests {
|
||||
use soundcraft_time::{Range, TimeFormat};
|
||||
use std::sync::Arc;
|
||||
|
||||
// The previous comparison is an oracle for preserving the saved-state policy.
|
||||
/// The clone-based policy, extended to ignore live input flags, serves as a test oracle.
|
||||
fn previous_same_document(saved: &Session, doc: &Session) -> bool {
|
||||
let mut doc = doc.clone();
|
||||
let (from, to) = (&saved.edit, &mut doc.edit);
|
||||
@@ -151,9 +222,14 @@ mod tests {
|
||||
to.selected_clips.clone_from(&from.selected_clips);
|
||||
to.playhead = from.playhead;
|
||||
to.zoom = from.zoom;
|
||||
for (saved, doc) in saved.tracks.iter().zip(&mut doc.tracks) {
|
||||
doc.mixer.record_arm = saved.mixer.record_arm;
|
||||
doc.mixer.input_monitor = saved.mixer.input_monitor;
|
||||
}
|
||||
*saved == doc
|
||||
}
|
||||
|
||||
/// Check both directions and compare against the normalized clone oracle.
|
||||
fn check(saved: &Session, doc: &Session, expected: bool, field: &str) {
|
||||
assert_eq!(same_document(saved, doc), expected, "{field}");
|
||||
assert_eq!(same_document(doc, saved), expected, "{field}, reversed");
|
||||
@@ -186,6 +262,9 @@ mod tests {
|
||||
("grid", |e| e.grid = soundcraft_time::GridValue::Seconds(2.0)),
|
||||
("nudge", |e| e.nudge = soundcraft_time::GridValue::Seconds(2.0)),
|
||||
("grid_lines", |e| e.grid_lines = !e.grid_lines),
|
||||
("grid_follow_main", |e| e.grid_follow_main = !e.grid_follow_main),
|
||||
("nudge_follow_main", |e| e.nudge_follow_main = !e.nudge_follow_main),
|
||||
("grid_clips_markers", |e| e.grid_clips_markers = !e.grid_clips_markers),
|
||||
("main_counter", |e| e.main_counter = TimeFormat::Samples),
|
||||
("sub_counter", |e| e.sub_counter = None),
|
||||
("zoom_toggle", |e| e.zoom_toggle = Some(ZoomToggle { samples_per_px: 64.0, scroll: 0, heights: Vec::new() })),
|
||||
@@ -252,6 +331,48 @@ mod tests {
|
||||
assert_eq!(same_document(&doc, &doc), previous_same_document(&doc, &doc), "NaN keeps the previous PartialEq behavior");
|
||||
}
|
||||
|
||||
/// Only arm and monitoring are transient; every other mixer field still contributes to dirtiness.
|
||||
#[test]
|
||||
fn live_flags_do_not_hide_persistent_mixer_changes() {
|
||||
use soundcraft_model::{AutomationMode, BusId, Insert, Route, SendSlot, SurroundPan};
|
||||
let mut saved = Session::default();
|
||||
let track = saved.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
let mut live = saved.clone();
|
||||
live.track_mut(track).unwrap().mixer.record_arm = true;
|
||||
live.track_mut(track).unwrap().mixer.input_monitor = true;
|
||||
check(&saved, &live, true, "live input flags");
|
||||
let edits: &[(&str, fn(&mut Mixer))] = &[
|
||||
("volume", |m| m.volume_db = -6.0),
|
||||
("pan", |m| m.pan[0] = 0.5),
|
||||
("mute", |m| m.mute = true),
|
||||
("solo", |m| m.solo = true),
|
||||
("solo_safe", |m| m.solo_safe = true),
|
||||
("phase_invert", |m| m.phase_invert = true),
|
||||
("input", |m| m.input = Route::Hardware("Mic".into())),
|
||||
("output", |m| m.output = Route::Bus(BusId(900))),
|
||||
("inserts", |m| m.inserts[0] = Some(Insert::new("eq7"))),
|
||||
("sends", |m| m.sends[0] = Some(SendSlot::new(Route::Main))),
|
||||
("automation_mode", |m| m.automation_mode = AutomationMode::Touch),
|
||||
("trim_db", |m| m.trim_db = -3.0),
|
||||
("vca", |m| m.vca = Some(900)),
|
||||
("surround", |m| m.surround = Some(SurroundPan::default())),
|
||||
];
|
||||
for &(field, edit) in edits {
|
||||
let mut doc = live.clone();
|
||||
edit(&mut doc.track_mut(track).unwrap().mixer);
|
||||
check(&saved, &doc, false, field);
|
||||
}
|
||||
let mut doc = live.clone();
|
||||
doc.tracks.push(doc.tracks[0].clone());
|
||||
check(&saved, &doc, false, "track count");
|
||||
let mut doc = live.clone();
|
||||
doc.tracks[0].id = TrackId(900);
|
||||
check(&saved, &doc, false, "track identity");
|
||||
let mut doc = live.clone();
|
||||
doc.tracks[0].mixer.volume_db = f32::NAN;
|
||||
assert!(!same_document(&doc, &doc), "persistent NaN keeps PartialEq semantics");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_saved_zoom_keeps_the_previous_partial_eq_behavior() {
|
||||
let mut saved = Session::default();
|
||||
|
||||
+11
-21
@@ -528,9 +528,15 @@ fn join_gain_env(l: &mut Clip, r: &Clip) {
|
||||
}
|
||||
|
||||
/// Move clips by `delta`, overwriting what they land on; `dest` sends whole tracks of them
|
||||
/// elsewhere (see [`destinations`]).
|
||||
/// elsewhere (see [`destinations`]). Same-track moves clamped to zero leave all material intact.
|
||||
pub fn move_clips(s: &mut Session, ids: &[ClipId], delta: Samples, dest: &[(TrackId, TrackId)]) -> usize {
|
||||
let ids: HashSet<ClipId> = ids.iter().copied().collect();
|
||||
// Limit the shift before removing any clips, so a stationary edit cannot overwrite overlaps.
|
||||
let limit = s.tracks.iter().flat_map(|t| t.clips()).filter(|c| ids.contains(&c.id) && !locked(c)).map(|c| c.start.saturating_neg()).max();
|
||||
let delta = delta.max(limit.unwrap_or(0));
|
||||
if delta == 0 && dest.iter().all(|(from, to)| from == to) {
|
||||
return 0;
|
||||
}
|
||||
let mut moving: Vec<(TrackId, Clip)> = Vec::new();
|
||||
for t in &mut s.tracks {
|
||||
let tid = t.id;
|
||||
@@ -546,8 +552,6 @@ pub fn move_clips(s: &mut Session, ids: &[ClipId], delta: Samples, dest: &[(Trac
|
||||
}
|
||||
}
|
||||
let n = moving.len();
|
||||
// Limit the shift once, so the group stops at zero together and keeps its spacing.
|
||||
let delta = delta.max(moving.iter().map(|(_, c)| c.start.saturating_neg()).max().unwrap_or(0));
|
||||
let placed = moving.into_iter().map(|(tid, mut c)| {
|
||||
c.start = c.start.saturating_add(delta);
|
||||
(lands(dest, tid), c)
|
||||
@@ -572,20 +576,7 @@ fn put_clips(s: &mut Session, placed: Vec<(TrackId, Clip)>) {
|
||||
|
||||
/// Whether the Edit window shows track `t`: not hidden, and not inside a closed folder at any level.
|
||||
pub fn shown(s: &Session, t: &Track) -> bool {
|
||||
!t.hidden && !folder_collapsed(s, t)
|
||||
}
|
||||
|
||||
/// Hidden because a folder at any level above this track is closed.
|
||||
fn folder_collapsed(s: &Session, track: &Track) -> bool {
|
||||
let mut current = track.folder;
|
||||
for _ in 0..64 {
|
||||
let Some(folder) = current.and_then(|folder| s.track(folder)) else { return false };
|
||||
if !folder.folder_open {
|
||||
return true;
|
||||
}
|
||||
current = folder.folder;
|
||||
}
|
||||
false
|
||||
s.track_shown(t)
|
||||
}
|
||||
|
||||
/// Where the tracks of clips `ids` go when track `from` goes to `to`: each keeps its distance
|
||||
@@ -790,12 +781,11 @@ pub fn shuffle_clips(s: &mut Session, ids: &[ClipId], delta: Samples, dest: &[(T
|
||||
/// How far a Grabber drag by `raw` moves `clip` in Grid mode: Absolute puts its sync point (its
|
||||
/// start when it has none inside the clip) on the nearest grid line; Relative moves it by whole
|
||||
/// grid steps, keeping its offset from the grid.
|
||||
pub fn grid_delta(s: &Session, clip: &Clip, raw: Samples, relative: bool) -> Samples {
|
||||
let (g, sr, map, rate) = (&s.edit.grid, s.sample_rate, &s.tempo, s.frame_rate);
|
||||
pub fn grid_delta(s: &Session, clip: &Clip, raw: Samples, relative: bool, moving: &[ClipId]) -> Samples {
|
||||
let sync = if (0..clip.length).contains(&clip.sync_point) { clip.sync_point } else { 0 };
|
||||
let anchor = clip.start.saturating_add(sync);
|
||||
let from = if relative { g.line_at_or_before(anchor, sr, map, rate) } else { anchor };
|
||||
g.snap(from.saturating_add(raw), sr, map, rate).saturating_sub(from)
|
||||
let from = if relative { s.grid_line_at_or_before_excluding(anchor, moving) } else { anchor };
|
||||
s.snap_to_grid_excluding(from.saturating_add(raw), moving).saturating_sub(from)
|
||||
}
|
||||
|
||||
/// Trim a clip's edges to `start` and/or `end` like the Trim tool, never past its file. In
|
||||
|
||||
@@ -330,9 +330,9 @@ fn grid_moves_snap_the_clip_start_or_keep_its_offset() {
|
||||
let (s, t) = session_with_clip();
|
||||
let step = s.edit.grid.step_samples(0, s.sample_rate, &s.tempo, s.frame_rate);
|
||||
let c = s.track(t).unwrap().clips()[0].clone();
|
||||
assert_eq!(c.start + grid_delta(&s, &c, step + 200, false), step);
|
||||
assert_eq!(c.start + grid_delta(&s, &c, step + 200, true), step + 1000);
|
||||
assert_eq!(grid_delta(&s, &c, step / 3, true), 0);
|
||||
assert_eq!(c.start + grid_delta(&s, &c, step + 200, false, &[c.id]), step);
|
||||
assert_eq!(c.start + grid_delta(&s, &c, step + 200, true, &[c.id]), step + 1000);
|
||||
assert_eq!(grid_delta(&s, &c, step / 3, true, &[c.id]), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+156
-18
@@ -42,19 +42,122 @@ pub use strip::{StripMode, StripNames, StripScan, bounded_to_track, name_strippe
|
||||
/// one. Only a regular file qualifies: a device or a pipe named by a session or a command would
|
||||
/// never end or never answer. Errors name the file.
|
||||
pub fn read_file(path: impl AsRef<Path>) -> Result<Vec<u8>> {
|
||||
let path = path.as_ref();
|
||||
read_file_within(path.as_ref(), false)
|
||||
}
|
||||
|
||||
/// [`read_file`]; a `session` file is refused ([`session_size`]) past [`session_limit`].
|
||||
fn read_file_within(path: &Path, session: bool) -> Result<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
crate::file_access::check_read(path).map_err(EngineError::Io)?;
|
||||
let err = |err: std::io::Error| EngineError::Io(format!("{}: {err}", path.display()));
|
||||
if !std::fs::metadata(path).map_err(err)?.is_file() {
|
||||
let meta = std::fs::metadata(path).map_err(err)?;
|
||||
if !meta.is_file() {
|
||||
return Err(EngineError::Io(format!("{}: not a regular file", path.display())));
|
||||
}
|
||||
std::fs::read(path).map_err(err)
|
||||
if !session {
|
||||
return std::fs::read(path).map_err(err);
|
||||
}
|
||||
session_size(path.display(), meta.len(), false)?;
|
||||
// The file may have grown since: never read more than one byte past the limit.
|
||||
let mut data = Vec::new();
|
||||
std::fs::File::open(path).map_err(err)?.take(session_limit().saturating_add(1)).read_to_end(&mut data).map_err(err)?;
|
||||
session_size(path.display(), data.len() as u64, false)?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// [`read_file`] as UTF-8 text.
|
||||
pub fn read_text(path: impl AsRef<Path>) -> Result<String> {
|
||||
let path = path.as_ref();
|
||||
String::from_utf8(read_file(path)?).map_err(|err| EngineError::Io(format!("{}: {err}", path.display())))
|
||||
utf8(path, read_file(path)?)
|
||||
}
|
||||
|
||||
fn utf8(path: &Path, bytes: Vec<u8>) -> Result<String> {
|
||||
String::from_utf8(bytes).map_err(|err| EngineError::Io(format!("{}: {err}", path.display())))
|
||||
}
|
||||
|
||||
/// The largest session (`.scraft`) SoundCraft opens or saves. A session is read whole and parsed
|
||||
/// in one go, so a larger one is refused by its size before it is read, and never written (it
|
||||
/// could not be opened again); real sessions are far smaller.
|
||||
pub const MAX_SESSION_BYTES: u64 = 256 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// A smaller limit than [`MAX_SESSION_BYTES`] for the tests on this thread ([`SessionLimit`]).
|
||||
static TEST_SESSION_LIMIT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// [`MAX_SESSION_BYTES`] (in tests, the limit a [`SessionLimit`] set on this thread).
|
||||
pub(crate) fn session_limit() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(limit) = TEST_SESSION_LIMIT.with(std::cell::Cell::get) {
|
||||
return limit;
|
||||
}
|
||||
MAX_SESSION_BYTES
|
||||
}
|
||||
|
||||
/// While it lives, sessions on this thread are opened and saved up to the limit given to
|
||||
/// [`SessionLimit::set`] instead of [`MAX_SESSION_BYTES`], so tests reach it with small sessions.
|
||||
#[cfg(test)]
|
||||
pub(crate) struct SessionLimit;
|
||||
|
||||
#[cfg(test)]
|
||||
impl SessionLimit {
|
||||
pub(crate) fn set(limit: u64) -> SessionLimit {
|
||||
TEST_SESSION_LIMIT.with(|l| l.set(Some(limit)));
|
||||
SessionLimit
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Drop for SessionLimit {
|
||||
fn drop(&mut self) {
|
||||
TEST_SESSION_LIMIT.with(|l| l.set(None));
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuses the session `name` of `len` bytes when it is larger than [`session_limit`]: too large
|
||||
/// to open, or, when `saving`, to save.
|
||||
pub(crate) fn session_size(name: impl std::fmt::Display, len: u64, saving: bool) -> Result<()> {
|
||||
let limit = session_limit();
|
||||
if len <= limit {
|
||||
return Ok(());
|
||||
}
|
||||
let most = if limit >= 1 << 20 { format!("{} MiB", limit >> 20) } else { format!("{limit} bytes") };
|
||||
Err(EngineError::Io(if saving {
|
||||
format!("{name} is too large to save: over {most}, more than SoundCraft opens")
|
||||
} else {
|
||||
format!("{name} is too large to open (over {most})")
|
||||
}))
|
||||
}
|
||||
|
||||
/// [`read_text`] for a session file: refused, unread, past [`session_limit`].
|
||||
pub(crate) fn read_session_text(path: impl AsRef<Path>) -> Result<String> {
|
||||
let path = path.as_ref();
|
||||
utf8(path, read_file_within(path, true)?)
|
||||
}
|
||||
|
||||
/// A bare `.scraft` handed over as bytes (the browser) as text: refused, uncopied, past
|
||||
/// [`session_limit`].
|
||||
pub(crate) fn session_bytes_text(name: &str, bytes: &[u8]) -> Result<String> {
|
||||
session_size(name, bytes.len() as u64, false)?;
|
||||
String::from_utf8(bytes.to_vec()).map_err(|_| EngineError::Io(format!("{name}: not a SoundCraft session")))
|
||||
}
|
||||
|
||||
/// How many bytes [`Session::to_json`] makes of `s`, counted without keeping them.
|
||||
fn json_len(s: &Session) -> u64 {
|
||||
struct Count(u64);
|
||||
impl std::io::Write for Count {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0 = self.0.saturating_add(buf.len() as u64);
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut n = Count(0);
|
||||
// A session that cannot be written counts as nothing here: `to_json` reports that error.
|
||||
serde_json::to_writer_pretty(&mut n, s).map_or(0, |()| n.0)
|
||||
}
|
||||
|
||||
/// Is there a file at `path` the automation read root lets us see? A path outside the root is
|
||||
@@ -497,7 +600,6 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
|
||||
let mut s = session.clone();
|
||||
let from = s.folder.clone();
|
||||
let same_dir = from.as_deref().is_some_and(|f| same_path(f, &dir));
|
||||
let mut written = 0;
|
||||
// A file can stay put for all the sources that name it, unless their audio differs.
|
||||
let shared_paths: Vec<bool> = {
|
||||
let mut audio_by_path: HashMap<&str, HashSet<Option<*const SourceAudio>>> = HashMap::new();
|
||||
@@ -506,8 +608,11 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
|
||||
}
|
||||
s.sources.iter().map(|src| audio_by_path.get(src.path.as_str()).is_some_and(|a| a.len() > 1)).collect()
|
||||
};
|
||||
// Files written for audio during this save: sources playing the same audio share one.
|
||||
// Files for audio in this save: sources playing the same audio share one. The files still to
|
||||
// write (their stem, audio and the sources naming them) are written once the size is checked.
|
||||
let mut files: HashMap<*const SourceAudio, String> = HashMap::new();
|
||||
let mut queued: HashMap<*const SourceAudio, usize> = HashMap::new();
|
||||
let mut pending: Vec<(String, Arc<SourceAudio>, Vec<usize>)> = Vec::new();
|
||||
for (i, src) in s.sources.iter_mut().enumerate() {
|
||||
if !same_dir
|
||||
&& s.pool.get(src.id).is_none()
|
||||
@@ -533,7 +638,14 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
|
||||
src.format = FileFormat::Wav;
|
||||
continue;
|
||||
}
|
||||
make_dir(&audio_dir)?;
|
||||
if let Some((stem, _, sources)) = queued.get(&Arc::as_ptr(audio)).and_then(|&k| pending.get_mut(k)) {
|
||||
// As long as any name the file can get, so the size checked is an upper bound.
|
||||
src.path = format!("Audio Files/{stem}_9999.wav");
|
||||
src.unsaved = false;
|
||||
src.format = FileFormat::Wav;
|
||||
sources.push(i);
|
||||
continue;
|
||||
}
|
||||
let mut stem = sanitize_name(&src.name);
|
||||
if overwrite {
|
||||
// One file per source id so autosaves never collide or pile up.
|
||||
@@ -545,23 +657,46 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: soundcraft_audio_io::BitDepth::Float32, dither: false, bwf: None };
|
||||
let bytes = soundcraft_audio_io::encode(&audio.buffer, &opts).map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
let (name, new) = store_wav(&audio_dir, &stem, &bytes)?;
|
||||
src.path = format!("Audio Files/{name}");
|
||||
src.path = format!("Audio Files/{stem}_9999.wav");
|
||||
src.unsaved = false;
|
||||
src.format = FileFormat::Wav;
|
||||
files.insert(Arc::as_ptr(audio), src.path.clone());
|
||||
written += usize::from(new);
|
||||
}
|
||||
if written > 0 {
|
||||
sync_dir(&audio_dir);
|
||||
queued.insert(Arc::as_ptr(audio), pending.len());
|
||||
pending.push((stem, Arc::clone(audio), vec![i]));
|
||||
}
|
||||
s.folder = Some(dir.clone());
|
||||
if !overwrite && let Some(stem) = p.file_stem().and_then(OsStr::to_str) {
|
||||
s.name = stem.to_string();
|
||||
}
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
// Before any audio is written: a session too large to open again is not saved (#892). With no
|
||||
// audio to write, the text checked is the text saved.
|
||||
let checked = if pending.is_empty() {
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
session_size(p.display(), text.len() as u64, true)?;
|
||||
Some(text)
|
||||
} else {
|
||||
session_size(p.display(), json_len(&s), true)?;
|
||||
None
|
||||
};
|
||||
let mut written = 0;
|
||||
for (stem, audio, sources) in &pending {
|
||||
make_dir(&audio_dir)?;
|
||||
let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: soundcraft_audio_io::BitDepth::Float32, dither: false, bwf: None };
|
||||
let bytes = soundcraft_audio_io::encode(&audio.buffer, &opts).map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
let (name, new) = store_wav(&audio_dir, stem, &bytes)?;
|
||||
for &i in sources {
|
||||
if let Some(src) = s.sources.get_mut(i) {
|
||||
src.path = format!("Audio Files/{name}");
|
||||
}
|
||||
}
|
||||
written += usize::from(new);
|
||||
}
|
||||
if written > 0 {
|
||||
sync_dir(&audio_dir);
|
||||
}
|
||||
let text = match checked {
|
||||
Some(text) => text,
|
||||
None => s.to_json().map_err(|err| EngineError::Io(err.to_string()))?,
|
||||
};
|
||||
make_dir(&dir)?;
|
||||
// Atomic-ish write: temp file then rename.
|
||||
let tmp = p.with_extension("scraft.tmp");
|
||||
@@ -762,10 +897,13 @@ fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::colle
|
||||
if total > limits.bytes {
|
||||
return Err(EngineError::Io("bundle: too large".into()));
|
||||
}
|
||||
let is_session = !rel.contains('/') && Path::new(&rel).extension().and_then(OsStr::to_str) == Some(soundcraft_model::SESSION_EXTENSION);
|
||||
if is_session && text.is_none() {
|
||||
session_size(format_args!("bundle: {rel}"), size, false)?;
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
// The declared size is hostile too: never read past it.
|
||||
f.by_ref().take(size).read_to_end(&mut data).map_err(|err| EngineError::Io(format!("bundle: {rel}: {err}")))?;
|
||||
let is_session = !rel.contains('/') && Path::new(&rel).extension().and_then(OsStr::to_str) == Some(soundcraft_model::SESSION_EXTENSION);
|
||||
if is_session && text.is_none() {
|
||||
text = Some(String::from_utf8(data).map_err(|_| EngineError::Io(format!("bundle: {rel} is not text")))?);
|
||||
} else {
|
||||
|
||||
@@ -69,6 +69,8 @@ fn session_bundle_within(session: &Session, limits: BundleLimits) -> Result<(Vec
|
||||
src.format = FileFormat::Wav;
|
||||
}
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
// Its session too: one the reader would refuse is not saved (#892).
|
||||
super::session_size("the session", text.len() as u64, true)?;
|
||||
fits(text.len())?;
|
||||
w.start_file(format!("{}.{}", sanitize_name(&s.name), soundcraft_model::SESSION_EXTENSION), opts).map_err(zerr)?;
|
||||
w.write_all(text.as_bytes()).map_err(ioerr)?;
|
||||
@@ -100,10 +102,7 @@ pub fn open_session_bytes(e: &mut Engine, name: &str, bytes: &[u8]) -> Result<Ve
|
||||
let (text, mut files) = if bytes.starts_with(b"PK\x03\x04") {
|
||||
read_bundle(bytes, BUNDLE_LIMITS)?
|
||||
} else {
|
||||
(
|
||||
String::from_utf8(bytes.to_vec()).map_err(|_| EngineError::Io(format!("{name}: not a SoundCraft session")))?,
|
||||
std::collections::HashMap::new(),
|
||||
)
|
||||
(super::session_bytes_text(name, bytes)?, std::collections::HashMap::new())
|
||||
};
|
||||
let mut s = Session::from_json(&text).map_err(|err| EngineError::Io(format!("{name}: {err}")))?;
|
||||
let mut missing = Vec::new();
|
||||
@@ -149,6 +148,38 @@ pub fn open_session_bytes(e: &mut Engine, name: &str, bytes: &[u8]) -> Result<Ve
|
||||
mod bundle_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_session_too_large_to_parse_is_refused_from_bytes() {
|
||||
// #892: a session the browser hands over as bytes has the cap a session file has. The
|
||||
// bytes are zeroed on allocation and never read, so they take no memory.
|
||||
let huge = vec![0u8; usize::try_from(super::super::MAX_SESSION_BYTES).unwrap() + 1];
|
||||
let err = open_session_bytes(&mut Engine::default(), "Huge.scraft", &huge).unwrap_err().to_string();
|
||||
assert_eq!(err, "Huge.scraft is too large to open (over 256 MiB)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundles_and_bare_sessions_keep_to_the_session_limit_both_ways() {
|
||||
// #892, with the limit lowered for this test: a bundle is saved only if its session can
|
||||
// be opened again (#433), and its reader and the bare-bytes reader refuse one past it.
|
||||
let e = crate::demo::demo_engine();
|
||||
let (bundle, fresh) = session_bundle(e.session()).unwrap();
|
||||
let inside = fresh.to_json().unwrap().len() as u64;
|
||||
let bare = e.session().to_json().unwrap();
|
||||
{
|
||||
let _limit = super::super::SessionLimit::set(inside.max(bare.len() as u64));
|
||||
assert!(session_bundle(e.session()).is_ok());
|
||||
assert!(open_session_bytes(&mut Engine::default(), "Song.scraftz", &bundle).is_ok());
|
||||
assert!(open_session_bytes(&mut Engine::default(), "Song.scraft", bare.as_bytes()).is_ok());
|
||||
}
|
||||
let _limit = super::super::SessionLimit::set(inside.min(bare.len() as u64) - 1);
|
||||
let err = session_bundle(e.session()).unwrap_err().to_string();
|
||||
assert!(err.starts_with("the session is too large to save"), "{err}");
|
||||
let err = open_session_bytes(&mut Engine::default(), "Song.scraftz", &bundle).unwrap_err().to_string();
|
||||
assert!(err.starts_with("bundle: ") && err.contains(".scraft is too large to open"), "{err}");
|
||||
let err = open_session_bytes(&mut Engine::default(), "Song.scraft", bare.as_bytes()).unwrap_err().to_string();
|
||||
assert!(err.starts_with("Song.scraft is too large to open"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_round_trips_session_and_audio() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::bundle::save_session_bundle;
|
||||
use super::import::add_source;
|
||||
use super::import::{MAX_IMPORT_SAMPLES, at_rate, relink_videos};
|
||||
use super::{
|
||||
Arc, Engine, EngineError, OsStr, Path, PathBuf, Result, Session, SourceAudio, file_key, read_file, read_text, stored_path, write_session,
|
||||
Arc, Engine, EngineError, OsStr, Path, PathBuf, Result, Session, SourceAudio, file_key, read_file, read_session_text, stored_path, write_session,
|
||||
};
|
||||
|
||||
/// Save the session to `path` (a `.scraft` file). Audio that only exists in memory is written
|
||||
@@ -44,7 +44,7 @@ pub fn open_session(e: &mut Engine, path: impl AsRef<Path>) -> Result<Vec<String
|
||||
/// [`open_session`], following the media paths in it as if they were stored in the session file
|
||||
/// `links` (crash recovery: the session written beside the autosave, its paths from the original).
|
||||
pub(crate) fn open_session_linked(e: &mut Engine, path: &Path, links: &Path) -> Result<Vec<String>> {
|
||||
let text = read_text(path)?;
|
||||
let text = read_session_text(path)?;
|
||||
let mut s = Session::from_json(&text).map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
let mut missing = Vec::new();
|
||||
@@ -98,6 +98,96 @@ mod save_tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// A new, empty scratch folder, removed again when the test ends, passed or not.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(tag: &str) -> Scratch {
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Scratch(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_file_too_large_to_parse_is_refused_unread() {
|
||||
// #892: a session file is read whole and parsed; past the cap it is refused by its size.
|
||||
// The file's length is set, not written, so it takes no time or space to make.
|
||||
let dir = Scratch::new("huge-session");
|
||||
let path = dir.0.join("Huge.scraft");
|
||||
std::fs::File::create(&path).unwrap().set_len(crate::io::MAX_SESSION_BYTES + 1).unwrap();
|
||||
let mut e = crate::demo::demo_engine();
|
||||
let err = open_session(&mut e, &path).unwrap_err().to_string();
|
||||
assert_eq!(err, format!("{} is too large to open (over 256 MiB)", path.display()));
|
||||
assert_eq!(e.session().tracks.len(), crate::demo::demo_engine().session().tracks.len());
|
||||
let err = e.execute("file.import_session_data", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(err.contains("too large to open"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_too_large_to_open_is_not_saved_and_leaves_nothing_behind() {
|
||||
// #892: what SoundCraft saves, it opens again. A refused save writes no audio and no
|
||||
// session; the limit is lowered for this test so a small session reaches it.
|
||||
let dir = Scratch::new("refused-save");
|
||||
let path = |p: &str| dir.0.join(p).to_string_lossy().into_owned();
|
||||
save_session(&mut with_take(0.5), &path("A/Song.scraft")).unwrap();
|
||||
let saved = std::fs::metadata(path("A/Song.scraft")).unwrap().len();
|
||||
let untouched = |sub: &str| assert!(!dir.0.join(sub).exists(), "{sub} was written");
|
||||
{
|
||||
let _limit = crate::io::SessionLimit::set(saved - 1);
|
||||
let mut e = with_take(0.5);
|
||||
let err = save_session(&mut e, &path("B/Song.scraft")).unwrap_err().to_string();
|
||||
assert_eq!(err, format!("{} is too large to save: over {} bytes, more than SoundCraft opens", path("B/Song.scraft"), saved - 1));
|
||||
assert!(e.is_dirty() && e.path.is_none());
|
||||
let err = e.execute("session.save_copy", &json!({"path": path("C/Song.scraft")})).unwrap_err().to_string();
|
||||
assert!(err.contains("too large to save"), "{err}");
|
||||
for sub in ["B", "C"] {
|
||||
untouched(sub);
|
||||
}
|
||||
// An open refuses the session saved before, now over the limit.
|
||||
let err = open_session(&mut Engine::default(), path("A/Song.scraft")).unwrap_err().to_string();
|
||||
assert!(err.contains("too large to open"), "{err}");
|
||||
}
|
||||
{
|
||||
// A template holds no audio or clips: a smaller limit refuses it.
|
||||
let _limit = crate::io::SessionLimit::set(100);
|
||||
std::fs::create_dir_all(dir.0.join("D")).unwrap();
|
||||
let err = with_take(0.5).execute("session.save_template", &json!({"path": path("D/Song.scraft")})).unwrap_err().to_string();
|
||||
assert!(err.contains("too large to save"), "{err}");
|
||||
untouched("D/Song.scraft");
|
||||
}
|
||||
// Checked before the audio file is named, against the longest name it can get: a
|
||||
// session at the limit plus that margin is saved, and is the same size as before.
|
||||
let _limit = crate::io::SessionLimit::set(saved + 5);
|
||||
save_session(&mut with_take(0.5), &path("B/Song.scraft")).unwrap();
|
||||
assert_eq!(std::fs::metadata(path("B/Song.scraft")).unwrap().len(), saved);
|
||||
assert_eq!(reopen(&path("B/Song.scraft")).session().sources.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_session_parses_as_it_did_through_a_tree() {
|
||||
// #892: parsing the text directly gives the document the `Value` round trip gave.
|
||||
let mut e = crate::demo::demo_engine();
|
||||
e.execute("mix.volume", &json!({"track": "Kick", "db": -7.0})).unwrap();
|
||||
let text = e.session().to_json().unwrap();
|
||||
let mut old: Session = serde_json::from_value(serde_json::from_str(&text).unwrap()).unwrap();
|
||||
old.sanitize();
|
||||
assert_eq!(Session::from_json(&text).unwrap(), old);
|
||||
let mut r = Engine::default();
|
||||
let dir = Scratch::new("reparse");
|
||||
let path = dir.0.join("Song.scraft").to_string_lossy().into_owned();
|
||||
save_session(&mut e, &path).unwrap();
|
||||
assert_eq!(open_session(&mut r, &path).unwrap(), Vec::<String>::new());
|
||||
assert_eq!(r.session().tracks, e.session().tracks);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_copy_leaves_document_untouched_and_reuses_audio() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
|
||||
+107
-1
@@ -119,6 +119,8 @@ pub struct Clipboard {
|
||||
pub markers: Vec<soundcraft_model::MemoryLocation>,
|
||||
/// How far the copied range started after a grid line; Relative Grid pastes keep it.
|
||||
pub grid_offset: Samples,
|
||||
/// Original insertion point when the clipboard was populated by Cut.
|
||||
pub cut_from: Option<Samples>,
|
||||
/// Copy Special › Automation: pasting it leaves the clips alone, in Shuffle mode too.
|
||||
pub automation_only: bool,
|
||||
/// The Auto Rename schemes of the copied clips, keyed as in their `auto_name`.
|
||||
@@ -128,7 +130,7 @@ pub struct Clipboard {
|
||||
impl Clipboard {
|
||||
/// An empty clipboard for material copied from `range`.
|
||||
pub fn of_range(s: &Session, range: soundcraft_time::Range) -> Clipboard {
|
||||
let line = s.edit.grid.line_at_or_before(range.start, s.sample_rate, &s.tempo, s.frame_rate);
|
||||
let line = s.grid_line_at_or_before(range.start);
|
||||
Clipboard { length: range.len(), grid_offset: range.start.saturating_sub(line), ..Clipboard::default() }
|
||||
}
|
||||
|
||||
@@ -279,6 +281,13 @@ impl Engine {
|
||||
Arc::make_mut(&mut self.doc)
|
||||
}
|
||||
|
||||
/// Mutable access for live state that redraws and reaches playback but is not part of the
|
||||
/// saved document. Callers must also keep the fields out of serialization and Undo/Redo.
|
||||
pub(crate) fn runtime_session_mut(&mut self) -> &mut Session {
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
Arc::make_mut(&mut self.doc)
|
||||
}
|
||||
|
||||
/// Like `session_mut`, for `edit.zoom` only and without bumping `revision`.
|
||||
pub fn zoom_mut(&mut self) -> &mut ZoomState {
|
||||
self.dirty = true;
|
||||
@@ -334,20 +343,34 @@ impl Engine {
|
||||
self.undo.iter().map(|h| h.label.clone()).collect()
|
||||
}
|
||||
|
||||
/// Bound Undo and Redo together, dropping farthest redo entries before oldest undo entries.
|
||||
pub fn set_history_limit(&mut self, limit: usize) {
|
||||
let limit = limit.max(1);
|
||||
self.history_limit = limit;
|
||||
let excess = self.undo.len().saturating_add(self.redo.len()).saturating_sub(limit);
|
||||
let from_redo = excess.min(self.redo.len());
|
||||
self.redo.drain(..from_redo);
|
||||
self.undo.drain(..excess - from_redo);
|
||||
}
|
||||
|
||||
/// Restore the previous document while retaining current edit mode and live input flags.
|
||||
pub fn undo(&mut self) -> bool {
|
||||
let Some(h) = self.undo.pop() else { return false };
|
||||
let cur = std::mem::replace(&mut self.doc, h.doc);
|
||||
self.keep_edit_mode(&cur);
|
||||
self.keep_runtime_track_states(&cur);
|
||||
self.redo.push(HistoryEntry { label: h.label, doc: cur });
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.dirty = true;
|
||||
true
|
||||
}
|
||||
|
||||
/// Restore the next document while retaining current edit mode and live input flags.
|
||||
pub fn redo(&mut self) -> bool {
|
||||
let Some(h) = self.redo.pop() else { return false };
|
||||
let cur = std::mem::replace(&mut self.doc, h.doc);
|
||||
self.keep_edit_mode(&cur);
|
||||
self.keep_runtime_track_states(&cur);
|
||||
self.undo.push(HistoryEntry { label: h.label, doc: cur });
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.dirty = true;
|
||||
@@ -368,6 +391,25 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo and Redo must not restore live input states captured in document snapshots. A track
|
||||
/// absent from the current document comes back safe rather than inheriting a historical arm.
|
||||
fn keep_runtime_track_states(&mut self, from: &Session) {
|
||||
let states: std::collections::HashMap<_, _> = from
|
||||
.tracks
|
||||
.iter()
|
||||
.filter(|track| track.mixer.record_arm || track.mixer.input_monitor)
|
||||
.map(|track| (track.id, (track.mixer.record_arm, track.mixer.input_monitor)))
|
||||
.collect();
|
||||
let state = |id| states.get(&id).copied().unwrap_or((false, false));
|
||||
// Keep shared snapshots untouched when the restored flags already match.
|
||||
if self.doc.tracks.iter().all(|track| (track.mixer.record_arm, track.mixer.input_monitor) == state(track.id)) {
|
||||
return;
|
||||
}
|
||||
for track in &mut Arc::make_mut(&mut self.doc).tracks {
|
||||
(track.mixer.record_arm, track.mixer.input_monitor) = state(track.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record an undo point manually (for interactive gestures committed by the UI).
|
||||
pub fn push_undo(&mut self, label: &str, before: Arc<Session>) {
|
||||
if Arc::ptr_eq(&before, &self.doc) {
|
||||
@@ -684,6 +726,59 @@ mod merge_tests {
|
||||
mod dirty_tests {
|
||||
use super::*;
|
||||
|
||||
/// Lowering the cap immediately removes the oldest retained Undo steps.
|
||||
#[test]
|
||||
fn reducing_the_history_limit_drops_the_oldest_steps_immediately() {
|
||||
let mut e = Engine::default();
|
||||
for _ in 0..4 {
|
||||
e.execute("track.new", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(e.undo_history().len(), 4);
|
||||
e.set_history_limit(2);
|
||||
assert_eq!(e.undo_history().len(), 2);
|
||||
assert!(e.undo());
|
||||
assert!(e.undo());
|
||||
assert!(!e.undo());
|
||||
}
|
||||
|
||||
/// A shared history cap retains the closest redo steps without letting either direction exceed it.
|
||||
#[test]
|
||||
fn lowering_history_limit_bounds_undo_and_redo_together() {
|
||||
for (requested, past, future) in [(0, 1, 0), (1, 1, 0), (2, 2, 0), (3, 2, 1), (4, 2, 2), (5, 2, 3), (usize::MAX, 2, 3)] {
|
||||
let mut e = Engine::default();
|
||||
for _ in 0..5 {
|
||||
e.execute("track.new", &json!({})).unwrap();
|
||||
}
|
||||
for _ in 0..3 {
|
||||
assert!(e.undo());
|
||||
}
|
||||
e.mark_clean();
|
||||
e.set_history_limit(requested);
|
||||
let limit = requested.max(1);
|
||||
assert_eq!(e.history_limit, limit);
|
||||
assert_eq!((e.undo.len(), e.redo.len()), (past, future), "requested {requested}");
|
||||
assert!(!e.is_dirty(), "history capacity is not a document edit");
|
||||
assert_eq!(e.session().tracks.len(), 2);
|
||||
for step in 1..=future {
|
||||
assert!(e.redo());
|
||||
assert_eq!(e.session().tracks.len(), 2 + step, "keep the nearest redo entries");
|
||||
assert!(e.undo.len() + e.redo.len() <= limit);
|
||||
}
|
||||
assert!(!e.redo());
|
||||
for step in 1..=past + future {
|
||||
assert!(e.undo());
|
||||
assert_eq!(e.session().tracks.len(), 2 + future - step, "keep the nearest undo entries");
|
||||
assert!(e.undo.len() + e.redo.len() <= limit);
|
||||
}
|
||||
assert!(!e.undo());
|
||||
for _ in 0..past + future {
|
||||
assert!(e.redo());
|
||||
assert!(e.undo.len() + e.redo.len() <= limit);
|
||||
}
|
||||
assert!(!e.redo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_locating_and_zooming_leave_the_session_clean() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
@@ -703,6 +798,17 @@ mod dirty_tests {
|
||||
assert!(!e.is_dirty());
|
||||
}
|
||||
|
||||
/// Unchanged runtime flags do not detach a shared document snapshot.
|
||||
#[test]
|
||||
fn matching_live_states_keep_the_document_shared() {
|
||||
let mut e = Engine::default();
|
||||
let track = e.session_mut().add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::Mono, None);
|
||||
e.runtime_session_mut().track_mut(track).unwrap().mixer.record_arm = true;
|
||||
let snapshot = e.session_arc();
|
||||
e.keep_runtime_track_states(&snapshot);
|
||||
assert!(Arc::ptr_eq(&snapshot, &e.session_arc()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirty_state_follows_save_undo_and_redo_after_navigation() {
|
||||
let mut e = Engine::default();
|
||||
|
||||
@@ -418,7 +418,9 @@ fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result<Str
|
||||
const STAFF_GAP: f64 = 70.0;
|
||||
const SYSTEM_GAP: f64 = 40.0;
|
||||
let n_measures = parts.iter().map(|p| p.measures.len()).max().unwrap_or(0);
|
||||
let per = setup.bars_per_system.max(1) as usize;
|
||||
// The layout range the setup offers (1 to 16): a caller's own value can't multiply the
|
||||
// barlines drawn per system beyond it.
|
||||
let per = setup.bars_per_system.clamp(1, 16) as usize;
|
||||
let systems = n_measures.div_ceil(per).max(1);
|
||||
let label_w = if setup.show_track_names { 70.0 } else { 0.0 };
|
||||
let staff_x0 = MARGIN + label_w + 34.0;
|
||||
@@ -782,6 +784,14 @@ mod tests {
|
||||
assert!(m.items.iter().any(|i| i.pitches.is_empty()), "the discarded suffix became rests");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bars_per_system_is_held_to_the_supported_range() {
|
||||
let setup = ScoreSetup { title: "t".into(), composer: String::new(), bars_per_system: u32::MAX, show_track_names: false };
|
||||
let part = Part { name: "p".into(), bass: false, measures: vec![Measure { numerator: 4, denominator: 4, items: Vec::new() }] };
|
||||
let out = svg_budgeted(std::slice::from_ref(&part), &setup, 1 << 20).unwrap();
|
||||
assert_eq!(out.matches("stroke-width=\"1\"").count(), 16, "sixteen barlines, not billions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_title_is_refused_by_the_header_check() {
|
||||
// An oversized part name/title must be caught by the header check even with no measures:
|
||||
|
||||
@@ -220,6 +220,129 @@ fn relative_grid_pastes_keep_the_offset_from_the_grid() {
|
||||
assert_eq!(clips(&e, t).last(), Some(&(5 * step, 1000)));
|
||||
}
|
||||
|
||||
/// A relative paste restores the insertion point even when Cut creates a new boundary there.
|
||||
#[test]
|
||||
fn relative_grid_cut_pastes_back_at_its_insertion_boundary() {
|
||||
let (mut e, t, _) = long("relative_grid", &[(1_000, 2_000, 0)]);
|
||||
run(&mut e, "view.grid", json!({"format": "clips_markers", "follow_main": false}));
|
||||
run(&mut e, "edit.cut", json!({"tracks": [t.0], "start": 1_500, "end": 2_000}));
|
||||
run(&mut e, "edit.paste", json!({"tracks": [t.0]}));
|
||||
assert_eq!(e.session().edit.selection.start, 1_500);
|
||||
assert!(clips(&e, t).contains(&(1_500, 500)), "{:?}", clips(&e, t));
|
||||
}
|
||||
|
||||
/// Moving a group excludes all its clips from Clips/Markers snap candidates.
|
||||
#[test]
|
||||
fn clips_markers_grid_ignores_every_clip_being_moved() {
|
||||
let (mut e, _, ids) = long("grid", &[(1_000, 1_000, 0), (4_000, 500, 2_000)]);
|
||||
e.session_mut().add_marker("Target", soundcraft_model::MarkerKind::Marker, 2_500, 2_500);
|
||||
run(&mut e, "view.grid", json!({"format": "clips_markers", "follow_main": false}));
|
||||
run(&mut e, "edit.move_clips", json!({"clips": [ids[0].0, ids[1].0], "to": 1_000}));
|
||||
assert_eq!([start(&e, ids[0]), start(&e, ids[1])], [1_000, 4_000]);
|
||||
run(&mut e, "edit.move_clips", json!({"clips": [ids[0].0, ids[1].0], "to": 2_200}));
|
||||
assert_eq!(start(&e, ids[0]), 2_500);
|
||||
assert_eq!(start(&e, ids[1]), 5_500);
|
||||
}
|
||||
|
||||
/// Zero and clamped moves preserve overlaps while off-grid quantization still changes position.
|
||||
#[test]
|
||||
fn zero_distance_move_keeps_overlapping_material_and_quantize_still_moves() {
|
||||
let (mut e, t, ids) = long("slip", &[(1_000, 1_000, 0), (1_500, 1_000, 2_000)]);
|
||||
let before = material(&e, t);
|
||||
run(&mut e, "edit.move_clips", json!({"clips": [ids[0].0], "by": 0}));
|
||||
assert_eq!(material(&e, t), before);
|
||||
|
||||
run(&mut e, "edit.select", json!({"clips": [ids[0].0]}));
|
||||
run(&mut e, "clip.quantize_to_grid", json!({}));
|
||||
assert_eq!(start(&e, ids[0]), 0);
|
||||
|
||||
let (mut e, t, ids) = long("slip", &[(0, 1_000, 0), (500, 1_000, 2_000)]);
|
||||
let before = material(&e, t);
|
||||
run(&mut e, "edit.move_clips", json!({"clips": [ids[0].0], "by": -1_000}));
|
||||
assert_eq!(material(&e, t), before);
|
||||
}
|
||||
|
||||
/// A vertical move remains a real edit and snaps its off-grid start on the destination track.
|
||||
#[test]
|
||||
fn zero_horizontal_grid_move_to_another_track_still_snaps() {
|
||||
let (mut e, _, [_, clip]) = engine("grid");
|
||||
let destination = new_track(&mut e);
|
||||
run(&mut e, "edit.move_clips", json!({"clips": [clip.0], "to": 2_000, "track": destination.0}));
|
||||
let (track, moved) = e.session().find_clip(clip).unwrap();
|
||||
assert_eq!(track, destination);
|
||||
assert_eq!(moved.start, 0);
|
||||
}
|
||||
|
||||
/// Nudge and quantization must preserve overlapping material when the clip cannot move.
|
||||
#[test]
|
||||
fn stationary_nudges_and_quantization_preserve_overlaps() {
|
||||
for (command, params) in [("edit.nudge", json!({"direction": -1})), ("clip.quantize_to_grid", json!({}))] {
|
||||
let (mut e, t, ids) = long("slip", &[(0, 1_000, 0), (500, 1_000, 2_000)]);
|
||||
run(&mut e, "edit.select", json!({"clips": [ids[0].0]}));
|
||||
let before = e.session().track(t).unwrap().clips().to_vec();
|
||||
let result = e.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(e.session().track(t).unwrap().clips(), before, "{command}");
|
||||
if command == "edit.nudge" {
|
||||
assert_eq!(result["moved"], 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every Nudge scale shifts clips and insertion across a tempo change and drop-frame rates.
|
||||
#[test]
|
||||
fn every_nudge_scale_moves_by_its_selected_increment() {
|
||||
use soundcraft_time::{FrameRate, SampleRate, TICKS_PER_QUARTER};
|
||||
for rate in [FrameRate::Fps30, FrameRate::Fps29_97Drop, FrameRate::Fps59_94Drop] {
|
||||
for at in [48_000, 144_000] {
|
||||
let cases = [
|
||||
(json!("1/4"), if at < 96_000 { 24_000 } else { 32_000 }),
|
||||
(json!({"seconds": 0.5}), 24_000),
|
||||
(json!({"timecode": "5_frames"}), rate.samples_at_frame(5, SampleRate::HZ_48000)),
|
||||
(json!({"feet_frames": "foot"}), rate.samples_at_frame(16, SampleRate::HZ_48000)),
|
||||
(json!({"samples": 100}), 100),
|
||||
];
|
||||
for (value, expected) in cases {
|
||||
let (mut e, track, ids) = long("slip", &[(at, 1_000, 0)]);
|
||||
e.session_mut().frame_rate = rate;
|
||||
e.session_mut().tempo.set_tempo(TICKS_PER_QUARTER * 4, 90.0).unwrap();
|
||||
run(&mut e, "edit.select", json!({"tracks": [track.0], "clips": [ids[0].0], "start": at, "end": at}));
|
||||
run(&mut e, "view.nudge", json!({"value": value, "follow_main": false}));
|
||||
let result = e.execute("edit.nudge", &json!({"direction": 1})).unwrap();
|
||||
assert_eq!(result["by"], expected, "{rate:?} at {at}");
|
||||
assert_eq!(result["moved"], 1);
|
||||
assert_eq!(start(&e, ids[0]), at + expected);
|
||||
assert_eq!(e.session().edit.selection.start, at + expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Separation refuses oversized numeric grids before splitting any material.
|
||||
#[test]
|
||||
fn separate_on_grid_refuses_a_truncated_boundary_set() {
|
||||
let (mut e, t, _) = long("grid", &[(0, 20_000, 0)]);
|
||||
run(&mut e, "view.grid", json!({"value": {"samples": 1}, "follow_main": false}));
|
||||
assert!(e.execute("edit.separate_on_grid", &json!({"tracks": [t.0], "start": 0, "end": 10_002})).is_err());
|
||||
assert_eq!(clips(&e, t), [(0, 20_000)]);
|
||||
}
|
||||
|
||||
/// Display thinning must never hide an oversized Clips/Markers separation request.
|
||||
#[test]
|
||||
fn separate_on_grid_refuses_dense_markers_before_changing_clips() {
|
||||
let (mut e, track, _) = long("grid", &[(0, 100_000, 0)]);
|
||||
let s = e.session_mut();
|
||||
for at in 1..=10_001 {
|
||||
s.add_marker("Boundary", soundcraft_model::MarkerKind::Marker, at, at);
|
||||
}
|
||||
run(&mut e, "view.grid", json!({"format": "clips_markers", "follow_main": false}));
|
||||
let before = e.session().clone();
|
||||
let undo_len = e.undo_history().len();
|
||||
let error = e.execute("edit.separate_on_grid", &json!({"tracks": [track.0], "start": 0, "end": 100_000})).unwrap_err();
|
||||
assert!(error.to_string().contains("10,000"), "{error}");
|
||||
assert_eq!(e.session(), &before);
|
||||
assert_eq!(e.undo_history().len(), undo_len);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_moves_keep_crossfade_partners_whole() {
|
||||
let (mut e, t, ids) = long("slip", &[(0, 1000, 10_000), (1000, 1000, 20_000), (2000, 1000, 30_000)]);
|
||||
|
||||
@@ -502,9 +502,11 @@ pub struct Mixer {
|
||||
pub solo: bool,
|
||||
#[serde(default)]
|
||||
pub solo_safe: bool,
|
||||
#[serde(default)]
|
||||
/// Live record-enable state. Runtime-only: opening a session must never arm an input.
|
||||
#[serde(skip)]
|
||||
pub record_arm: bool,
|
||||
#[serde(default)]
|
||||
/// Live input-monitor state. Runtime-only: opening a session must never enable monitoring.
|
||||
#[serde(skip)]
|
||||
pub input_monitor: bool,
|
||||
#[serde(default)]
|
||||
pub phase_invert: bool,
|
||||
|
||||
+375
-4
@@ -5,7 +5,7 @@ use crate::{
|
||||
Bus, BusId, ChannelFormat, Clip, ClipId, Group, GroupId, MarkerId, MarkerKind, MemoryLocation, OutputPath, Source, SourceId, SourcePool,
|
||||
TRACK_COLORS, Track, TrackId, TrackKind, VideoSource,
|
||||
};
|
||||
use soundcraft_time::{FrameRate, GridValue, Range, SampleRate, Samples, TempoMap, TimeFormat};
|
||||
use soundcraft_time::{FrameRate, GridScale, GridValue, Range, SampleRate, Samples, TempoMap, TimeFormat};
|
||||
|
||||
/// Native session file extension.
|
||||
pub const SESSION_EXTENSION: &str = "scraft";
|
||||
@@ -147,6 +147,7 @@ pub struct ZoomState {
|
||||
}
|
||||
|
||||
impl Default for ZoomState {
|
||||
/// Starts with a practical overview zoom and five reusable preset levels.
|
||||
fn default() -> Self {
|
||||
ZoomState { samples_per_px: 1024.0, scroll: 0, waveform_zoom: 1.0, presets: [64.0, 256.0, 1024.0, 4096.0, 16384.0] }
|
||||
}
|
||||
@@ -179,6 +180,15 @@ pub struct EditState {
|
||||
pub playhead: Samples,
|
||||
pub grid: GridValue,
|
||||
pub nudge: GridValue,
|
||||
/// Grid/Nudge time scales follow the main counter when enabled.
|
||||
#[serde(default)]
|
||||
pub grid_follow_main: bool,
|
||||
#[serde(default)]
|
||||
pub nudge_follow_main: bool,
|
||||
/// Grid lines and snapping use visible clip boundaries and memory locations while the numeric
|
||||
/// Grid value is retained for when this mode is left.
|
||||
#[serde(default)]
|
||||
pub grid_clips_markers: bool,
|
||||
#[serde(default = "yes")]
|
||||
pub grid_lines: bool,
|
||||
pub main_counter: TimeFormat,
|
||||
@@ -244,6 +254,7 @@ fn yes() -> bool {
|
||||
}
|
||||
|
||||
impl Default for EditState {
|
||||
/// Starts the Edit window in Slip mode with independent Grid and Nudge scales.
|
||||
fn default() -> Self {
|
||||
EditState {
|
||||
tool: Tool::Smart,
|
||||
@@ -255,6 +266,9 @@ impl Default for EditState {
|
||||
playhead: 0,
|
||||
grid: GridValue::default(),
|
||||
nudge: GridValue::Seconds(1.0),
|
||||
grid_follow_main: false,
|
||||
nudge_follow_main: false,
|
||||
grid_clips_markers: false,
|
||||
grid_lines: true,
|
||||
main_counter: TimeFormat::MinSecs,
|
||||
sub_counter: Some(TimeFormat::Samples),
|
||||
@@ -490,6 +504,138 @@ impl Session {
|
||||
soundcraft_time::parse_position(text, fmt, self.sample_rate, &self.tempo, self.frame_rate, self.timecode_start, self.feet_frames_start())
|
||||
}
|
||||
|
||||
/// Whether the Edit window shows a track: unhidden, with every parent folder open.
|
||||
pub fn track_shown(&self, track: &Track) -> bool {
|
||||
if track.hidden {
|
||||
return false;
|
||||
}
|
||||
let mut folder = track.folder;
|
||||
for _ in 0..64 {
|
||||
let Some(parent) = folder.and_then(|id| self.track(id)) else { return true };
|
||||
if !parent.folder_open {
|
||||
return false;
|
||||
}
|
||||
folder = parent.folder;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Collects unique visible active-playlist clip boundaries and memory-location boundaries.
|
||||
fn clip_marker_grid_points(&self, keep: impl Fn(Samples) -> bool, excluded: &[ClipId], include_zero: bool) -> Vec<Samples> {
|
||||
let mut points = Vec::new();
|
||||
let excluded: std::collections::HashSet<ClipId> = excluded.iter().copied().collect();
|
||||
if include_zero && keep(0) {
|
||||
points.push(0);
|
||||
}
|
||||
for clip in
|
||||
self.tracks.iter().filter(|track| self.track_shown(track)).flat_map(|track| track.clips()).filter(|clip| !excluded.contains(&clip.id))
|
||||
{
|
||||
points.extend([clip.start, clip.end()].into_iter().filter(|point| keep(*point)));
|
||||
}
|
||||
for marker in &self.markers {
|
||||
if keep(marker.start) {
|
||||
points.push(marker.start);
|
||||
}
|
||||
if marker.end != marker.start && keep(marker.end) {
|
||||
points.push(marker.end);
|
||||
}
|
||||
}
|
||||
points.sort_unstable();
|
||||
points.dedup();
|
||||
points
|
||||
}
|
||||
|
||||
/// Sample-domain Timecode reference; Feet+Frames applies its origin in frames separately.
|
||||
fn grid_origin(&self) -> Samples {
|
||||
match self.edit.grid.scale() {
|
||||
GridScale::Timecode => self.timecode_start,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Grid lines for the current Grid value, including clip and marker boundaries.
|
||||
pub fn grid_lines(&self, start: Samples, end: Samples, max: usize) -> Vec<Samples> {
|
||||
if !self.edit.grid_clips_markers {
|
||||
if let GridValue::FeetFrames(value) = self.edit.grid {
|
||||
return value.lines(start, end, self.sample_rate, self.frame_rate, self.feet_frames_start(), max);
|
||||
}
|
||||
let origin = self.grid_origin();
|
||||
return self
|
||||
.edit
|
||||
.grid
|
||||
.lines(start.saturating_add(origin), end.saturating_add(origin), self.sample_rate, &self.tempo, self.frame_rate, max)
|
||||
.into_iter()
|
||||
.map(|point| point.saturating_sub(origin))
|
||||
.collect();
|
||||
}
|
||||
let points = self.clip_marker_grid_points(|point| point >= start && point < end, &[], true);
|
||||
if points.len() <= max {
|
||||
return points;
|
||||
}
|
||||
match max {
|
||||
0 => Vec::new(),
|
||||
1 => points.first().copied().into_iter().collect(),
|
||||
_ => {
|
||||
let span = i128::from(end).saturating_sub(i128::from(start)).max(1);
|
||||
let mut bucket = None;
|
||||
points
|
||||
.into_iter()
|
||||
.filter(|point| {
|
||||
let next = i128::from(*point).saturating_sub(i128::from(start)).saturating_mul(max as i128) / span;
|
||||
if bucket == Some(next) {
|
||||
false
|
||||
} else {
|
||||
bucket = Some(next);
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The current Grid line at or before `position`.
|
||||
pub fn grid_line_at_or_before(&self, position: Samples) -> Samples {
|
||||
self.grid_line_at_or_before_excluding(position, &[])
|
||||
}
|
||||
|
||||
/// Find the current Grid line at or before `position` without boundaries of `excluded` clips.
|
||||
pub fn grid_line_at_or_before_excluding(&self, position: Samples, excluded: &[ClipId]) -> Samples {
|
||||
if !self.edit.grid_clips_markers {
|
||||
if let GridValue::FeetFrames(value) = self.edit.grid {
|
||||
return value.line_at_or_before(position, self.sample_rate, self.frame_rate, self.feet_frames_start());
|
||||
}
|
||||
let origin = self.grid_origin();
|
||||
return self
|
||||
.edit
|
||||
.grid
|
||||
.line_at_or_before(position.saturating_add(origin), self.sample_rate, &self.tempo, self.frame_rate)
|
||||
.saturating_sub(origin);
|
||||
}
|
||||
self.clip_marker_grid_points(|_| true, excluded, true).into_iter().take_while(|point| *point <= position).last().unwrap_or(position)
|
||||
}
|
||||
|
||||
/// Snap to the nearest line in the current Grid.
|
||||
pub fn snap_to_grid(&self, position: Samples) -> Samples {
|
||||
self.snap_to_grid_excluding(position, &[])
|
||||
}
|
||||
|
||||
/// Snap to the nearest current Grid line without using boundaries of `excluded` clips.
|
||||
pub fn snap_to_grid_excluding(&self, position: Samples, excluded: &[ClipId]) -> Samples {
|
||||
if !self.edit.grid_clips_markers {
|
||||
if let GridValue::FeetFrames(value) = self.edit.grid {
|
||||
return value.snap(position, self.sample_rate, self.frame_rate, self.feet_frames_start());
|
||||
}
|
||||
let origin = self.grid_origin();
|
||||
return self.edit.grid.snap(position.saturating_add(origin), self.sample_rate, &self.tempo, self.frame_rate).saturating_sub(origin);
|
||||
}
|
||||
let mut points = self.clip_marker_grid_points(|_| true, excluded, false);
|
||||
if !points.is_empty() {
|
||||
points.push(0);
|
||||
}
|
||||
points.into_iter().min_by_key(|point| i128::from(*point).saturating_sub(i128::from(position)).abs()).unwrap_or(position)
|
||||
}
|
||||
|
||||
pub fn next_track_color(&self) -> [u8; 3] {
|
||||
let n = self.tracks.iter().filter(|t| t.kind != TrackKind::Master).count();
|
||||
TRACK_COLORS.get(n % TRACK_COLORS.len()).copied().unwrap_or([128, 128, 128])
|
||||
@@ -578,13 +724,36 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Parse a session; decoded audio must be attached separately (`pool`).
|
||||
///
|
||||
/// The text is parsed straight into the document, never into a `serde_json::Value` tree
|
||||
/// first (which takes many times the file's size). Only the version is read before that.
|
||||
/// A field of the document given twice in one object is refused (`duplicate field`), as no
|
||||
/// writer repeats one. Keys of maps (plugin params, edit values, Auto Rename schemes, MIDI
|
||||
/// originals) and unknown keys keep the last value given, as before.
|
||||
pub fn from_json(text: &str) -> Result<Session, SessionError> {
|
||||
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| SessionError::Format(e.to_string()))?;
|
||||
let ver = v.get("format_version").and_then(serde_json::Value::as_u64).ok_or_else(|| SessionError::Format("missing format_version".into()))?;
|
||||
/// The version alone: every other field is skipped, not kept.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Head {
|
||||
format_version: Option<serde_json::Number>,
|
||||
}
|
||||
// `Head` would also take a JSON array as its fields in order: only an object has a version.
|
||||
let object = text.trim_start_matches([' ', '\t', '\n', '\r']).starts_with('{');
|
||||
let version = match object.then(|| serde_json::from_str::<Head>(text)) {
|
||||
Some(Ok(head)) => head.format_version,
|
||||
// A version given twice is that error, not a missing version.
|
||||
Some(Err(e)) if e.to_string().starts_with("duplicate field") => return Err(SessionError::Format(e.to_string())),
|
||||
// Valid JSON of another shape (not an object, or a version that is not a number)
|
||||
// has no version; anything else is not JSON.
|
||||
_ => {
|
||||
serde_json::from_str::<serde::de::IgnoredAny>(text).map_err(|e| SessionError::Format(e.to_string()))?;
|
||||
None
|
||||
}
|
||||
};
|
||||
let ver = version.and_then(|v| v.as_u64()).ok_or_else(|| SessionError::Format("missing format_version".into()))?;
|
||||
if ver > u64::from(Self::FORMAT_VERSION) {
|
||||
return Err(SessionError::Version(u32::try_from(ver).unwrap_or(u32::MAX)));
|
||||
}
|
||||
let mut s: Session = serde_json::from_value(v).map_err(|e| SessionError::Format(e.to_string()))?;
|
||||
let mut s: Session = serde_json::from_str(text).map_err(|e| SessionError::Format(e.to_string()))?;
|
||||
s.sanitize();
|
||||
s.validate()?;
|
||||
Ok(s)
|
||||
@@ -762,6 +931,136 @@ mod tests {
|
||||
assert_eq!(back, s);
|
||||
}
|
||||
|
||||
/// Clips/Markers mode snaps and draws at clip and memory-location boundaries.
|
||||
#[test]
|
||||
fn clips_markers_grid_uses_visible_clip_edges_and_memory_locations() {
|
||||
let mut s = Session::default();
|
||||
let track = s.add_track(TrackKind::Midi, ChannelFormat::Mono, None);
|
||||
let clip = Clip::midi(s.new_clip_id(), "Notes", 1_000, 2_000, soundcraft_midi::Sequence::default());
|
||||
let clip_id = clip.id;
|
||||
s.track_mut(track).and_then(Track::playlist_mut).unwrap().clips.push(clip);
|
||||
let hidden = s.add_track(TrackKind::Midi, ChannelFormat::Mono, None);
|
||||
let hidden_clip = Clip::midi(s.new_clip_id(), "Hidden", 3_200, 100, soundcraft_midi::Sequence::default());
|
||||
if let Some(track) = s.track_mut(hidden) {
|
||||
track.hidden = true;
|
||||
track.playlist_mut().unwrap().clips.push(hidden_clip);
|
||||
}
|
||||
s.add_marker("Cue", MarkerKind::Marker, 2_500, 2_500);
|
||||
s.add_marker("Selection", MarkerKind::Selection, 4_000, 4_500);
|
||||
s.edit.grid_clips_markers = true;
|
||||
|
||||
assert_eq!(s.grid_lines(0, 5_000, 20), [0, 1_000, 2_500, 3_000, 4_000, 4_500]);
|
||||
assert_eq!(s.grid_line_at_or_before(2_800), 2_500);
|
||||
assert_eq!(s.snap_to_grid(2_800), 3_000);
|
||||
assert_eq!(s.snap_to_grid(3_700), 4_000);
|
||||
assert_eq!(s.grid_lines(2_400, 4_100, 2), [2_500, 4_000]);
|
||||
assert_eq!(s.snap_to_grid(3_200), 3_000);
|
||||
assert_eq!(s.snap_to_grid_excluding(2_800, &[clip_id]), 2_500);
|
||||
|
||||
let folder = s.add_track(TrackKind::Folder, ChannelFormat::Stereo, None);
|
||||
s.track_mut(track).unwrap().folder = Some(folder);
|
||||
s.track_mut(folder).unwrap().folder_open = false;
|
||||
assert_eq!(s.grid_lines(0, 5_000, 20), [0, 2_500, 4_000, 4_500]);
|
||||
}
|
||||
|
||||
/// Open hidden folders keep their visible descendants eligible for lines and snapping.
|
||||
#[test]
|
||||
fn clips_markers_grid_keeps_visible_children_of_hidden_open_folders() {
|
||||
let mut s = Session::default();
|
||||
let outer = s.add_track(TrackKind::Folder, ChannelFormat::Stereo, None);
|
||||
let inner = s.add_track(TrackKind::Folder, ChannelFormat::Stereo, None);
|
||||
let child = s.add_track(TrackKind::Midi, ChannelFormat::Mono, None);
|
||||
let clip = Clip::midi(s.new_clip_id(), "Visible", 1_000, 2_000, soundcraft_midi::Sequence::default());
|
||||
s.track_mut(inner).unwrap().folder = Some(outer);
|
||||
s.track_mut(inner).unwrap().hidden = true;
|
||||
s.track_mut(child).unwrap().folder = Some(inner);
|
||||
s.track_mut(child).unwrap().playlist_mut().unwrap().clips.push(clip);
|
||||
s.edit.grid_clips_markers = true;
|
||||
|
||||
assert_eq!(s.grid_lines(0, 5_000, 20), [0, 1_000, 3_000]);
|
||||
assert_eq!(s.snap_to_grid(2_800), 3_000);
|
||||
assert_eq!(s.grid_line_at_or_before(2_800), 1_000);
|
||||
|
||||
s.track_mut(child).unwrap().hidden = true;
|
||||
assert_eq!(s.grid_lines(0, 5_000, 20), [0]);
|
||||
assert_eq!(s.snap_to_grid(2_800), 2_800);
|
||||
s.track_mut(child).unwrap().hidden = false;
|
||||
s.track_mut(inner).unwrap().folder_open = false;
|
||||
assert_eq!(s.grid_lines(0, 5_000, 20), [0]);
|
||||
s.track_mut(inner).unwrap().folder_open = true;
|
||||
s.track_mut(outer).unwrap().folder_open = false;
|
||||
assert_eq!(s.grid_lines(0, 5_000, 20), [0]);
|
||||
}
|
||||
|
||||
/// With no real Clips/Markers boundaries, snapping leaves the position alone while drawing
|
||||
/// retains the session-start line.
|
||||
#[test]
|
||||
fn empty_clips_markers_grid_does_not_snap_everything_to_zero() {
|
||||
let mut s = Session::default();
|
||||
s.edit.grid_clips_markers = true;
|
||||
assert_eq!(s.grid_lines(0, 1_000, 10), [0]);
|
||||
assert_eq!(s.snap_to_grid(678), 678);
|
||||
}
|
||||
|
||||
/// Frame-based grids share the same references as their displayed counters.
|
||||
#[test]
|
||||
fn frame_grids_apply_session_counter_origins() {
|
||||
let mut s = Session { sample_rate: SampleRate::HZ_48000, frame_rate: FrameRate::Fps30, timecode_start: 1_600, ..Session::default() };
|
||||
s.edit.grid = GridValue::Timecode(soundcraft_time::TimecodeValue::Second);
|
||||
assert_eq!(s.grid_line_at_or_before(47_000), 46_400);
|
||||
assert_eq!(s.snap_to_grid(46_400), 46_400);
|
||||
|
||||
s.edit.grid = GridValue::FeetFrames(soundcraft_time::FeetFramesValue::Foot);
|
||||
s.edit.values.insert(FEET_FRAMES_START.into(), 1.0);
|
||||
assert_eq!(s.grid_line_at_or_before(25_000), 24_000);
|
||||
assert_eq!(s.snap_to_grid(24_000), 24_000);
|
||||
}
|
||||
|
||||
/// Every Feet+Frames increment shares the parser's single rounding at fractional frame rates.
|
||||
#[test]
|
||||
fn feet_frames_grid_matches_parsed_positions_with_signed_frame_origins() {
|
||||
use soundcraft_time::FeetFramesValue;
|
||||
for rate in [FrameRate::Fps23_976, FrameRate::Fps29_97, FrameRate::Fps29_97Drop, FrameRate::Fps59_94Drop] {
|
||||
let mut s = Session { sample_rate: SampleRate::HZ_48000, frame_rate: rate, ..Session::default() };
|
||||
for origin in [-17, -1, 1, 17] {
|
||||
s.edit.values.insert(FEET_FRAMES_START.into(), origin as f64);
|
||||
for value in FeetFramesValue::ALL {
|
||||
s.edit.grid = GridValue::FeetFrames(value);
|
||||
for feet in [-64, -2, 0, 1, 2, 4, 7, 12, 128] {
|
||||
let at = s.parse_position(&format!("{feet}+00"), TimeFormat::FeetFrames).unwrap();
|
||||
assert_eq!(s.grid_line_at_or_before(at), at, "{rate:?} {value:?} origin {origin}, foot {feet}");
|
||||
assert_eq!(s.snap_to_grid(at), at);
|
||||
assert_eq!(s.grid_lines(at - 1, at + 2, 4), [at]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut s = Session { sample_rate: SampleRate::HZ_48000, frame_rate: FrameRate::Fps29_97, ..Session::default() };
|
||||
s.edit.values.insert(FEET_FRAMES_START.into(), 1.0);
|
||||
s.edit.grid = GridValue::FeetFrames(FeetFramesValue::Foot);
|
||||
assert_eq!(s.snap_to_grid(49_649), 49_650);
|
||||
assert_eq!(s.format_position(49_650, TimeFormat::FeetFrames), "2+00");
|
||||
}
|
||||
|
||||
/// Drop-frame minute boundaries keep their counter alignment with signed session origins.
|
||||
#[test]
|
||||
fn drop_frame_grids_apply_session_origins_at_minute_boundaries() {
|
||||
for (rate, minute_frame) in [(FrameRate::Fps29_97Drop, 1_800), (FrameRate::Fps59_94Drop, 3_600)] {
|
||||
for origin_frame in [-1, 1] {
|
||||
let sr = SampleRate::HZ_48000;
|
||||
let origin = rate.samples_at_frame(origin_frame, sr);
|
||||
let mut s = Session { sample_rate: sr, frame_rate: rate, timecode_start: origin, ..Session::default() };
|
||||
s.edit.grid = GridValue::Timecode(soundcraft_time::TimecodeValue::Second);
|
||||
for boundary in [-minute_frame, minute_frame] {
|
||||
let at = rate.samples_at_frame(boundary, sr) - origin;
|
||||
assert_eq!(s.grid_line_at_or_before(at), at, "{rate:?}, origin {origin_frame}");
|
||||
assert_eq!(s.snap_to_grid(at + 1), at, "{rate:?}, origin {origin_frame}");
|
||||
assert_eq!(s.grid_lines(at - 1, at + 2, 10), [at]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_with_legacy_fit_height_loads() {
|
||||
let mut s = Session::default();
|
||||
@@ -775,6 +1074,31 @@ mod tests {
|
||||
assert_eq!(back.track(t).map(|tr| tr.height), Some(crate::TrackHeight::Medium));
|
||||
}
|
||||
|
||||
/// Session JSON omits live flags and ignores their values in legacy documents.
|
||||
#[test]
|
||||
fn live_input_states_are_never_saved_or_restored() {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
let track = s.track_mut(t).unwrap();
|
||||
track.mixer.mute = true;
|
||||
track.mixer.record_arm = true;
|
||||
track.mixer.input_monitor = true;
|
||||
|
||||
let mut value = serde_json::to_value(&s).unwrap();
|
||||
let mixer = value["tracks"][0]["mixer"].as_object_mut().unwrap();
|
||||
assert!(!mixer.contains_key("record_arm"));
|
||||
assert!(!mixer.contains_key("input_monitor"));
|
||||
|
||||
// Files written by older versions may still contain these keys; ignore them on input.
|
||||
mixer.insert("record_arm".into(), serde_json::Value::Bool(true));
|
||||
mixer.insert("input_monitor".into(), serde_json::Value::Bool(true));
|
||||
let loaded = Session::from_json(&value.to_string()).unwrap();
|
||||
let track = loaded.track(t).unwrap();
|
||||
assert!(track.mixer.mute, "persistent mixer state still loads");
|
||||
assert!(!track.mixer.record_arm);
|
||||
assert!(!track.mixer.input_monitor);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn video_clip_round_trips_and_old_sessions_load() {
|
||||
let mut s = Session::default();
|
||||
@@ -864,6 +1188,53 @@ mod tests {
|
||||
assert!(matches!(Session::from_json(&v.to_string()), Err(SessionError::Version(999))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_version_is_checked_as_before() {
|
||||
// #892: the version is read without building the whole document as a tree; the errors
|
||||
// stay what they were.
|
||||
let format = |t: &str| match Session::from_json(t) {
|
||||
Err(SessionError::Format(m)) => m,
|
||||
other => panic!("{t}: {other:?}"),
|
||||
};
|
||||
for t in [
|
||||
"{}",
|
||||
"[]",
|
||||
"[5]",
|
||||
" \n[1, {}]",
|
||||
"\"x\"",
|
||||
"5",
|
||||
"null",
|
||||
r#"{"format_version":"1"}"#,
|
||||
r#"{"format_version":-1}"#,
|
||||
r#"{"format_version":1.5}"#,
|
||||
r#"{"format_version":null}"#,
|
||||
r#"{"format_version":[0,0,0]}"#,
|
||||
r#"{"name":"x","other":{"format_version":1}}"#,
|
||||
] {
|
||||
assert_eq!(format(t), "missing format_version", "{t}");
|
||||
}
|
||||
for t in ["not json", r#"{"format_version":1"#, r#"{"format_version":1} x"#, r#"{"format_version":"1", ]"#] {
|
||||
let want = serde_json::from_str::<serde_json::Value>(t).unwrap_err().to_string();
|
||||
assert_eq!(format(t), want, "{t}");
|
||||
}
|
||||
let mut v = serde_json::to_value(Session::default()).unwrap();
|
||||
for (ver, want) in [(serde_json::json!(2), 2), (serde_json::json!(1u64 << 40), u32::MAX)] {
|
||||
v["format_version"] = ver;
|
||||
assert_eq!(Session::from_json(&v.to_string()), Err(SessionError::Version(want)));
|
||||
}
|
||||
// A field given twice is refused by name, the version too.
|
||||
let twice = |key: &str| format(&format!(r#"{{"format_version":1,"{key}":"a","{key}":"b"}}"#));
|
||||
assert!(twice("name").starts_with("duplicate field `name` at line 1 column "), "{}", twice("name"));
|
||||
assert!(twice("format_version").starts_with("duplicate field `format_version` at line 1 column "), "{}", twice("format_version"));
|
||||
// A newer version is refused even when the rest would not parse.
|
||||
assert_eq!(Session::from_json(r#"{"format_version":7,"tracks":5}"#), Err(SessionError::Version(7)));
|
||||
// An older or the current version loads as it did.
|
||||
for ver in [0, 1] {
|
||||
v["format_version"] = serde_json::json!(ver);
|
||||
assert_eq!(Session::from_json(&v.to_string()).map(|s| s.format_version), Ok(ver));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_ids_are_rejected_on_load() {
|
||||
let mut s = Session::default();
|
||||
|
||||
+86
-37
@@ -83,8 +83,7 @@ impl TrackKind {
|
||||
}
|
||||
|
||||
/// Track heights (View › Track Height presets).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(from = "TrackHeightRepr")]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize)]
|
||||
pub enum TrackHeight {
|
||||
/// Any height from Micro to Extreme, in points.
|
||||
Custom(u16),
|
||||
@@ -100,49 +99,69 @@ pub enum TrackHeight {
|
||||
Fit(u16),
|
||||
}
|
||||
|
||||
/// What a saved track height may look like: the current form, or the bare `"Fit"` string older sessions used.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum TrackHeightRepr {
|
||||
Current(TrackHeightCurrent),
|
||||
LegacyFit(LegacyFit),
|
||||
/// A saved track height: `"Micro"` … `"Extreme"` (or `{"Micro": null}` …), `{"Custom": points}`,
|
||||
/// `{"Fit": points}`, or the bare `"Fit"` older sessions used. Read as it comes, never buffered (as an
|
||||
/// untagged enum would), so anything else in a session file is refused at its first token.
|
||||
impl<'de> serde::Deserialize<'de> for TrackHeight {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
d.deserialize_any(HeightVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
enum LegacyFit {
|
||||
Fit,
|
||||
const HEIGHT_VARIANTS: &[&str] = &["Custom", "Micro", "Mini", "Small", "Medium", "Large", "Jumbo", "Extreme", "Fit"];
|
||||
|
||||
struct HeightVisitor;
|
||||
|
||||
impl HeightVisitor {
|
||||
/// The height a variant without a size names.
|
||||
fn preset(name: &str) -> Option<TrackHeight> {
|
||||
Some(match name {
|
||||
"Micro" => TrackHeight::Micro,
|
||||
"Mini" => TrackHeight::Mini,
|
||||
"Small" => TrackHeight::Small,
|
||||
"Medium" => TrackHeight::Medium,
|
||||
"Large" => TrackHeight::Large,
|
||||
"Jumbo" => TrackHeight::Jumbo,
|
||||
"Extreme" => TrackHeight::Extreme,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror of `TrackHeight` that derives the current serialized form.
|
||||
#[derive(serde::Deserialize)]
|
||||
enum TrackHeightCurrent {
|
||||
Custom(u16),
|
||||
Micro,
|
||||
Mini,
|
||||
Small,
|
||||
Medium,
|
||||
Large,
|
||||
Jumbo,
|
||||
Extreme,
|
||||
Fit(u16),
|
||||
}
|
||||
impl<'de> serde::de::Visitor<'de> for HeightVisitor {
|
||||
type Value = TrackHeight;
|
||||
|
||||
impl From<TrackHeightRepr> for TrackHeight {
|
||||
fn from(repr: TrackHeightRepr) -> Self {
|
||||
match repr {
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Custom(p)) => TrackHeight::Custom(p),
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Micro) => TrackHeight::Micro,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Mini) => TrackHeight::Mini,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Small) => TrackHeight::Small,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Medium) => TrackHeight::Medium,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Large) => TrackHeight::Large,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Jumbo) => TrackHeight::Jumbo,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Extreme) => TrackHeight::Extreme,
|
||||
TrackHeightRepr::Current(TrackHeightCurrent::Fit(p)) => TrackHeight::Fit(p),
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a track height")
|
||||
}
|
||||
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<TrackHeight, E> {
|
||||
match v {
|
||||
// Older sessions stored Fit with no size, drawn 88 points tall: the default Medium height.
|
||||
TrackHeightRepr::LegacyFit(LegacyFit::Fit) => TrackHeight::Medium,
|
||||
"Fit" => Ok(TrackHeight::Medium),
|
||||
"Custom" => Err(E::invalid_type(serde::de::Unexpected::UnitVariant, &"a height in points")),
|
||||
other => Self::preset(other).ok_or_else(|| E::unknown_variant(other, HEIGHT_VARIANTS)),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<TrackHeight, A::Error> {
|
||||
use serde::de::Error as _;
|
||||
let Some(key) = map.next_key::<String>()? else { return Err(A::Error::invalid_length(0, &"one variant")) };
|
||||
let h = match key.as_str() {
|
||||
"Custom" => TrackHeight::Custom(map.next_value()?),
|
||||
// `{"Fit": null}` is the old size-less Fit too, as above.
|
||||
"Fit" => map.next_value::<Option<u16>>()?.map_or(TrackHeight::Medium, TrackHeight::Fit),
|
||||
other => {
|
||||
let h = Self::preset(other).ok_or_else(|| A::Error::unknown_variant(other, HEIGHT_VARIANTS))?;
|
||||
map.next_value::<()>()?;
|
||||
h
|
||||
}
|
||||
};
|
||||
if map.next_key::<serde::de::IgnoredAny>()?.is_some() {
|
||||
return Err(A::Error::invalid_length(2, &"one variant"));
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
}
|
||||
|
||||
impl TrackHeight {
|
||||
@@ -383,6 +402,36 @@ mod tests {
|
||||
assert_eq!(serde_json::from_str::<TrackHeight>("{\"Custom\":50}").unwrap(), TrackHeight::Custom(50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_saved_height_form_loads_and_nothing_else() {
|
||||
for h in TrackHeight::ALL.into_iter().chain([TrackHeight::Custom(50), TrackHeight::Fit(120)]) {
|
||||
assert_eq!(serde_json::from_str::<TrackHeight>(&serde_json::to_string(&h).unwrap()).unwrap(), h);
|
||||
assert_eq!(serde_json::from_value::<TrackHeight>(serde_json::to_value(h).unwrap()).unwrap(), h);
|
||||
}
|
||||
for h in TrackHeight::ALL {
|
||||
let null = format!("{{{}:null}}", serde_json::to_string(&h).unwrap());
|
||||
assert_eq!(serde_json::from_str::<TrackHeight>(&null).unwrap(), h, "{null}");
|
||||
}
|
||||
assert_eq!(serde_json::from_str::<TrackHeight>(r#"{"Fit":null}"#).unwrap(), TrackHeight::Medium);
|
||||
assert!(serde_json::from_str::<TrackHeight>(r#"{"Custom":null}"#).is_err());
|
||||
for bad in
|
||||
[r#""Custom""#, r#""Huge""#, "7", "[]", "null", "{}", r#"{"Fit":"x"}"#, r#"{"Fit":70000}"#, r#"{"Large":1}"#, r#"{"Fit":1,"Fit":2}"#]
|
||||
{
|
||||
assert!(serde_json::from_str::<TrackHeight>(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_height_is_refused_at_its_first_token() {
|
||||
// #892: the height was read through an untagged enum, which buffers the whole value
|
||||
// first; a session could hold a huge array there. It is refused where it starts.
|
||||
for (open, rest) in [("[", "0,".repeat(100_000) + "0]"), (r#"{"Fit":["#, "0,".repeat(100_000) + "0]}")] {
|
||||
let text = format!("{open}{rest}");
|
||||
let err = serde_json::from_str::<TrackHeight>(&text).unwrap_err();
|
||||
assert!(err.is_data() && err.line() == 1 && err.column() <= open.len() + 1, "{open}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_track_defaults() {
|
||||
let t = Track::new(TrackId(1), "Gtr", TrackKind::Audio, ChannelFormat::Stereo, TRACK_COLORS[0]);
|
||||
|
||||
+499
-20
@@ -1,11 +1,12 @@
|
||||
//! Grid and Nudge values: musical or absolute step sizes, grid lines and snapping.
|
||||
|
||||
use crate::{FrameRate, SampleRate, Samples, TICKS_PER_QUARTER, TempoMap, to_samples};
|
||||
use crate::{FrameRate, SampleRate, Samples, TICKS_PER_QUARTER, TempoMap, Timecode, to_samples};
|
||||
|
||||
/// Note values for Bars|Beats grids.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NoteValue {
|
||||
Bar,
|
||||
Whole,
|
||||
Half,
|
||||
Quarter,
|
||||
Eighth,
|
||||
@@ -15,8 +16,10 @@ pub enum NoteValue {
|
||||
}
|
||||
|
||||
impl NoteValue {
|
||||
pub const ALL: [NoteValue; 7] = [
|
||||
/// Every musical increment in menu order, from largest to smallest.
|
||||
pub const ALL: [NoteValue; 8] = [
|
||||
NoteValue::Bar,
|
||||
NoteValue::Whole,
|
||||
NoteValue::Half,
|
||||
NoteValue::Quarter,
|
||||
NoteValue::Eighth,
|
||||
@@ -24,9 +27,11 @@ impl NoteValue {
|
||||
NoteValue::ThirtySecond,
|
||||
NoteValue::SixtyFourth,
|
||||
];
|
||||
/// Returns the nominal tick length; bars are adjusted for the active meter when used.
|
||||
pub fn ticks(self) -> i64 {
|
||||
match self {
|
||||
NoteValue::Bar => TICKS_PER_QUARTER * 4,
|
||||
NoteValue::Whole => TICKS_PER_QUARTER * 4,
|
||||
NoteValue::Half => TICKS_PER_QUARTER * 2,
|
||||
NoteValue::Quarter => TICKS_PER_QUARTER,
|
||||
NoteValue::Eighth => TICKS_PER_QUARTER / 2,
|
||||
@@ -35,9 +40,11 @@ impl NoteValue {
|
||||
NoteValue::SixtyFourth => TICKS_PER_QUARTER / 16,
|
||||
}
|
||||
}
|
||||
/// Returns the menu label for this musical increment.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
NoteValue::Bar => "1 bar",
|
||||
NoteValue::Whole => "Whole note",
|
||||
NoteValue::Half => "1/2 note",
|
||||
NoteValue::Quarter => "1/4 note",
|
||||
NoteValue::Eighth => "1/8 note",
|
||||
@@ -48,26 +55,257 @@ impl NoteValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// The time scale used by a Grid or Nudge value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum GridScale {
|
||||
BarsBeats,
|
||||
MinSecs,
|
||||
Timecode,
|
||||
FeetFrames,
|
||||
Samples,
|
||||
ClipsMarkers,
|
||||
}
|
||||
|
||||
impl GridScale {
|
||||
/// Numeric time scales shared by Grid and Nudge.
|
||||
pub const TIME: [GridScale; 5] = [GridScale::BarsBeats, GridScale::MinSecs, GridScale::Timecode, GridScale::FeetFrames, GridScale::Samples];
|
||||
|
||||
/// Returns the user-facing scale label.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
GridScale::BarsBeats => "Bars|Beats",
|
||||
GridScale::MinSecs => "Min:Secs",
|
||||
GridScale::Timecode => "Timecode",
|
||||
GridScale::FeetFrames => "Feet+Frames",
|
||||
GridScale::Samples => "Samples",
|
||||
GridScale::ClipsMarkers => "Clips/Markers",
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the stable command and session identifier.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
GridScale::BarsBeats => "bars_beats",
|
||||
GridScale::MinSecs => "min_secs",
|
||||
GridScale::Timecode => "timecode",
|
||||
GridScale::FeetFrames => "feet_frames",
|
||||
GridScale::Samples => "samples",
|
||||
GridScale::ClipsMarkers => "clips_markers",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a stable identifier or user-facing label.
|
||||
pub fn from_id(id: &str) -> Option<GridScale> {
|
||||
Self::TIME.into_iter().chain([GridScale::ClipsMarkers]).find(|scale| scale.id() == id || scale.label().eq_ignore_ascii_case(id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Timecode Grid/Nudge increments, ordered independently of the session frame rate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TimecodeValue {
|
||||
Second,
|
||||
/// Five physical frames, independent of skipped drop-frame labels.
|
||||
FiveFrames,
|
||||
Frame,
|
||||
HalfFrame,
|
||||
QuarterFrame,
|
||||
SubFrame,
|
||||
}
|
||||
|
||||
impl TimecodeValue {
|
||||
/// Every Timecode increment in menu order, from largest to smallest.
|
||||
pub const ALL: [TimecodeValue; 6] = [
|
||||
TimecodeValue::Second,
|
||||
TimecodeValue::FiveFrames,
|
||||
TimecodeValue::Frame,
|
||||
TimecodeValue::HalfFrame,
|
||||
TimecodeValue::QuarterFrame,
|
||||
TimecodeValue::SubFrame,
|
||||
];
|
||||
|
||||
/// Returns the user-facing increment label.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
TimecodeValue::Second => "1 second",
|
||||
TimecodeValue::FiveFrames => "5 frames",
|
||||
TimecodeValue::Frame => "1 frame",
|
||||
TimecodeValue::HalfFrame => "1/2 frame",
|
||||
TimecodeValue::QuarterFrame => "1/4 frame",
|
||||
TimecodeValue::SubFrame => "1 subframe",
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the stable command and session identifier.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
TimecodeValue::Second => "second",
|
||||
TimecodeValue::FiveFrames => "5_frames",
|
||||
TimecodeValue::Frame => "frame",
|
||||
TimecodeValue::HalfFrame => "half_frame",
|
||||
TimecodeValue::QuarterFrame => "quarter_frame",
|
||||
TimecodeValue::SubFrame => "subframe",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a stable identifier or user-facing label.
|
||||
pub fn from_id(id: &str) -> Option<TimecodeValue> {
|
||||
Self::ALL.into_iter().find(|value| value.id() == id || value.label().eq_ignore_ascii_case(id))
|
||||
}
|
||||
|
||||
/// Returns the increment length in frames at the session rate.
|
||||
fn frames(self, rate: FrameRate) -> f64 {
|
||||
match self {
|
||||
TimecodeValue::Second => rate.nominal() as f64,
|
||||
TimecodeValue::FiveFrames => 5.0,
|
||||
TimecodeValue::Frame => 1.0,
|
||||
TimecodeValue::HalfFrame => 0.5,
|
||||
TimecodeValue::QuarterFrame => 0.25,
|
||||
TimecodeValue::SubFrame => 0.01,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feet+Frames Grid/Nudge increments in physical frames, independent of drop-frame label skips.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FeetFramesValue {
|
||||
Foot,
|
||||
Frame,
|
||||
QuarterFrame,
|
||||
SubFrame,
|
||||
}
|
||||
|
||||
impl FeetFramesValue {
|
||||
/// Every Feet+Frames increment in menu order, from largest to smallest.
|
||||
pub const ALL: [FeetFramesValue; 4] = [FeetFramesValue::Foot, FeetFramesValue::Frame, FeetFramesValue::QuarterFrame, FeetFramesValue::SubFrame];
|
||||
|
||||
/// Returns the user-facing increment label.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
FeetFramesValue::Foot => "1 foot",
|
||||
FeetFramesValue::Frame => "1 frame",
|
||||
FeetFramesValue::QuarterFrame => "1/4 frame",
|
||||
FeetFramesValue::SubFrame => "1 subframe",
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the stable command and session identifier.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
FeetFramesValue::Foot => "foot",
|
||||
FeetFramesValue::Frame => "frame",
|
||||
FeetFramesValue::QuarterFrame => "quarter_frame",
|
||||
FeetFramesValue::SubFrame => "subframe",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a stable identifier or user-facing label.
|
||||
pub fn from_id(id: &str) -> Option<FeetFramesValue> {
|
||||
Self::ALL.into_iter().find(|value| value.id() == id || value.label().eq_ignore_ascii_case(id))
|
||||
}
|
||||
|
||||
/// Returns the increment length in frames.
|
||||
fn frames(self) -> f64 {
|
||||
let (num, den) = self.frame_ratio();
|
||||
num as f64 / den as f64
|
||||
}
|
||||
|
||||
/// Exact numerator and denominator of the increment in physical frames.
|
||||
fn frame_ratio(self) -> (i128, i128) {
|
||||
match self {
|
||||
Self::Foot => (16, 1),
|
||||
Self::Frame => (1, 1),
|
||||
Self::QuarterFrame => (1, 4),
|
||||
Self::SubFrame => (1, 100),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the counter origin in frames before rounding once to the nearest sample.
|
||||
fn sample_line(self, index: i128, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
|
||||
let (num, den) = self.frame_ratio();
|
||||
let (rate_num, rate_den) = rate.rational();
|
||||
let frames = index * num - i128::from(origin) * den;
|
||||
let samples = frames * i128::from(sr.hz().max(1)) * i128::from(rate_den);
|
||||
let divisor = den * i128::from(rate_num);
|
||||
let magnitude = (samples.abs() + divisor / 2) / divisor;
|
||||
let rounded = if samples < 0 { -magnitude } else { magnitude };
|
||||
i64::try_from(rounded).unwrap_or(if rounded < 0 { i64::MIN } else { i64::MAX })
|
||||
}
|
||||
|
||||
/// Find a line index using exact frame arithmetic, allowing for whole-sample rounding.
|
||||
fn line_index(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> i128 {
|
||||
let (num, den) = self.frame_ratio();
|
||||
let (rate_num, rate_den) = rate.rational();
|
||||
let scale = i128::from(sr.hz().max(1)) * i128::from(rate_den);
|
||||
let frames = i128::from(position) * i128::from(rate_num) + i128::from(origin) * scale;
|
||||
let mut index = (frames * den).div_euclid(scale * num);
|
||||
if self.sample_line(index + 1, sr, rate, origin) <= position {
|
||||
index += 1;
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// The Feet+Frames line at or before a sample, relative to the counter's frame origin.
|
||||
pub fn line_at_or_before(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
|
||||
self.sample_line(self.line_index(position, sr, rate, origin), sr, rate, origin)
|
||||
}
|
||||
|
||||
/// The next distinct sample line; subframe increments may share a sample at low sample rates.
|
||||
fn next_line(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
|
||||
self.sample_line(self.line_index(position, sr, rate, origin) + 1, sr, rate, origin).max(position.saturating_add(1))
|
||||
}
|
||||
|
||||
/// Snap against frame-origin lines, choosing the earlier line when distances are equal.
|
||||
pub fn snap(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
|
||||
let lo = self.line_at_or_before(position, sr, rate, origin);
|
||||
let hi = self.next_line(lo, sr, rate, origin);
|
||||
if i128::from(position) - i128::from(lo) <= i128::from(hi) - i128::from(position) { lo } else { hi }
|
||||
}
|
||||
|
||||
/// Distinct Feet+Frames sample lines within `[start, end)`, capped at `max`.
|
||||
pub fn lines(self, start: Samples, end: Samples, sr: SampleRate, rate: FrameRate, origin: i64, max: usize) -> Vec<Samples> {
|
||||
let mut out = Vec::new();
|
||||
let mut line = self.line_at_or_before(start, sr, rate, origin);
|
||||
while line < end && out.len() < max {
|
||||
if line >= start {
|
||||
out.push(line);
|
||||
}
|
||||
let next = self.next_line(line, sr, rate, origin);
|
||||
if next <= line {
|
||||
break;
|
||||
}
|
||||
line = next;
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A grid or nudge step.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum GridValue {
|
||||
/// Musical: note value, optionally dotted or triplet.
|
||||
Note { value: NoteValue, dotted: bool, triplet: bool },
|
||||
/// Absolute seconds (Min:Secs grids: 0.001 … 10 s).
|
||||
/// Absolute seconds (Min:Secs grids: 0.001 … 1 s).
|
||||
Seconds(f64),
|
||||
/// Frames at the session timecode rate.
|
||||
/// Kept for sessions and commands written before named timecode increments were added.
|
||||
Frames(i64),
|
||||
/// A named Timecode increment, including fractional frames and one second.
|
||||
Timecode(TimecodeValue),
|
||||
/// A Feet+Frames increment (one foot is 16 frames).
|
||||
FeetFrames(FeetFramesValue),
|
||||
/// Raw samples.
|
||||
Samples(i64),
|
||||
}
|
||||
|
||||
impl Default for GridValue {
|
||||
/// Starts on a straight sixteenth-note Bars|Beats grid.
|
||||
fn default() -> Self {
|
||||
GridValue::Note { value: NoteValue::Sixteenth, dotted: false, triplet: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl GridValue {
|
||||
/// Returns the user-facing label for this increment.
|
||||
pub fn label(&self) -> String {
|
||||
match self {
|
||||
GridValue::Note { value, dotted, triplet } => {
|
||||
@@ -80,15 +318,47 @@ impl GridValue {
|
||||
}
|
||||
s
|
||||
}
|
||||
GridValue::Seconds(s) => format!("{s:.3} sec"),
|
||||
GridValue::Seconds(s) => {
|
||||
if *s >= 1.0 {
|
||||
format!("{s} second{}", if *s == 1.0 { "" } else { "s" })
|
||||
} else {
|
||||
format!("{} ms", (s * 1000.0).round() as i64)
|
||||
}
|
||||
}
|
||||
GridValue::Frames(f) => format!("{f} frame{}", if *f == 1 { "" } else { "s" }),
|
||||
GridValue::Samples(n) => format!("{n} samples"),
|
||||
GridValue::Timecode(value) => value.label().to_string(),
|
||||
GridValue::FeetFrames(value) => value.label().to_string(),
|
||||
GridValue::Samples(n) => format!("{n} sample{}", if *n == 1 { "" } else { "s" }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The next larger or smaller value of the same kind, or `self` at either end. Note values keep their
|
||||
/// dot or triplet; seconds, frames and samples step by tens.
|
||||
/// Returns the time scale to which this increment belongs.
|
||||
pub fn scale(self) -> GridScale {
|
||||
match self {
|
||||
GridValue::Note { .. } => GridScale::BarsBeats,
|
||||
GridValue::Seconds(_) => GridScale::MinSecs,
|
||||
GridValue::Frames(_) | GridValue::Timecode(_) => GridScale::Timecode,
|
||||
GridValue::FeetFrames(_) => GridScale::FeetFrames,
|
||||
GridValue::Samples(_) => GridScale::Samples,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the default increment for a newly selected time scale.
|
||||
pub fn for_scale(scale: GridScale) -> GridValue {
|
||||
match scale {
|
||||
GridScale::BarsBeats => GridValue::default(),
|
||||
GridScale::MinSecs => GridValue::Seconds(1.0),
|
||||
GridScale::Timecode => GridValue::Timecode(TimecodeValue::Frame),
|
||||
GridScale::FeetFrames => GridValue::FeetFrames(FeetFramesValue::Frame),
|
||||
GridScale::Samples => GridValue::Samples(100),
|
||||
GridScale::ClipsMarkers => GridValue::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The next larger or smaller menu value of the same kind, or `self` at either end. Note values keep
|
||||
/// their dot or triplet modifier.
|
||||
pub fn stepped(self, larger: bool) -> GridValue {
|
||||
/// Finds the next value in a numeric increment ladder without wrapping.
|
||||
fn next<T: PartialOrd + Copy>(ladder: &[T], v: T, larger: bool) -> Option<T> {
|
||||
if larger { ladder.iter().copied().find(|x| *x > v) } else { ladder.iter().rev().copied().find(|x| *x < v) }
|
||||
}
|
||||
@@ -98,9 +368,11 @@ impl GridValue {
|
||||
let j = if larger { i.checked_sub(1) } else { i.checked_add(1) };
|
||||
j.and_then(|j| NoteValue::ALL.get(j)).map_or(self, |&value| GridValue::Note { value, dotted, triplet })
|
||||
}
|
||||
GridValue::Seconds(s) => next(&[0.001, 0.01, 0.1, 1.0, 10.0], s, larger).map_or(self, GridValue::Seconds),
|
||||
GridValue::Seconds(s) => next(&[0.001, 0.01, 0.1, 0.5, 1.0], s, larger).map_or(self, GridValue::Seconds),
|
||||
GridValue::Frames(f) => next(&[1, 10, 100], f, larger).map_or(self, GridValue::Frames),
|
||||
GridValue::Samples(n) => next(&[1, 10, 100, 1_000, 10_000, 100_000], n, larger).map_or(self, GridValue::Samples),
|
||||
GridValue::Timecode(value) => step_enum(&TimecodeValue::ALL, value, larger).map_or(self, GridValue::Timecode),
|
||||
GridValue::FeetFrames(value) => step_enum(&FeetFramesValue::ALL, value, larger).map_or(self, GridValue::FeetFrames),
|
||||
GridValue::Samples(n) => next(&[1, 2, 10, 100, 1_000, 10_000], n, larger).map_or(self, GridValue::Samples),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,12 +398,17 @@ impl GridValue {
|
||||
}
|
||||
GridValue::Seconds(s) => sr.samples(s.clamp(0.000_01, 3600.0)).max(1),
|
||||
GridValue::Frames(f) => to_samples(rate.samples_per_frame(sr) * f.clamp(1, 1_000_000) as f64).max(1),
|
||||
GridValue::Timecode(value) => to_samples(rate.samples_per_frame(sr) * value.frames(rate)).max(1),
|
||||
GridValue::FeetFrames(value) => to_samples(rate.samples_per_frame(sr) * value.frames()).max(1),
|
||||
GridValue::Samples(n) => n.max(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Nearest grid line to `pos`.
|
||||
pub fn snap(&self, pos: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
|
||||
if let Self::FeetFrames(value) = *self {
|
||||
return value.snap(pos, sr, rate, 0);
|
||||
}
|
||||
let lo = self.line_at_or_before(pos, sr, map, rate);
|
||||
let hi = self.next_line(lo, sr, map, rate);
|
||||
if (pos - lo) <= (hi - pos) { lo } else { hi }
|
||||
@@ -140,6 +417,7 @@ impl GridValue {
|
||||
/// The grid line at or before `pos`.
|
||||
pub fn line_at_or_before(&self, pos: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
|
||||
match *self {
|
||||
Self::FeetFrames(value) => value.line_at_or_before(pos, sr, rate, 0),
|
||||
GridValue::Note { value, dotted, triplet } => {
|
||||
// Float ticks can land a hair either side of a line's own tick.
|
||||
let mut t = map.samples_to_ticks_f(pos, sr).floor() as i64;
|
||||
@@ -148,12 +426,14 @@ impl GridValue {
|
||||
} else if map.tick_to_samples(t.saturating_add(1), sr) <= pos {
|
||||
t = t.saturating_add(1);
|
||||
}
|
||||
// Grid lines restart at each bar line so odd meters stay aligned.
|
||||
// Sub-bar values restart at each bar so odd meters stay aligned. A whole note is
|
||||
// always four quarter notes and therefore keeps a continuous tick origin.
|
||||
let bb = map.bar_beat_at_tick(t);
|
||||
let bar_tick = map.bar_start_tick(bb.bar);
|
||||
let step = Self::note_ticks(value, dotted, triplet, map, bar_tick);
|
||||
let k = (t - bar_tick).div_euclid(step);
|
||||
map.tick_to_samples(bar_tick + k * step, sr)
|
||||
let origin = if value == NoteValue::Whole { 0 } else { bar_tick };
|
||||
let step = Self::note_ticks(value, dotted, triplet, map, origin);
|
||||
let k = (t - origin).div_euclid(step);
|
||||
map.tick_to_samples(origin + k * step, sr)
|
||||
}
|
||||
_ => self.abs_line(self.abs_index_at_or_before(pos, sr, rate), sr, rate),
|
||||
}
|
||||
@@ -162,21 +442,60 @@ impl GridValue {
|
||||
/// Position of absolute grid line `k` (Seconds, Frames, Samples), at an exact multiple of the step
|
||||
/// rounded once, so rounding never accumulates from line to line.
|
||||
fn abs_line(&self, k: i64, sr: SampleRate, rate: FrameRate) -> Samples {
|
||||
if let Self::FeetFrames(value) = *self {
|
||||
return value.sample_line(i128::from(k), sr, rate, 0);
|
||||
}
|
||||
if matches!(self, GridValue::Timecode(TimecodeValue::Second)) && rate.is_drop() {
|
||||
return rate.samples_at_frame(Self::drop_second_frame(k, rate), sr);
|
||||
}
|
||||
if let Some(frames) = self.frame_step(rate) {
|
||||
let whole = frames.round();
|
||||
if frames == whole {
|
||||
return rate.samples_at_frame(k.saturating_mul(whole as i64), sr);
|
||||
}
|
||||
let step = (rate.samples_per_frame(sr) * frames).max(1.0);
|
||||
return to_samples(k as f64 * step);
|
||||
}
|
||||
match *self {
|
||||
GridValue::Seconds(s) => to_samples(k as f64 * Self::seconds_step(s, sr)),
|
||||
GridValue::Frames(f) => rate.samples_at_frame(k.saturating_mul(f.clamp(1, 1_000_000)), sr),
|
||||
GridValue::Samples(n) => k.saturating_mul(n.max(1)),
|
||||
GridValue::Note { .. } => 0,
|
||||
GridValue::Frames(_) | GridValue::Timecode(_) | GridValue::FeetFrames(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the absolute grid line at or before `pos`.
|
||||
fn abs_index_at_or_before(&self, pos: Samples, sr: SampleRate, rate: FrameRate) -> i64 {
|
||||
let mut k = match *self {
|
||||
GridValue::Seconds(s) => (pos as f64 / Self::seconds_step(s, sr)).floor() as i64,
|
||||
GridValue::Frames(f) => rate.frames_at(pos, sr).div_euclid(f.clamp(1, 1_000_000)),
|
||||
GridValue::Samples(n) => return pos.div_euclid(n.max(1)),
|
||||
GridValue::Note { .. } => return 0,
|
||||
if matches!(self, GridValue::Timecode(TimecodeValue::Second)) && rate.is_drop() {
|
||||
let tc = Timecode::from_frames(rate.frames_at(pos, sr), rate);
|
||||
let magnitude = tc.hours.saturating_mul(3600).saturating_add(tc.minutes.saturating_mul(60)).saturating_add(tc.seconds);
|
||||
let mut k = if tc.negative { magnitude.saturating_neg() } else { magnitude };
|
||||
while self.abs_line(k, sr, rate) > pos {
|
||||
let previous = k.saturating_sub(1);
|
||||
if previous == k {
|
||||
break;
|
||||
}
|
||||
k = previous;
|
||||
}
|
||||
while self.abs_line(k.saturating_add(1), sr, rate) <= pos {
|
||||
let next = k.saturating_add(1);
|
||||
if next == k {
|
||||
break;
|
||||
}
|
||||
k = next;
|
||||
}
|
||||
return k;
|
||||
}
|
||||
let mut k = if let Some(frames) = self.frame_step(rate) {
|
||||
let step = (rate.samples_per_frame(sr) * frames).max(1.0);
|
||||
(pos as f64 / step).floor() as i64
|
||||
} else {
|
||||
match *self {
|
||||
GridValue::Seconds(s) => (pos as f64 / Self::seconds_step(s, sr)).floor() as i64,
|
||||
GridValue::Samples(n) => return pos.div_euclid(n.max(1)),
|
||||
GridValue::Note { .. } => return 0,
|
||||
GridValue::Frames(_) | GridValue::Timecode(_) | GridValue::FeetFrames(_) => return 0,
|
||||
}
|
||||
};
|
||||
// Lines are rounded to whole samples, so the floored index can be one off either way.
|
||||
if self.abs_line(k, sr, rate) > pos {
|
||||
@@ -192,8 +511,36 @@ impl GridValue {
|
||||
(s.clamp(0.000_01, 3600.0) * sr.as_f64()).max(1.0)
|
||||
}
|
||||
|
||||
/// Maps a signed whole-second timecode label to its physical frame at a drop-frame rate.
|
||||
fn drop_second_frame(index: i64, rate: FrameRate) -> i64 {
|
||||
let seconds = index.unsigned_abs();
|
||||
let total_minutes = seconds / 60;
|
||||
let frames = if seconds.is_multiple_of(60) && !total_minutes.is_multiple_of(10) { if rate.nominal() >= 60 { 4 } else { 2 } } else { 0 };
|
||||
Timecode {
|
||||
negative: index < 0,
|
||||
hours: i64::try_from(seconds / 3600).unwrap_or(i64::MAX),
|
||||
minutes: i64::try_from((seconds / 60) % 60).unwrap_or(0),
|
||||
seconds: i64::try_from(seconds % 60).unwrap_or(0),
|
||||
frames,
|
||||
}
|
||||
.to_frames(rate)
|
||||
}
|
||||
|
||||
/// A frame-based increment as a possibly fractional number of frames.
|
||||
fn frame_step(&self, rate: FrameRate) -> Option<f64> {
|
||||
match *self {
|
||||
GridValue::Frames(frames) => Some(frames.clamp(1, 1_000_000) as f64),
|
||||
GridValue::Timecode(value) => Some(value.frames(rate)),
|
||||
GridValue::FeetFrames(value) => Some(value.frames()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first grid line strictly after `line`.
|
||||
pub fn next_line(&self, line: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
|
||||
if let Self::FeetFrames(value) = *self {
|
||||
return value.next_line(line, sr, rate, 0);
|
||||
}
|
||||
if !matches!(self, GridValue::Note { .. }) {
|
||||
let next = self.abs_line(self.abs_index_at_or_before(line, sr, rate).saturating_add(1), sr, rate);
|
||||
return if next > line { next } else { line.saturating_add(1) };
|
||||
@@ -205,6 +552,9 @@ impl GridValue {
|
||||
|
||||
/// All grid lines within `[start, end)`, capped at `max` lines.
|
||||
pub fn lines(&self, start: Samples, end: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate, max: usize) -> Vec<Samples> {
|
||||
if let Self::FeetFrames(value) = *self {
|
||||
return value.lines(start, end, sr, rate, 0, max);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut p = self.line_at_or_before(start, sr, map, rate);
|
||||
while p < end && out.len() < max {
|
||||
@@ -221,10 +571,43 @@ impl GridValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves one position through an ordered increment menu without wrapping.
|
||||
fn step_enum<T: Copy + PartialEq>(values: &[T], value: T, larger: bool) -> Option<T> {
|
||||
let index = values.iter().position(|candidate| *candidate == value)?;
|
||||
let next = if larger { index.checked_sub(1) } else { index.checked_add(1) }?;
|
||||
values.get(next).copied()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Frame origins are subtracted before rounding whole frames, quarter frames and subframes.
|
||||
#[test]
|
||||
fn feet_frames_origins_round_only_after_applying_the_frame_offset() {
|
||||
let (sr, rate) = (SampleRate::HZ_48000, FrameRate::Fps29_97);
|
||||
for at in [49_650, 100_901, 177_778] {
|
||||
assert_eq!(FeetFramesValue::Foot.line_at_or_before(at, sr, rate, 1), at);
|
||||
assert_eq!(FeetFramesValue::Foot.snap(at - 1, sr, rate, 1), at);
|
||||
}
|
||||
assert_eq!(FeetFramesValue::QuarterFrame.snap(50_049, sr, rate, 1), 50_050);
|
||||
assert_eq!(FeetFramesValue::SubFrame.lines(49_665, 49_667, sr, rate, 1, 4), [49_666]);
|
||||
}
|
||||
|
||||
/// Dense subframes retain distinct sample lines and remain bounded with extreme signed origins.
|
||||
#[test]
|
||||
fn feet_frames_subframes_handle_dense_steps_and_extreme_origins() {
|
||||
let sr = SampleRate::new(8_000).unwrap();
|
||||
let rate = FrameRate::Fps120;
|
||||
for origin in [i64::MIN, -1, 0, 1, i64::MAX] {
|
||||
assert_eq!(FeetFramesValue::SubFrame.lines(-3, 4, sr, rate, origin, 20), [-3, -2, -1, 0, 1, 2, 3]);
|
||||
for at in [i64::MIN, -1, 0, 1, i64::MAX] {
|
||||
assert_eq!(FeetFramesValue::SubFrame.line_at_or_before(at, sr, rate, origin), at);
|
||||
assert_eq!(FeetFramesValue::SubFrame.snap(at, sr, rate, origin), at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_lines_are_their_own_line_at_odd_tempos() {
|
||||
let (g, sr, rate) = (GridValue::default(), SampleRate::HZ_48000, FrameRate::Fps30);
|
||||
@@ -238,6 +621,29 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Musical boundaries stay exact across a tempo change while absolute scales remain
|
||||
/// independent of the tempo map.
|
||||
#[test]
|
||||
fn grids_stay_aligned_across_a_tempo_change() {
|
||||
let (sr, rate) = (SampleRate::HZ_48000, FrameRate::Fps29_97Drop);
|
||||
let mut map = TempoMap::default();
|
||||
map.set_tempo(TICKS_PER_QUARTER * 4, 90.0).unwrap();
|
||||
let musical = GridValue::Note { value: NoteValue::Quarter, dotted: false, triplet: false };
|
||||
for tick in [0, TICKS_PER_QUARTER * 3, TICKS_PER_QUARTER * 4, TICKS_PER_QUARTER * 5] {
|
||||
let line = map.tick_to_samples(tick, sr);
|
||||
assert_eq!(musical.line_at_or_before(line, sr, &map, rate), line);
|
||||
}
|
||||
for absolute in [
|
||||
GridValue::Seconds(0.5),
|
||||
GridValue::Timecode(TimecodeValue::Second),
|
||||
GridValue::FeetFrames(FeetFramesValue::Foot),
|
||||
GridValue::Samples(1_000),
|
||||
] {
|
||||
let line = absolute.next_line(absolute.line_at_or_before(100_000, sr, &map, rate), sr, &map, rate);
|
||||
assert_eq!(absolute.line_at_or_before(line, sr, &map, rate), line, "{absolute:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteenth_grid_at_120() {
|
||||
let g = GridValue::default();
|
||||
@@ -248,14 +654,33 @@ mod tests {
|
||||
assert_eq!(g.lines(0, 24_000, sr, &map, rate, 100), vec![0, 6000, 12000, 18000]);
|
||||
}
|
||||
|
||||
/// Absolute increments report their expected sample lengths at a fixed rate.
|
||||
#[test]
|
||||
fn absolute_grids() {
|
||||
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps25);
|
||||
assert_eq!(GridValue::Seconds(1.0).snap(70_000, sr, &map, rate), 48_000);
|
||||
assert_eq!(GridValue::Frames(1).step_samples(0, sr, &map, rate), 1920);
|
||||
assert_eq!(GridValue::Timecode(TimecodeValue::Second).step_samples(0, sr, &map, rate), 48_000);
|
||||
assert_eq!(GridValue::Timecode(TimecodeValue::FiveFrames).step_samples(0, sr, &map, rate), 9_600);
|
||||
assert_eq!(GridValue::Timecode(TimecodeValue::HalfFrame).step_samples(0, sr, &map, rate), 960);
|
||||
assert_eq!(GridValue::Timecode(TimecodeValue::QuarterFrame).step_samples(0, sr, &map, rate), 480);
|
||||
assert_eq!(GridValue::Timecode(TimecodeValue::SubFrame).step_samples(0, sr, &map, rate), 19);
|
||||
assert_eq!(GridValue::FeetFrames(FeetFramesValue::Foot).step_samples(0, sr, &map, rate), 30_720);
|
||||
assert_eq!(GridValue::Samples(0).step_samples(0, sr, &map, rate), 1);
|
||||
}
|
||||
|
||||
/// Bar length follows the meter while a whole note always spans four quarter notes.
|
||||
#[test]
|
||||
fn a_bar_and_a_whole_note_differ_in_three_four() {
|
||||
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::new(120.0, 3, 4).unwrap(), FrameRate::Fps25);
|
||||
let note = |value| GridValue::Note { value, dotted: false, triplet: false };
|
||||
assert_eq!(note(NoteValue::Bar).step_samples(0, sr, &map, rate), 72_000);
|
||||
assert_eq!(note(NoteValue::Whole).step_samples(0, sr, &map, rate), 96_000);
|
||||
assert_eq!(note(NoteValue::Bar).line_at_or_before(96_000, sr, &map, rate), 72_000);
|
||||
assert_eq!(note(NoteValue::Whole).line_at_or_before(96_000, sr, &map, rate), 96_000);
|
||||
assert_eq!(note(NoteValue::Half).lines(0, 150_000, sr, &map, rate, 10), [0, 48_000, 72_000, 120_000, 144_000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seconds_grid_lines_land_on_whole_seconds() {
|
||||
let (sr, map, rate) = (SampleRate::HZ_44100, TempoMap::default(), FrameRate::Fps30);
|
||||
@@ -268,6 +693,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Legacy frame grids stay aligned to exact frame starts at fractional rates.
|
||||
#[test]
|
||||
fn frame_grid_lines_land_on_frame_starts() {
|
||||
let sr = SampleRate::HZ_48000;
|
||||
@@ -291,6 +717,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Named whole- and sub-frame grids retain the exact-multiple calculation used by legacy frame grids.
|
||||
#[test]
|
||||
fn named_frame_grids_land_on_exact_subdivisions() {
|
||||
let sr = SampleRate::HZ_48000;
|
||||
let map = TempoMap::default();
|
||||
let grids = TimecodeValue::ALL.into_iter().map(GridValue::Timecode).chain(FeetFramesValue::ALL.into_iter().map(GridValue::FeetFrames));
|
||||
for rate in [FrameRate::Fps29_97, FrameRate::Fps23_976] {
|
||||
for grid in grids.clone() {
|
||||
for index in 0..200 {
|
||||
let line = grid.abs_line(index, sr, rate);
|
||||
assert_eq!(grid.line_at_or_before(line, sr, &map, rate), line, "{grid:?} {rate:?} line {index}");
|
||||
assert_eq!(grid.next_line(line, sr, &map, rate), grid.abs_line(index + 1, sr, rate), "{grid:?} {rate:?} line {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop-frame second grids follow labelled second boundaries in both timeline directions.
|
||||
#[test]
|
||||
fn drop_frame_second_grids_follow_timecode_labels() {
|
||||
let sr = SampleRate::HZ_48000;
|
||||
let map = TempoMap::default();
|
||||
let grid = GridValue::Timecode(TimecodeValue::Second);
|
||||
for rate in [FrameRate::Fps29_97Drop, FrameRate::Fps59_94Drop] {
|
||||
for seconds in [0, 59, 60, 61, 600, 601, 3600] {
|
||||
let frame = GridValue::drop_second_frame(seconds, rate);
|
||||
let line = rate.samples_at_frame(frame, sr);
|
||||
assert_eq!(grid.line_at_or_before(line, sr, &map, rate), line, "{rate:?} second {seconds}");
|
||||
assert_eq!(grid.line_at_or_before(-line, sr, &map, rate), -line, "{rate:?} second -{seconds}");
|
||||
for offset in -2..=rate.nominal() + 2 {
|
||||
let position = rate.samples_at_frame(frame.saturating_add(offset), sr);
|
||||
let before = grid.line_at_or_before(position, sr, &map, rate);
|
||||
assert!(before <= position, "{rate:?} second {seconds}, frame offset {offset}");
|
||||
assert!(grid.next_line(before, sr, &map, rate) > position, "{rate:?} second {seconds}, frame offset {offset}");
|
||||
}
|
||||
}
|
||||
let labelled = Timecode { negative: false, hours: 0, minutes: 1, seconds: 1, frames: 0 }.to_samples(rate, sr);
|
||||
assert_eq!(grid.snap(labelled, sr, &map, rate), labelled);
|
||||
}
|
||||
|
||||
for (rate, minute_frame) in [(FrameRate::Fps29_97Drop, 1800), (FrameRate::Fps59_94Drop, 3600)] {
|
||||
let boundary = rate.samples_at_frame(minute_frame, sr);
|
||||
assert_eq!(grid.line_at_or_before(boundary, sr, &map, rate), boundary, "{rate:?} positive minute boundary");
|
||||
assert_eq!(grid.snap(boundary, sr, &map, rate), boundary, "{rate:?} positive minute snap");
|
||||
assert_eq!(grid.line_at_or_before(-boundary, sr, &map, rate), -boundary, "{rate:?} negative minute boundary");
|
||||
assert_eq!(grid.snap(-boundary, sr, &map, rate), -boundary, "{rate:?} negative minute snap");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_are_capped() {
|
||||
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps25);
|
||||
@@ -306,6 +781,7 @@ mod tests {
|
||||
assert_eq!(d.step_samples(0, sr, &map, rate), 36_000);
|
||||
}
|
||||
|
||||
/// Stepping follows each menu ladder and stops at its endpoints.
|
||||
#[test]
|
||||
fn values_step_to_the_next_larger_or_smaller() {
|
||||
let note = |value, triplet| GridValue::Note { value, dotted: false, triplet };
|
||||
@@ -315,9 +791,12 @@ mod tests {
|
||||
assert_eq!(note(NoteValue::SixtyFourth, false).stepped(false), note(NoteValue::SixtyFourth, false));
|
||||
assert_eq!(GridValue::Seconds(0.01).stepped(true), GridValue::Seconds(0.1));
|
||||
assert_eq!(GridValue::Seconds(0.5).stepped(false), GridValue::Seconds(0.1));
|
||||
assert_eq!(GridValue::Seconds(10.0).stepped(true), GridValue::Seconds(10.0));
|
||||
assert_eq!(GridValue::Seconds(1.0).stepped(true), GridValue::Seconds(1.0));
|
||||
assert_eq!(GridValue::Frames(1).stepped(true), GridValue::Frames(10));
|
||||
assert_eq!(GridValue::Timecode(TimecodeValue::Frame).stepped(false), GridValue::Timecode(TimecodeValue::HalfFrame));
|
||||
assert_eq!(GridValue::FeetFrames(FeetFramesValue::Frame).stepped(true), GridValue::FeetFrames(FeetFramesValue::Foot));
|
||||
assert_eq!(GridValue::Samples(100).stepped(false), GridValue::Samples(10));
|
||||
assert_eq!(GridValue::Samples(1).stepped(true), GridValue::Samples(2));
|
||||
assert_eq!(GridValue::Samples(1).stepped(false), GridValue::Samples(1));
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ mod tempo;
|
||||
mod timecode;
|
||||
|
||||
pub use format::{TimeFormat, format_length, format_position, parse_position};
|
||||
pub use grid::{GridValue, NoteValue};
|
||||
pub use grid::{FeetFramesValue, GridScale, GridValue, NoteValue, TimecodeValue};
|
||||
pub use tempo::{BarBeat, MeterEvent, TICKS_PER_QUARTER, TempoEvent, TempoMap};
|
||||
pub use timecode::{FrameRate, Timecode};
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ soundcraft-video.workspace = true
|
||||
# 0.37 makes the bundled faces opt-in; the app's own font loader starts from
|
||||
# `FontDefinitions::default()`, and kittest never supplies fonts to this root.
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_extras = { workspace = true }
|
||||
web-time.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::state::MainWindow;
|
||||
use super::{
|
||||
ControlRequest, Engine, Gesture, HashMap, MeterDisplay, OutputTrouble, Player, Range, Receiver, Samples, SoundApp, TrackId, TransportRequest,
|
||||
Trouble, UiState, Value, VecDeque, bounce, dialogs, edit_window, extra_windows, fonts, import, json, menus, midi_editor, mix_window, ops_windows,
|
||||
palette, panels, recovery, sampler_window, score_editor, shortcuts, theme, updates_ui, video_track, video_window, windows,
|
||||
palette, panels, preferences, recovery, sampler_window, score_editor, shortcuts, theme, updates_ui, video_track, video_window, windows,
|
||||
};
|
||||
|
||||
mod audio;
|
||||
@@ -63,6 +63,7 @@ impl SoundApp {
|
||||
ops: ops_windows::OpsState::default(),
|
||||
extra: extra_windows::ExtraState::default(),
|
||||
palette: palette::PaletteState::default(),
|
||||
preferences: preferences::PreferencesState::default(),
|
||||
focus_mix: false,
|
||||
edit_scroll_into_view: None,
|
||||
mix_scroll_into_view: None,
|
||||
@@ -137,6 +138,8 @@ impl SoundApp {
|
||||
/// Each host iteration starts with `raw_input_hook`; its editor-poll admission prevents an
|
||||
/// empty queue on a discarded pass from ending a still-active plugin gesture.
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
self.ui.undo_levels = self.ui.undo_levels.clamp(1, 64);
|
||||
self.engine.set_history_limit(self.ui.undo_levels);
|
||||
// Fonts set now take effect next frame, so draw only from the frame after.
|
||||
if !self.fonts_ready {
|
||||
if self.fonts_installed {
|
||||
@@ -333,6 +336,7 @@ impl SoundApp {
|
||||
}
|
||||
panels::floating(self, &ctx);
|
||||
windows::show(self, &ctx);
|
||||
preferences::show(self, &ctx);
|
||||
video_window::show(self, &ctx);
|
||||
ops_windows::show(self, &ctx);
|
||||
extra_windows::show(self, &ctx);
|
||||
|
||||
+322
-53
@@ -262,71 +262,213 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
|
||||
let list = sorted(CONTRIBUTORS, v.names, v.key, v.ascending);
|
||||
ui.label(RichText::new(format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().weak());
|
||||
ui.separator();
|
||||
egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| {
|
||||
if list.is_empty() {
|
||||
ui.label("No contributor data was built into this copy.");
|
||||
} else if v.table {
|
||||
table(ui, &list, &mut v);
|
||||
} else {
|
||||
if list.is_empty() {
|
||||
ui.label("No contributor data was built into this copy.");
|
||||
} else if v.table {
|
||||
// The table scrolls vertically itself, under a fixed header; it only scrolls sideways
|
||||
// once its columns are dragged wider than the dialog.
|
||||
egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| table(ui, &list, &mut v));
|
||||
} else {
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
contributors_grab_bag(ui, &list, v.names);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, v));
|
||||
}
|
||||
|
||||
fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
|
||||
egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| {
|
||||
for k in SortKey::ALL {
|
||||
let arrow = if v.key == k { if v.ascending { " ⏶" } else { " ⏷" } } else { "" };
|
||||
if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() {
|
||||
if v.key == k {
|
||||
v.ascending = !v.ascending;
|
||||
} else {
|
||||
v.key = k;
|
||||
v.ascending = k.default_ascending();
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.end_row();
|
||||
for c in list {
|
||||
ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary());
|
||||
ui.label(group(c.prs));
|
||||
ui.label(group(c.commits));
|
||||
ui.label(group(c.lines_added));
|
||||
ui.label(group(c.lines_deleted));
|
||||
ui.label(signed(c.lines_delta()));
|
||||
ui.label(group(c.binary_added));
|
||||
ui.label(group(c.binary_deleted));
|
||||
ui.label(day(c.first_commit));
|
||||
ui.label(day(c.last_commit));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
/// How the contributor table's spare width is shared out: all of it to Name.
|
||||
const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
|
||||
|
||||
/// How the model table's spare width is shared out: to Company and Model, the text columns.
|
||||
const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0];
|
||||
|
||||
/// The narrowest a column can be dragged.
|
||||
const MIN_COLUMN: f32 = 28.0;
|
||||
|
||||
/// The width a column needs for its header and its widest cell.
|
||||
fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator<Item = String>) -> f32 {
|
||||
let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x;
|
||||
let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max);
|
||||
widest + 2.0 * ui.spacing().button_padding.x
|
||||
}
|
||||
|
||||
/// About › Models: AI models credited in Co-Authored-By trailers.
|
||||
/// Opening column widths: each column's natural width, with the spare room shared out by `grow`,
|
||||
/// so the columns fill `room` exactly. When there is too little room, only the growing columns
|
||||
/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that.
|
||||
fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec<f32> {
|
||||
let spare = room - natural.iter().sum::<f32>();
|
||||
let weight = grow.iter().sum::<f32>();
|
||||
let slack = |w: f32| (w - MIN_COLUMN).max(0.0);
|
||||
let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum();
|
||||
natural
|
||||
.iter()
|
||||
.zip(grow)
|
||||
.map(|(w, g)| {
|
||||
if *g > 0.0 && spare >= 0.0 {
|
||||
w + spare * g / weight
|
||||
} else if *g > 0.0 && flexible > 0.0 {
|
||||
w - (-spare).min(flexible) * slack(*w) / flexible
|
||||
} else {
|
||||
*w
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls
|
||||
/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge:
|
||||
/// only a table dragged wider than the window scrolls sideways. Text too long for its column is
|
||||
/// clipped. When a column's natural width or the window changes, the columns go back to a new fit,
|
||||
/// dropping any dragged widths.
|
||||
fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> {
|
||||
// Every cell is followed by the item gap, and the vertical scrollbar keeps its margins.
|
||||
let s = ui.spacing();
|
||||
let gaps = s.item_spacing.x * natural.len() as f32;
|
||||
let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin;
|
||||
let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0));
|
||||
// The table keeps its own column widths, so a change in what they were fitted to has to clear
|
||||
// them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available
|
||||
// width, so this compares the natural widths and the clip rect, which scrolling never moves.
|
||||
let fit = egui::Id::unique(("credits_fit", id));
|
||||
let measured = (natural.to_vec(), ui.clip_rect().width());
|
||||
let refit = ui.data_mut(|d| d.get_temp::<(Vec<f32>, f32)>(fit)).as_ref() != Some(&measured);
|
||||
ui.data_mut(|d| d.insert_temp(fit, measured));
|
||||
let mut t =
|
||||
egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY);
|
||||
if refit {
|
||||
t.reset();
|
||||
}
|
||||
for w in widths {
|
||||
t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true));
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred.
|
||||
fn aligned<R>(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) };
|
||||
ui.with_layout(layout, add).inner
|
||||
}
|
||||
|
||||
fn row_height(ui: &egui::Ui) -> f32 {
|
||||
ui.text_style_height(&egui::TextStyle::Body) + 6.0
|
||||
}
|
||||
|
||||
/// One contributor's table cells after the name, in `SortKey::ALL` order.
|
||||
fn cells(c: &Contributor) -> [String; 9] {
|
||||
[
|
||||
group(c.prs),
|
||||
group(c.commits),
|
||||
group(c.lines_added),
|
||||
group(c.lines_deleted),
|
||||
signed(c.lines_delta()),
|
||||
group(c.binary_added),
|
||||
group(c.binary_deleted),
|
||||
day(c.first_commit).to_string(),
|
||||
day(c.last_commit).to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// A contributor-table header. The sorted column is highlighted; its direction shows on the
|
||||
/// toolbar's sort-order button, so no arrow widens the column.
|
||||
fn header_text(k: SortKey) -> RichText {
|
||||
RichText::new(k.label().1).strong()
|
||||
}
|
||||
|
||||
fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
|
||||
let h = row_height(ui);
|
||||
let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect();
|
||||
let widths: Vec<f32> = SortKey::ALL
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &k)| match i.checked_sub(1) {
|
||||
None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))),
|
||||
Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())),
|
||||
})
|
||||
.collect();
|
||||
fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW)
|
||||
.header(h + 4.0, |mut header| {
|
||||
for k in SortKey::ALL {
|
||||
header.col(|ui| {
|
||||
let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))).on_hover_text(k.label().0);
|
||||
|
||||
if r.clicked() {
|
||||
if v.key == k {
|
||||
v.ascending = !v.ascending;
|
||||
} else {
|
||||
v.key = k;
|
||||
v.ascending = k.default_ascending();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
.body(|mut body| {
|
||||
for (c, cells) in list.iter().zip(rows) {
|
||||
body.row(h, |mut row| {
|
||||
row.col(|ui| {
|
||||
aligned(ui, false, |ui| ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)))
|
||||
.on_hover_text(c.summary());
|
||||
});
|
||||
for text in cells {
|
||||
row.col(|ui| {
|
||||
aligned(ui, true, |ui| ui.label(text));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// About ▸ Models: AI models credited in Co-Authored-By trailers.
|
||||
pub fn models_ui(ui: &mut egui::Ui) {
|
||||
if MODELS.is_empty() {
|
||||
ui.label("No model credits were built into this copy.");
|
||||
return;
|
||||
}
|
||||
let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1);
|
||||
egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| {
|
||||
egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| {
|
||||
for h in ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"] {
|
||||
ui.label(RichText::new(h).strong());
|
||||
}
|
||||
ui.end_row();
|
||||
for m in MODELS {
|
||||
ui.label(m.company);
|
||||
ui.label(m.model);
|
||||
ui.label(m.version);
|
||||
ui.label(group(m.commits));
|
||||
ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64));
|
||||
ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
let h = row_height(ui);
|
||||
let titles = ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"];
|
||||
// Company, Model and Version read as text; the counts line up on the right.
|
||||
let right = [false, false, false, true, true, true];
|
||||
let rows: Vec<[String; 6]> = MODELS
|
||||
.iter()
|
||||
.map(|m| {
|
||||
[
|
||||
m.company.to_string(),
|
||||
m.model.to_string(),
|
||||
m.version.to_string(),
|
||||
group(m.commits),
|
||||
format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64),
|
||||
format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let widths: Vec<f32> = titles
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, title)| natural(ui, RichText::new(*title).strong(), rows.iter().filter_map(|r| r.get(i).cloned())))
|
||||
.collect();
|
||||
egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| {
|
||||
fitted_table(ui, "credits_models", &widths, &MODEL_GROW)
|
||||
.header(h + 4.0, |mut header| {
|
||||
for (title, r) in titles.into_iter().zip(right) {
|
||||
header.col(|ui| {
|
||||
aligned(ui, r, |ui| ui.label(RichText::new(title).strong()));
|
||||
});
|
||||
}
|
||||
})
|
||||
.body(|mut body| {
|
||||
for cells in rows {
|
||||
body.row(h, |mut row| {
|
||||
for (text, r) in cells.into_iter().zip(right) {
|
||||
row.col(|ui| {
|
||||
aligned(ui, r, |ui| ui.label(text));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -406,4 +548,131 @@ mod tests {
|
||||
assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07");
|
||||
assert_eq!(day(""), "—");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() {
|
||||
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]);
|
||||
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]);
|
||||
let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0);
|
||||
assert!((w.iter().sum::<f32>() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_little_room_shrinks_only_growing_columns() {
|
||||
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]);
|
||||
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]);
|
||||
assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() {
|
||||
let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0);
|
||||
assert!((w.iter().sum::<f32>() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}");
|
||||
assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}");
|
||||
assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]);
|
||||
}
|
||||
|
||||
const WINDOW: f32 = 640.5;
|
||||
const NATURAL: [f32; 3] = [120.0, 80.0, 80.0];
|
||||
const GROW: [f32; 3] = [1.0, 0.0, 0.0];
|
||||
|
||||
/// One frame of a table long enough to scroll; the rects of its header cells.
|
||||
fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec<egui::Event>) -> Vec<egui::Rect> {
|
||||
scrolled_frame(ctx, width, natural, 0.0, events)
|
||||
}
|
||||
|
||||
/// [`table_frame`], scrolled `offset` points sideways.
|
||||
fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec<egui::Event>) -> Vec<egui::Rect> {
|
||||
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0)));
|
||||
let raw = egui::RawInput { screen_rect, events, ..Default::default() };
|
||||
let mut cells = Vec::new();
|
||||
let out = ctx.run_ui(raw, |ui| {
|
||||
cells.clear();
|
||||
egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| {
|
||||
fitted_table(ui, "test", natural, &GROW)
|
||||
.header(20.0, |mut header| {
|
||||
for _ in natural {
|
||||
header.col(|ui| cells.push(ui.max_rect()));
|
||||
}
|
||||
})
|
||||
.body(|mut body| {
|
||||
for _ in 0..40 {
|
||||
body.row(20.0, |mut row| {
|
||||
for _ in natural {
|
||||
row.col(|ui| {
|
||||
ui.label("x");
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
out.drop_without_applying_deltas();
|
||||
cells
|
||||
}
|
||||
|
||||
/// A new context with the table open and settled, and the rects of its header cells.
|
||||
fn opened_table() -> (egui::Context, Vec<egui::Rect>) {
|
||||
let ctx = egui::Context::default();
|
||||
table_frame(&ctx, WINDOW, &NATURAL, Vec::new());
|
||||
let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new());
|
||||
(ctx, cells)
|
||||
}
|
||||
|
||||
/// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go.
|
||||
fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) {
|
||||
use egui::{Event, Modifiers, PointerButton};
|
||||
let start = egui::pos2(cell.right() + 4.0, cell.center().y);
|
||||
let halfway = start + egui::vec2(by / 2.0, 0.0);
|
||||
let end = start + egui::vec2(by, 0.0);
|
||||
let moved = Event::PointerMoved;
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] {
|
||||
table_frame(ctx, WINDOW, &NATURAL, vec![event]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() {
|
||||
let (_, opened) = opened_table();
|
||||
for (dragged, cell) in opened.iter().enumerate() {
|
||||
let (ctx, _) = opened_table();
|
||||
drag_edge(&ctx, *cell, -30.0);
|
||||
table_frame(&ctx, WINDOW, &NATURAL, Vec::new());
|
||||
let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new());
|
||||
for (column, (was, now)) in opened.iter().zip(&after).enumerate() {
|
||||
let want = if column == dragged { was.width() - 30.0 } else { was.width() };
|
||||
assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_fit_replaces_the_column_widths() {
|
||||
let (ctx, opened) = opened_table();
|
||||
drag_edge(&ctx, opened[0], -30.0);
|
||||
let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new());
|
||||
assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}");
|
||||
let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new());
|
||||
let widths: Vec<f32> = wider.iter().map(|c| c.width().round()).collect();
|
||||
assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}");
|
||||
assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}");
|
||||
let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new());
|
||||
assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrolling_sideways_keeps_dragged_widths() {
|
||||
let (ctx, opened) = opened_table();
|
||||
drag_edge(&ctx, opened[0], 100.0);
|
||||
table_frame(&ctx, WINDOW, &NATURAL, Vec::new());
|
||||
let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new());
|
||||
assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}");
|
||||
for offset in [13.3, 27.77, 41.1, 0.6] {
|
||||
scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new());
|
||||
let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new());
|
||||
assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ use audiosuite::SPEED_RAMP_CHOICES;
|
||||
use audiosuite::audiosuite_window;
|
||||
pub use files::{NotUnicode, ask_to_save, open_path, open_session_bytes, run_or_ask, takes_path, unicode};
|
||||
use files::{OPEN_PENDING, default_dir, open_pending_session, path_dialog};
|
||||
use strip_silence::{AUTO_NAME_LABELS, STRIP_NAME_LABELS, StripRectangles, auto_rename_action, strip_name_fields, strip_silence_action};
|
||||
use strip_silence::{AUTO_NAME_LABELS, STRIP_NAME_LABELS, StripRectangles, StripValues, auto_rename_action, strip_name_fields, strip_silence_action};
|
||||
pub use strip_silence::{StripRects, strip_silence_rectangles};
|
||||
|
||||
pub mod new_tracks;
|
||||
@@ -78,6 +78,8 @@ pub struct Dialogs {
|
||||
pending_session: Option<(String, Vec<u8>)>,
|
||||
/// The naming scheme Strip Silence gives the clips it leaves, kept from one use to the next.
|
||||
pub strip_names: StripNames,
|
||||
/// The values Strip Silence last had, which it opens with next time.
|
||||
strip_values: StripValues,
|
||||
/// The Strip Silence rectangles the Edit window draws while Strip Silence is open.
|
||||
strip_rectangles: StripRectangles,
|
||||
}
|
||||
@@ -211,7 +213,10 @@ impl Dialogs {
|
||||
Dialog::Number { cmd: id.into(), title: "Quantize strength".into(), key: "strength".into(), value: 100.0, suffix: "%".into() }
|
||||
}
|
||||
"edit.fades_create" => Dialog::Fades { shape: "equal power".into() },
|
||||
"edit.strip_silence" => Dialog::StripSilence { threshold: -48.0, min_ms: 50.0, pre_ms: 5.0, post_ms: 20.0 },
|
||||
"edit.strip_silence" => {
|
||||
let StripValues([threshold, min_ms, pre_ms, post_ms]) = self.strip_values;
|
||||
Dialog::StripSilence { threshold, min_ms, pre_ms, post_ms }
|
||||
}
|
||||
"track.group" => {
|
||||
let s = e.session();
|
||||
let members = s.tracks.iter().map(|t| (t.id.0, t.name.clone(), s.edit.selected_tracks.contains(&t.id))).collect();
|
||||
@@ -712,6 +717,14 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
});
|
||||
// Strip Silence keeps the values it shows, however it closes: Escape, Cancel or one of its actions.
|
||||
match &d {
|
||||
Dialog::StripSilence { threshold, min_ms, pre_ms, post_ms } => {
|
||||
app.dialogs.strip_values = StripValues([*threshold, *min_ms, *pre_ms, *post_ms])
|
||||
}
|
||||
Dialog::StripSilenceRename { strip, .. } => app.dialogs.strip_values = StripValues(*strip),
|
||||
_ => {}
|
||||
}
|
||||
if esc || ctx.memory(|m| m.data.get_temp::<bool>(egui::Id::unique("dlg_cancel")).unwrap_or(false)) {
|
||||
keep = false;
|
||||
action = None;
|
||||
|
||||
@@ -3,6 +3,17 @@ use super::{Arc, ClipId, Dialog, SoundApp, StripNames, Tokens, TrackId, Value, j
|
||||
/// What Strip keeps on each track: the Strip Silence rectangles.
|
||||
pub type StripRects = Arc<Vec<(TrackId, Vec<soundcraft_time::Range>)>>;
|
||||
|
||||
/// The Strip Silence values (threshold dB, min strip duration, clip start and end pads in ms) the
|
||||
/// window opens with: the ones it last had, or these defaults before its first use.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) struct StripValues(pub(super) [f64; 4]);
|
||||
|
||||
impl Default for StripValues {
|
||||
fn default() -> Self {
|
||||
Self([-48.0, 50.0, 5.0, 20.0])
|
||||
}
|
||||
}
|
||||
|
||||
/// The session revision and the Strip Silence values (as bits) that rectangles were found for.
|
||||
type StripKey = (u64, [u64; 4]);
|
||||
|
||||
|
||||
@@ -167,14 +167,20 @@ fn main_area_content(app: &mut SoundApp, ui: &mut Ui) {
|
||||
}
|
||||
app.edit_layout.content_h = content_h;
|
||||
let clip_rect = Rect::from_min_max(pos2(full.min.x, tl.min.y), pos2(full.max.x, tl.max.y));
|
||||
let grid = clips::GridLines::new(app.engine.session(), tl);
|
||||
let grid_revision = app.engine.revision;
|
||||
for (id, r) in app.edit_layout.rows.clone() {
|
||||
let row = rect(r);
|
||||
if row.max.y >= clip_rect.min.y && row.min.y <= clip_rect.max.y {
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(row));
|
||||
child.set_clip_rect(clip_rect);
|
||||
track_row(app, &mut child, TrackId(id), row, tl, &cols);
|
||||
track_row(app, &mut child, TrackId(id), row, tl, &cols, &grid);
|
||||
}
|
||||
}
|
||||
// Keep one consistent grid snapshot during this pass, then refresh after a row edits it.
|
||||
if app.engine.revision != grid_revision {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
// Below the tracks a click clears the selection and a double-click opens New Tracks.
|
||||
let empty = Rect::from_min_max(pos2(full.min.x, y.max(tl.min.y)), tl.max);
|
||||
if empty.height() > 4.0 {
|
||||
|
||||
@@ -25,26 +25,41 @@ pub(super) fn draw_strip_silence(painter: &egui::Painter, s: &Session, tl: Rect,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn grid_lines(painter: &egui::Painter, s: &Session, tl: Rect, lane: Rect) {
|
||||
let t = Tokens::current();
|
||||
let view = Range::new(sample_at(s, tl, tl.min.x).max(0), sample_at(s, tl, tl.max.x));
|
||||
let sr = s.sample_rate;
|
||||
// Bar lines always; grid lines when enabled and dense enough.
|
||||
let bar = GridValue::Note { value: NoteValue::Bar, dotted: false, triplet: false };
|
||||
let bar_px = bar.step_samples(view.start, sr, &s.tempo, s.frame_rate) as f64 / s.edit.zoom.samples_per_px;
|
||||
if bar_px > 6.0 {
|
||||
let col = grid_veil(t.bar_line, t.playlist_bg);
|
||||
for at in bar.lines(view.start, view.end, sr, &s.tempo, s.frame_rate, 600) {
|
||||
let x = x_of(s, tl, at);
|
||||
painter.line_segment([pos2(x, lane.min.y), pos2(x, lane.max.y)], Stroke::new(1.0, col));
|
||||
/// Grid positions computed once for the current viewport and shared by all visible lanes.
|
||||
#[derive(Default)]
|
||||
pub(super) struct GridLines {
|
||||
bars: Vec<f32>,
|
||||
grid: Vec<f32>,
|
||||
}
|
||||
|
||||
impl GridLines {
|
||||
/// Collect and project visible lines before drawing any lanes in this frame.
|
||||
pub(super) fn new(s: &Session, tl: Rect) -> Self {
|
||||
let mut lines = Self::default();
|
||||
let view = Range::new(sample_at(s, tl, tl.min.x).max(0), sample_at(s, tl, tl.max.x));
|
||||
let sr = s.sample_rate;
|
||||
// Bar lines always; grid lines when enabled and dense enough.
|
||||
let bar = GridValue::Note { value: NoteValue::Bar, dotted: false, triplet: false };
|
||||
let bar_px = bar.step_samples(view.start, sr, &s.tempo, s.frame_rate) as f64 / s.edit.zoom.samples_per_px;
|
||||
if bar_px > 6.0 {
|
||||
lines.bars = bar.lines(view.start, view.end, sr, &s.tempo, s.frame_rate, 600).into_iter().map(|at| x_of(s, tl, at)).collect();
|
||||
}
|
||||
if s.edit.grid_lines {
|
||||
let step_px = s.edit.grid.step_samples(view.start, sr, &s.tempo, s.frame_rate) as f64 / s.edit.zoom.samples_per_px;
|
||||
if s.edit.grid_clips_markers || step_px > 7.0 {
|
||||
let visible_columns = tl.width().ceil().clamp(1.0, 16_384.0) as usize;
|
||||
lines.grid = s.grid_lines(view.start, view.end, visible_columns).into_iter().map(|at| x_of(s, tl, at)).collect();
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
if s.edit.grid_lines {
|
||||
let step_px = s.edit.grid.step_samples(view.start, sr, &s.tempo, s.frame_rate) as f64 / s.edit.zoom.samples_per_px;
|
||||
if step_px > 7.0 {
|
||||
let col = grid_veil(t.grid_line, t.playlist_bg);
|
||||
for at in s.edit.grid.lines(view.start, view.end, sr, &s.tempo, s.frame_rate, 2000) {
|
||||
let x = x_of(s, tl, at);
|
||||
|
||||
/// Draw the prepared lines on one lane, preserving bar and grid colors and stacking order.
|
||||
pub(super) fn draw(&self, painter: &egui::Painter, lane: Rect) {
|
||||
let t = Tokens::current();
|
||||
for (positions, color) in [(&self.bars, t.bar_line), (&self.grid, t.grid_line)] {
|
||||
let col = grid_veil(color, t.playlist_bg);
|
||||
for &x in positions {
|
||||
painter.line_segment([pos2(x, lane.min.y), pos2(x, lane.max.y)], Stroke::new(1.0, col));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,8 @@ pub(super) fn drive_drag(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let plan = drag_plan(ctx, &s, app.engine.revision, clips, (*from_track, *tt), *grab_at);
|
||||
*delta = move_delta(&plan, &s, *from_track, at - *grab_at, ctx.input(|i| i.modifiers.command));
|
||||
}
|
||||
Some(Gesture::TrimStart { to, .. } | Gesture::TrimEnd { to, .. }) => *to = drag_snap(&s, at, ctx.input(|i| i.modifiers.command)),
|
||||
Some(Gesture::TrimStart { clip, to, .. }) => *to = trim_drag_snap(&s, *clip, at, true, ctx.input(|i| i.modifiers.command)),
|
||||
Some(Gesture::TrimEnd { clip, to, .. }) => *to = trim_drag_snap(&s, *clip, at, false, ctx.input(|i| i.modifiers.command)),
|
||||
Some(Gesture::MidiClip { to, .. }) => *to = at,
|
||||
Some(Gesture::Fade { clip, fade_in, to, .. }) => {
|
||||
if let Some(range) = s.find_clip(*clip).and_then(|(_, c)| fade_drag_range(c, *fade_in, at)) {
|
||||
@@ -206,7 +207,18 @@ fn finish_drag(app: &mut SoundApp, s: &Session, tl: Rect, p: Option<Pos2>) {
|
||||
|
||||
/// Grid snapping while dragging; holding Cmd/Ctrl swaps Grid and Slip.
|
||||
pub(super) fn drag_snap(s: &Session, at: Samples, flip: bool) -> Samples {
|
||||
if s.edit.edit_mode.is_grid() != flip { s.edit.grid.snap(at, s.sample_rate, &s.tempo, s.frame_rate) } else { at }
|
||||
drag_snap_excluding(s, at, flip, &[])
|
||||
}
|
||||
|
||||
/// Grid snapping that ignores boundaries belonging to clips changed by the gesture.
|
||||
pub(super) fn drag_snap_excluding(s: &Session, at: Samples, flip: bool, excluded: &[ClipId]) -> Samples {
|
||||
if s.edit.edit_mode.is_grid() != flip { s.snap_to_grid_excluding(at, excluded) } else { at }
|
||||
}
|
||||
|
||||
/// Snap a trim while preserving the clip edge when the pointer returns to its origin.
|
||||
pub(super) fn trim_drag_snap(s: &Session, clip: ClipId, at: Samples, start: bool, flip: bool) -> Samples {
|
||||
let origin = s.find_clip(clip).map(|(_, clip)| if start { clip.start } else { clip.end() });
|
||||
if origin == Some(at) { at } else { drag_snap_excluding(s, at, flip, &[clip]) }
|
||||
}
|
||||
|
||||
/// What a clip drag works out once per target track rather than every frame: where the tracks go
|
||||
@@ -216,6 +228,7 @@ pub(super) struct DragPlan {
|
||||
pub(super) dest: Option<Vec<(TrackId, TrackId)>>,
|
||||
pub(super) groups: Vec<(TrackId, Samples, Vec<Samples>)>,
|
||||
pub(super) moving: Vec<(TrackId, Samples, Samples)>,
|
||||
moving_ids: Vec<ClipId>,
|
||||
grabbed: Option<Clip>,
|
||||
}
|
||||
|
||||
@@ -246,10 +259,11 @@ pub(super) fn drag_plan(
|
||||
};
|
||||
let ids: HashSet<ClipId> = clips.iter().copied().collect();
|
||||
let movable = |c: &&Clip| ids.contains(&c.id) && !ops::locked(c);
|
||||
let moving = s.tracks.iter().flat_map(|t| t.clips().iter().filter(movable).map(|c| (t.id, c.start, c.length))).collect();
|
||||
let moving: Vec<_> = s.tracks.iter().flat_map(|t| t.clips().iter().filter(movable).map(|c| (t.id, c.start, c.length))).collect();
|
||||
let moving_ids: Vec<_> = s.tracks.iter().flat_map(|t| t.clips().iter().filter(movable).map(|c| c.id)).collect();
|
||||
let mine: Vec<&Clip> = s.track(from).map(|t| t.clips().iter().filter(movable).collect()).unwrap_or_default();
|
||||
let grabbed = mine.iter().rev().find(|c| c.range().contains(grab_at)).or_else(|| mine.iter().min_by_key(|c| c.start)).map(|c| (*c).clone());
|
||||
let plan = Arc::new(DragPlan { dest, groups, moving, grabbed });
|
||||
let plan = Arc::new(DragPlan { dest, groups, moving, moving_ids, grabbed });
|
||||
ctx.data_mut(|d| d.insert_temp(id, (key, Arc::clone(&plan))));
|
||||
plan
|
||||
}
|
||||
@@ -258,6 +272,10 @@ pub(super) fn drag_plan(
|
||||
/// Shuffle lands the earliest clip bound for the target track on a slot there, as
|
||||
/// `edit.move_clips` does; Grid snaps the grabbed clip.
|
||||
fn move_delta(plan: &DragPlan, s: &Session, from: TrackId, raw: Samples, flip: bool) -> Samples {
|
||||
let track_changed = plan.dest.as_ref().is_some_and(|dest| ops::lands(dest, from) != from);
|
||||
if raw == 0 && !track_changed {
|
||||
return 0;
|
||||
}
|
||||
let mode = s.edit.edit_mode;
|
||||
if mode == EditMode::Shuffle {
|
||||
let to = plan.dest.as_ref().map_or(from, |d| ops::lands(d, from));
|
||||
@@ -268,7 +286,7 @@ fn move_delta(plan: &DragPlan, s: &Session, from: TrackId, raw: Samples, flip: b
|
||||
} else if mode.is_grid() != flip
|
||||
&& let Some(c) = &plan.grabbed
|
||||
{
|
||||
ops::grid_delta(s, c, raw, mode == EditMode::GridRelative)
|
||||
ops::grid_delta(s, c, raw, mode == EditMode::GridRelative, &plan.moving_ids)
|
||||
} else {
|
||||
raw
|
||||
}
|
||||
|
||||
@@ -9,9 +9,10 @@ use super::{
|
||||
|
||||
// ---- interaction -----------------------------------------------------------------------------
|
||||
|
||||
/// Apply snapping when the current edit mode or Snap to Grid option enables it.
|
||||
pub(super) fn snap(s: &Session, at: Samples) -> Samples {
|
||||
let on = s.edit.edit_mode.is_grid() || s.edit.flag(ops::SNAP_TO_GRID);
|
||||
if on { s.edit.grid.snap(at, s.sample_rate, &s.tempo, s.frame_rate) } else { at }
|
||||
if on { s.snap_to_grid(at) } else { at }
|
||||
}
|
||||
|
||||
pub(super) fn clip_at(track: &Track, at: Samples) -> Option<&Clip> {
|
||||
|
||||
@@ -2,6 +2,25 @@ use super::*;
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
|
||||
/// A trim cannot snap to the clip's own old boundary in Clips/Markers mode.
|
||||
#[test]
|
||||
fn clips_markers_trim_ignores_the_trimmed_clip() {
|
||||
let mut s = Session::default();
|
||||
let track = s.add_track(TrackKind::Midi, soundcraft_model::ChannelFormat::Mono, None);
|
||||
let clip = Clip::midi(s.new_clip_id(), "Notes", 1_000, 1_000, soundcraft_midi::Sequence::default());
|
||||
let clip_id = clip.id;
|
||||
s.track_mut(track).and_then(Track::playlist_mut).unwrap().clips.push(clip);
|
||||
s.add_marker("Inside", soundcraft_model::MarkerKind::Marker, 1_500, 1_500);
|
||||
s.add_marker("Target", soundcraft_model::MarkerKind::Marker, 2_500, 2_500);
|
||||
s.edit.edit_mode = soundcraft_model::EditMode::Grid;
|
||||
s.edit.grid_clips_markers = true;
|
||||
|
||||
assert_eq!(super::drag::drag_snap(&s, 2_100, false), 2_000);
|
||||
assert_eq!(super::drag::drag_snap_excluding(&s, 2_100, false, &[clip_id]), 2_500);
|
||||
assert_eq!(super::drag::trim_drag_snap(&s, clip_id, 1_000, true, false), 1_000);
|
||||
assert_eq!(super::drag::trim_drag_snap(&s, clip_id, 2_000, false, false), 2_000);
|
||||
}
|
||||
|
||||
/// The painted header selectors are interactive controls; their accessible name is the field
|
||||
/// they edit, not the short value text ("Read", "Waveform") painted inside them.
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::automation::draw_automation;
|
||||
use super::clips::{ClipLane, draw_clip, draw_live_take, draw_strip_silence, grid_lines};
|
||||
use super::clips::{ClipLane, GridLines, draw_clip, draw_live_take, draw_strip_silence};
|
||||
use super::header::{header_column, track_header};
|
||||
use super::input::lane_interaction;
|
||||
use super::layout::{Column, HEADER_W, LANE_H, STRIP_W, lane_rect, sample_at, x_of};
|
||||
@@ -58,7 +58,8 @@ pub(crate) fn click_track(app: &mut SoundApp, id: TrackId, mods: egui::Modifiers
|
||||
|
||||
// ---- track rows ------------------------------------------------------------------------------
|
||||
|
||||
pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect, tl: Rect, cols: &[Column]) {
|
||||
/// Draw one track with grid positions shared by all lanes in the current frame.
|
||||
pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect, tl: Rect, cols: &[Column], grid: &GridLines) {
|
||||
let t = Tokens::current();
|
||||
let s = app.engine.session_arc();
|
||||
let Some(track) = s.track(id) else { return };
|
||||
@@ -84,7 +85,7 @@ pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect,
|
||||
let s = app.engine.session_arc();
|
||||
// Shown grid lines go over the clips; otherwise the bar lines stay behind them.
|
||||
if !s.edit.grid_lines {
|
||||
grid_lines(&painter, &s, tl, lane);
|
||||
grid.draw(&painter, lane);
|
||||
}
|
||||
let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x));
|
||||
let auto_view = AutoParam::parse(&track.view);
|
||||
@@ -98,7 +99,7 @@ pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect,
|
||||
draw_live_take(app, &painter, &s, track, tl, lane);
|
||||
crate::video_track::draw_lane(app, &painter, &s, track, tl, lane);
|
||||
if s.edit.grid_lines {
|
||||
grid_lines(&painter, &s, tl, lane);
|
||||
grid.draw(&painter, lane);
|
||||
}
|
||||
if let Some(p) = &auto_view {
|
||||
draw_automation(&painter, &s, track, p, tl, lane);
|
||||
|
||||
@@ -27,6 +27,7 @@ pub mod menus;
|
||||
pub mod mix_window;
|
||||
pub mod palette;
|
||||
pub mod panels;
|
||||
pub mod preferences;
|
||||
pub mod shortcuts;
|
||||
pub mod theme;
|
||||
pub mod toolbar;
|
||||
@@ -114,6 +115,13 @@ pub struct UiState {
|
||||
pub show_workspace: bool,
|
||||
pub show_configurations: bool,
|
||||
pub show_playback_engine: bool,
|
||||
/// Setup › Preferences. The selected page is kept per machine; the search and staged values
|
||||
/// live in [`preferences::PreferencesState`] and are discarded when the window closes.
|
||||
pub show_preferences: bool,
|
||||
pub preferences_page: preferences::PreferencesPage,
|
||||
pub preferences_window_pos: Option<[f32; 2]>,
|
||||
pub reduce_visual_effects: preferences::ReduceVisualEffects,
|
||||
pub undo_levels: usize,
|
||||
/// 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
|
||||
@@ -182,6 +190,11 @@ impl Default for UiState {
|
||||
show_workspace: false,
|
||||
show_configurations: false,
|
||||
show_playback_engine: false,
|
||||
show_preferences: false,
|
||||
preferences_page: preferences::PreferencesPage::default(),
|
||||
preferences_window_pos: None,
|
||||
reduce_visual_effects: preferences::ReduceVisualEffects::default(),
|
||||
undo_levels: 64,
|
||||
audio: soundcraft_playback::AudioConfig::default(),
|
||||
mix_separate: false,
|
||||
show_io_setup: false,
|
||||
@@ -302,6 +315,7 @@ pub struct SoundApp {
|
||||
pub ops: ops_windows::OpsState,
|
||||
pub extra: extra_windows::ExtraState,
|
||||
pub palette: palette::PaletteState,
|
||||
pub preferences: preferences::PreferencesState,
|
||||
/// Bring the separate Mix window to the front on the next frame.
|
||||
pub(crate) focus_mix: bool,
|
||||
/// Scroll Into View: the track each window brings to its top (Edit) or left (Mix) when it
|
||||
|
||||
+150
-45
@@ -75,6 +75,8 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
|
||||
("ui.bounce_dialog", "Bounce Mix…", "", None),
|
||||
("ui.set", "Set UI State", "", None),
|
||||
("ui.theme", "Appearance", "", None),
|
||||
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
|
||||
("ui.undo_levels", "Levels of Undo", "", None),
|
||||
];
|
||||
|
||||
/// Extra catalog mappings handled by the UI layer.
|
||||
@@ -225,56 +227,65 @@ pub fn tree() -> Vec<MenuNode> {
|
||||
|
||||
pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
let t = crate::theme::Tokens::current();
|
||||
let menu_entries_enabled = !app.ui.show_preferences;
|
||||
let preferences_enabled = preferences_menu_enabled(app);
|
||||
egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(t.menu_bar).inner_margin(egui::Margin::symmetric(8, 2))).show(
|
||||
ui,
|
||||
|ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button("SoundCraft", |ui| {
|
||||
if ui.button("About SoundCraft").clicked() {
|
||||
app.ui.show_about = true;
|
||||
}
|
||||
if ui.button("Check for Updates…").clicked() {
|
||||
let _ = app.run("app.checkForUpdates", json!({}));
|
||||
}
|
||||
if ui.button("Session Info").clicked() {
|
||||
app.ui.show_session_info = true;
|
||||
}
|
||||
if ui.button("Session Audio Health").clicked() {
|
||||
let _ = app.run("window.audio_health", json!({"value": true}));
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Quit").clicked() {
|
||||
let _ = crate::dialogs::run_or_ask(app, "app.quit", json!({}));
|
||||
}
|
||||
ui.add_enabled_ui(menu_entries_enabled, |ui| {
|
||||
if ui.button("About SoundCraft").clicked() {
|
||||
app.ui.show_about = true;
|
||||
}
|
||||
if ui.add_enabled(preferences_enabled, egui::Button::new("Preferences...")).clicked() {
|
||||
let _ = app.run("setup.preferences", json!({"value": true}));
|
||||
}
|
||||
if ui.button("Check for Updates…").clicked() {
|
||||
let _ = app.run("app.checkForUpdates", json!({}));
|
||||
}
|
||||
if ui.button("Session Info").clicked() {
|
||||
app.ui.show_session_info = true;
|
||||
}
|
||||
if ui.button("Session Audio Health").clicked() {
|
||||
let _ = app.run("window.audio_health", json!({"value": true}));
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Quit").clicked() {
|
||||
let _ = crate::dialogs::run_or_ask(app, "app.quit", json!({}));
|
||||
}
|
||||
});
|
||||
});
|
||||
let extra = ui_aliases();
|
||||
for root in tree() {
|
||||
ui.menu_button(&root.label, |ui| {
|
||||
for c in &root.children {
|
||||
menu_node(app, ui, c, &extra);
|
||||
if c.path == "File > Open" {
|
||||
crate::recent::menu(app, ui);
|
||||
ui.add_enabled_ui(menu_entries_enabled, |ui| {
|
||||
for c in &root.children {
|
||||
menu_node(app, ui, c, &extra);
|
||||
if c.path == "File > Open" {
|
||||
crate::recent::menu(app, ui);
|
||||
}
|
||||
if c.path == "Track > New..." {
|
||||
instrument_menu(app, ui);
|
||||
}
|
||||
}
|
||||
if c.path == "Track > New..." {
|
||||
instrument_menu(app, ui);
|
||||
if root.label == "AudioSuite" {
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new("Processes selected clips offline").small().color(t.text_dim));
|
||||
}
|
||||
}
|
||||
if root.label == "AudioSuite" {
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new("Processes selected clips offline").small().color(t.text_dim));
|
||||
}
|
||||
if root.label == "Window" {
|
||||
ui.separator();
|
||||
let mut separate = app.ui.mix_separate;
|
||||
if ui
|
||||
.checkbox(&mut separate, "Mix in Separate Window")
|
||||
.on_hover_text("Show Edit and Mix at once, e.g. one per monitor")
|
||||
.changed()
|
||||
{
|
||||
let _ = run_ui_command(app, "window.mix_separate", &json!({"value": separate}));
|
||||
ui.close();
|
||||
if root.label == "Window" {
|
||||
ui.separator();
|
||||
let mut separate = app.ui.mix_separate;
|
||||
if ui
|
||||
.checkbox(&mut separate, "Mix in Separate Window")
|
||||
.on_hover_text("Show Edit and Mix at once, e.g. one per monitor")
|
||||
.changed()
|
||||
{
|
||||
let _ = run_ui_command(app, "window.mix_separate", &json!({"value": separate}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
let title = format!(
|
||||
@@ -338,18 +349,31 @@ pub fn command_for_path(path: &str, extra: &[(&str, &str)]) -> Option<String> {
|
||||
|
||||
/// Enabled and checked state shared by all menu presentations.
|
||||
pub fn item_state(app: &SoundApp, path: &str, id: Option<&str>) -> (bool, bool) {
|
||||
let enabled = match id {
|
||||
Some(i)
|
||||
if i.starts_with("window.") || i.starts_with("view.mix_section") || matches!(i, "audiosuite.process" | "ui.dock" | "ui.dock.reset") =>
|
||||
{
|
||||
true
|
||||
let enabled = if app.ui.show_preferences {
|
||||
false
|
||||
} else {
|
||||
match id {
|
||||
Some("setup.preferences") => preferences_menu_enabled(app),
|
||||
Some(i)
|
||||
if i.starts_with("window.")
|
||||
|| i.starts_with("view.mix_section")
|
||||
|| matches!(i, "audiosuite.process" | "ui.dock" | "ui.dock.reset") =>
|
||||
{
|
||||
true
|
||||
}
|
||||
Some(i) => soundcraft_engine::find_command(i).is_some_and(|c| (c.enabled)(&app.engine).is_ok() && !app.engine.blocked_while_recording(i)),
|
||||
None => false,
|
||||
}
|
||||
Some(i) => soundcraft_engine::find_command(i).is_some_and(|c| (c.enabled)(&app.engine).is_ok() && !app.engine.blocked_while_recording(i)),
|
||||
None => false,
|
||||
};
|
||||
(enabled, checked_state(app, path, id))
|
||||
}
|
||||
|
||||
/// Preferences cannot replace audio resources while transport is active or another Preferences
|
||||
/// instance is already modal.
|
||||
fn preferences_menu_enabled(app: &SoundApp) -> bool {
|
||||
!app.ui.show_preferences && !app.is_playing() && !app.engine.transport.recording
|
||||
}
|
||||
|
||||
fn checked_state(app: &SoundApp, path: &str, id: Option<&str>) -> bool {
|
||||
let e = &app.engine.session().edit;
|
||||
match id {
|
||||
@@ -469,6 +493,10 @@ pub fn live_label(app: &SoundApp, id: Option<&str>) -> Option<String> {
|
||||
|
||||
/// Menu-style invocation: may open a dialog.
|
||||
pub fn invoke_menu(app: &mut SoundApp, id: &str, path: &str) {
|
||||
if id == "setup.preferences" {
|
||||
let _ = app.run(id, json!({"value": true}));
|
||||
return;
|
||||
}
|
||||
if let Some((_, w)) = MENU_WINDOWS.iter().find(|(p, _)| *p == path)
|
||||
&& w.starts_with("window.")
|
||||
{
|
||||
@@ -587,6 +615,15 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
"window.midi_ops" => toggle(&mut app.ui.show_midi_ops),
|
||||
"window.rtp" => toggle(&mut app.ui.show_rtp),
|
||||
"window.playback_engine" => toggle(&mut app.ui.show_playback_engine),
|
||||
// The engine catalog already exposes this command. Handling it here keeps the menu,
|
||||
// control channel and scripted callers on the same public command id.
|
||||
"setup.preferences" => {
|
||||
let result = toggle(&mut app.ui.show_preferences);
|
||||
if !app.ui.show_preferences {
|
||||
app.preferences.discard_draft();
|
||||
}
|
||||
result
|
||||
}
|
||||
"window.io_setup" => toggle(&mut app.ui.show_io_setup),
|
||||
"window.shortcuts" => toggle(&mut app.ui.show_shortcuts),
|
||||
"window.color_palette" => toggle(&mut app.ui.show_color_palette),
|
||||
@@ -640,6 +677,8 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
app.ui.show_undo_history = false;
|
||||
app.ui.show_session_info = false;
|
||||
app.ui.show_audio_health = false;
|
||||
app.ui.show_preferences = false;
|
||||
app.preferences.discard_draft();
|
||||
app.ui.show_automation = false;
|
||||
app.ui.plugin_windows.clear();
|
||||
app.ui.audiosuite = None;
|
||||
@@ -694,6 +733,23 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
app.ui.theme = mode;
|
||||
json!({"mode": mode.id()})
|
||||
}
|
||||
"ui.reduce_visual_effects" => {
|
||||
let Some(mode) = p.get("mode").and_then(Value::as_str) else {
|
||||
return Some(Ok(json!({"mode": app.ui.reduce_visual_effects.id()})));
|
||||
};
|
||||
let Some(mode) = crate::preferences::ReduceVisualEffects::parse(mode) else {
|
||||
return Some(Err(format!("unknown visual-effects mode `{mode}` (never, playback or always)")));
|
||||
};
|
||||
app.ui.reduce_visual_effects = mode;
|
||||
json!({"mode": mode.id()})
|
||||
}
|
||||
"ui.undo_levels" => {
|
||||
if let Some(levels) = p.get("levels").and_then(Value::as_u64) {
|
||||
app.ui.undo_levels = usize::try_from(levels).unwrap_or(64).clamp(1, 64);
|
||||
app.engine.set_history_limit(app.ui.undo_levels);
|
||||
}
|
||||
json!({"levels": app.ui.undo_levels})
|
||||
}
|
||||
"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()) {
|
||||
@@ -706,8 +762,14 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
if let Err(error) = crate::docking::validate(&ns.docking).and_then(|()| crate::docking::validate_mix(&ns.mix_docking)) {
|
||||
return Some(Err(error));
|
||||
}
|
||||
let closed_preferences = app.ui.show_preferences && !ns.show_preferences;
|
||||
crate::docking::cancel_replaced_state(app, &ns);
|
||||
app.ui = ns;
|
||||
app.ui.undo_levels = app.ui.undo_levels.clamp(1, 64);
|
||||
app.engine.set_history_limit(app.ui.undo_levels);
|
||||
if closed_preferences {
|
||||
app.preferences.discard_draft();
|
||||
}
|
||||
json!({"ui": app.ui})
|
||||
}
|
||||
Err(e) => return Some(Err(format!("bad ui state: {e}"))),
|
||||
@@ -731,6 +793,49 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::{Services, SoundApp};
|
||||
|
||||
/// Preferences menu entries follow transport safety and the modal window locks every menu.
|
||||
#[test]
|
||||
fn preferences_menu_state_tracks_transport_and_modality() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
assert!(item_state(&app, "Setup > Preferences...", Some("setup.preferences")).0);
|
||||
|
||||
app.engine.transport.playing = true;
|
||||
assert!(!item_state(&app, "Setup > Preferences...", Some("setup.preferences")).0);
|
||||
app.engine.transport.playing = false;
|
||||
app.engine.transport.recording = true;
|
||||
assert!(!item_state(&app, "Setup > Preferences...", Some("setup.preferences")).0);
|
||||
|
||||
app.engine.transport.recording = false;
|
||||
app.ui.show_preferences = true;
|
||||
assert!(!item_state(&app, "Setup > Preferences...", Some("setup.preferences")).0);
|
||||
assert!(!item_state(&app, "Window > About", Some("window.about")).0);
|
||||
assert!(!item_state(&app, "File > Save Session", Some("session.save")).0);
|
||||
}
|
||||
|
||||
/// Re-selecting Preferences through either menu keeps its modal window open.
|
||||
#[test]
|
||||
fn preferences_menu_always_opens_instead_of_toggling() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
invoke_menu(&mut app, "setup.preferences", "Setup > Preferences...");
|
||||
assert!(app.ui.show_preferences);
|
||||
invoke_menu(&mut app, "setup.preferences", "Setup > Preferences...");
|
||||
assert!(app.ui.show_preferences);
|
||||
}
|
||||
|
||||
/// Generic UI-state updates clamp and immediately synchronize the engine history limit.
|
||||
#[test]
|
||||
fn ui_set_synchronizes_undo_levels_immediately() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
|
||||
let result = app.run("ui.set", json!({"undo_levels": 0})).unwrap();
|
||||
assert_eq!(result["ui"]["undo_levels"], 1);
|
||||
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (1, 1));
|
||||
|
||||
let result = app.run("ui.set", json!({"undo_levels": 100})).unwrap();
|
||||
assert_eq!(result["ui"]["undo_levels"], 64);
|
||||
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (64, 64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mix_view_aliases_are_allocated_once() {
|
||||
let first = ui_aliases();
|
||||
|
||||
@@ -7,7 +7,7 @@ pub(super) fn about(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
return;
|
||||
}
|
||||
let tab_id = egui::Id::unique("about_tab");
|
||||
egui::Window::new("About SoundCraft").open(&mut open).default_size(vec2(640.0, 420.0)).collapsible(false).show(ctx, |ui| {
|
||||
egui::Window::new("About SoundCraft").open(&mut open).default_size(vec2(820.0, 420.0)).collapsible(false).show(ctx, |ui| {
|
||||
let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);
|
||||
ui.horizontal(|ui| {
|
||||
for (i, l) in (0u8..).zip(["About", "Contributors", "Models"]) {
|
||||
|
||||
@@ -16,7 +16,6 @@ pub struct ExtraState {
|
||||
pub show_ui_customization: bool,
|
||||
pub auto_update_config: bool,
|
||||
pub ui_scale: f32,
|
||||
pub reduce_motion: bool,
|
||||
pub tooltips: bool,
|
||||
last_auto_update: f64,
|
||||
applied: Option<(f32, bool)>,
|
||||
@@ -29,7 +28,6 @@ impl Default for ExtraState {
|
||||
show_ui_customization: false,
|
||||
auto_update_config: false,
|
||||
ui_scale: 1.0,
|
||||
reduce_motion: false,
|
||||
tooltips: true,
|
||||
last_auto_update: 0.0,
|
||||
applied: None,
|
||||
@@ -59,7 +57,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
fn apply_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let want = (app.extra.ui_scale.clamp(0.75, 1.5), app.extra.reduce_motion);
|
||||
let reduce = match app.ui.reduce_visual_effects {
|
||||
crate::preferences::ReduceVisualEffects::Never => false,
|
||||
crate::preferences::ReduceVisualEffects::Playback => app.is_playing(),
|
||||
crate::preferences::ReduceVisualEffects::Always => true,
|
||||
};
|
||||
let want = (app.extra.ui_scale.clamp(0.75, 1.5), reduce);
|
||||
// Rescaling mid-drag would move the Interface scale slider out from under the pointer.
|
||||
if app.extra.applied == Some(want) || ctx.input(|i| i.pointer.any_down()) {
|
||||
return;
|
||||
@@ -163,7 +166,17 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.custom_formatter(|v, _| format!("{:.0} %", v * 100.0))
|
||||
.text("Interface scale"),
|
||||
);
|
||||
crate::widgets::checkbox(ui, &mut app.extra.reduce_motion, "Reduce motion");
|
||||
let mut chosen_effects = None;
|
||||
craft_ui::ComboBox::from_label("Reduce visual effects").selected_text(app.ui.reduce_visual_effects.label()).show_ui(ui, |ui| {
|
||||
for mode in crate::preferences::ReduceVisualEffects::ALL {
|
||||
if ui.selectable_label(app.ui.reduce_visual_effects == mode, mode.label()).clicked() {
|
||||
chosen_effects = Some(mode);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(mode) = chosen_effects {
|
||||
let _ = app.run("ui.reduce_visual_effects", json!({"mode": mode.id()}));
|
||||
}
|
||||
let mut chosen = None;
|
||||
craft_ui::ComboBox::from_label("Theme").selected_text(app.ui.theme.label()).show_ui(ui, |ui| {
|
||||
for mode in crate::theme::ThemeMode::ALL {
|
||||
@@ -179,7 +192,7 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.add_space(4.0);
|
||||
if ui.button("Reset").clicked() {
|
||||
app.extra.ui_scale = 1.0;
|
||||
app.extra.reduce_motion = false;
|
||||
let _ = app.run("ui.reduce_visual_effects", json!({"mode": "never"}));
|
||||
let _ = app.run("ui.theme", json!({"mode": crate::theme::ThemeMode::default().id()}));
|
||||
}
|
||||
},
|
||||
|
||||
@@ -408,7 +408,7 @@ fn configurations(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
app.ui.show_configurations = open;
|
||||
}
|
||||
|
||||
/// Restore a saved window configuration, keeping the configuration list and the appearance.
|
||||
/// Restore a window layout while retaining current application preferences and any open draft.
|
||||
/// A configuration saved before the current panel layouts gets the default layouts.
|
||||
pub fn recall_configuration(app: &mut SoundApp, saved: &Value) -> Result<(), String> {
|
||||
let mut saved = saved.clone();
|
||||
@@ -417,8 +417,14 @@ pub fn recall_configuration(app: &mut SoundApp, saved: &Value) -> Result<(), Str
|
||||
crate::docking::validate(&st.docking).and_then(|()| crate::docking::validate_mix(&st.mix_docking))?;
|
||||
st.configurations = app.ui.configurations.clone();
|
||||
st.theme = app.ui.theme;
|
||||
st.show_preferences = app.ui.show_preferences;
|
||||
st.preferences_page = app.ui.preferences_page;
|
||||
st.preferences_window_pos = app.ui.preferences_window_pos;
|
||||
st.reduce_visual_effects = app.ui.reduce_visual_effects;
|
||||
st.undo_levels = app.ui.undo_levels.clamp(1, 64);
|
||||
st.show_configurations = true;
|
||||
crate::docking::cancel_replaced_state(app, &st);
|
||||
app.engine.set_history_limit(st.undo_levels);
|
||||
app.ui = st;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -59,7 +59,7 @@ fn search_chord(m: Modifiers, mac: bool) -> bool {
|
||||
pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// Cmd+= and Cmd+0 are Mix/Edit and Quantize to Grid, not egui's built-in interface zoom.
|
||||
ctx.options_mut(|o| o.zoom_with_keyboard = false);
|
||||
if ctx.egui_wants_keyboard_input() || app.dialogs.open.is_some() {
|
||||
if ctx.egui_wants_keyboard_input() || app.dialogs.open.is_some() || app.ui.show_preferences {
|
||||
return;
|
||||
}
|
||||
// A scripted press is identified by its exact position in this pass's events, not by matching
|
||||
|
||||
@@ -457,6 +457,8 @@ fn a_preset_changed_in_an_effect_editor_is_stored_once() {
|
||||
fn preferences_saved_before_the_window_was_remembered_keep_full_scale() {
|
||||
let ui: super::UiState = serde_json::from_value(json!({"show_transport": true})).unwrap();
|
||||
assert_eq!((ui.window_size, ui.window_maximized, ui.ui_scale), ([1600.0, 1000.0], false, 1.0));
|
||||
assert_eq!(ui.reduce_visual_effects, crate::preferences::ReduceVisualEffects::Never);
|
||||
assert_eq!(ui.undo_levels, 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+339
-27
@@ -3,11 +3,11 @@
|
||||
use crate::theme::{Tokens, bold, mono, regular};
|
||||
use crate::widgets::{icon_button, key, key_fill};
|
||||
use crate::{SoundApp, icons};
|
||||
use egui::{Align2, Color32, CornerRadius, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use egui::{Align2, Color32, CornerRadius, Painter, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use serde_json::json;
|
||||
use soundcraft_engine::edit::{SHUFFLE_LOCK, SNAP_TO_GRID};
|
||||
use soundcraft_model::{EditMode, EditState, Tool};
|
||||
use soundcraft_time::{TimeFormat, format_length};
|
||||
use soundcraft_model::{EditMode, EditState, Session, Tool};
|
||||
use soundcraft_time::{FeetFramesValue, GridScale, GridValue, NoteValue, TimeFormat, TimecodeValue, format_length};
|
||||
|
||||
pub const HEIGHT: f32 = 78.0;
|
||||
|
||||
@@ -281,12 +281,12 @@ fn counters(app: &mut SoundApp, ui: &mut Ui) {
|
||||
ui.painter().text(pos2(r.max.x - 8.0, y), Align2::RIGHT_CENTER, format!("{st} · {dev}"), regular(10.0), t.text_dim);
|
||||
}
|
||||
|
||||
/// Grid-line toggle, grid value menu and nudge value menu.
|
||||
/// Draws the compact Grid and Nudge readouts and their scale menus.
|
||||
fn grid_nudge(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let t = Tokens::current();
|
||||
let (grid, nudge, lines) = {
|
||||
let (grid, nudge, lines, grid_follow, nudge_follow, clips_markers) = {
|
||||
let e = &app.engine.session().edit;
|
||||
(e.grid, e.nudge, e.grid_lines)
|
||||
(e.grid, e.nudge, e.grid_lines, e.grid_follow_main, e.nudge_follow_main, e.grid_clips_markers)
|
||||
};
|
||||
let (r, _) = ui.allocate_exact_size(vec2(170.0, 64.0), Sense::hover());
|
||||
ui.painter().rect(r, CornerRadius::same(4), t.counter_bg, Stroke::new(1.0, t.counter_border), StrokeKind::Inside);
|
||||
@@ -298,39 +298,243 @@ fn grid_nudge(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let _ = app.run("view.grid_lines", json!({}));
|
||||
}
|
||||
let gr = Rect::from_min_max(pos2(r.min.x + 60.0, r.min.y + 6.0), pos2(r.max.x - 4.0, r.min.y + 26.0));
|
||||
ui.painter().text(pos2(gr.max.x - 14.0, gr.center().y), Align2::RIGHT_CENTER, grid.label(), mono(11.0), t.counter_text);
|
||||
let grid_label = if clips_markers { GridScale::ClipsMarkers.label().to_string() } else { compact_grid_label(app.engine.session(), grid) };
|
||||
if !clips_markers {
|
||||
draw_compact_note_icon(ui.painter(), gr, grid, t.counter_text);
|
||||
}
|
||||
ui.painter().text(pos2(gr.max.x - 14.0, gr.center().y), Align2::RIGHT_CENTER, grid_label, mono(11.0), t.counter_text);
|
||||
let gresp = ui.interact(gr, ui.scope_id().with("grid_value"), Sense::click());
|
||||
value_menu(app, &gresp, "view.grid");
|
||||
value_menu(app, &gresp, "view.grid", grid, grid_follow, clips_markers, true);
|
||||
ui.painter().text(pos2(r.min.x + 10.0, r.min.y + 44.0), Align2::LEFT_CENTER, "Nudge", regular(11.0), t.counter_label);
|
||||
let nr = Rect::from_min_max(pos2(r.min.x + 60.0, r.min.y + 34.0), pos2(r.max.x - 4.0, r.min.y + 54.0));
|
||||
ui.painter().text(pos2(nr.max.x - 14.0, nr.center().y), Align2::RIGHT_CENTER, nudge.label(), mono(11.0), t.counter_text);
|
||||
draw_compact_note_icon(ui.painter(), nr, nudge, t.counter_text);
|
||||
ui.painter().text(
|
||||
pos2(nr.max.x - 14.0, nr.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
compact_grid_label(app.engine.session(), nudge),
|
||||
mono(11.0),
|
||||
t.counter_text,
|
||||
);
|
||||
let nresp = ui.interact(nr, ui.scope_id().with("nudge_value"), Sense::click());
|
||||
value_menu(app, &nresp, "view.nudge");
|
||||
value_menu(app, &nresp, "view.nudge", nudge, nudge_follow, false, false);
|
||||
for rr in [gr, nr] {
|
||||
icons::draw(ui.painter(), Rect::from_center_size(pos2(rr.max.x - 6.0, rr.center().y), vec2(10.0, 10.0)), "triangle_down", t.text_dim);
|
||||
}
|
||||
}
|
||||
|
||||
fn value_menu(app: &mut SoundApp, resp: &egui::Response, cmd: &str) {
|
||||
egui::Popup::menu(resp).show(|ui| {
|
||||
for v in ["1 bar", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/8t", "1/16t", "1/4."] {
|
||||
if ui.button(v).clicked() {
|
||||
let _ = app.run(cmd, json!({"value": v}));
|
||||
/// Formats a Grid/Nudge increment in the compact counter style for its time scale.
|
||||
fn compact_grid_label(session: &Session, value: GridValue) -> String {
|
||||
match value {
|
||||
GridValue::Note { value, dotted, triplet } => {
|
||||
let at_tick = session.tempo.samples_to_ticks(session.edit.selection.start, session.sample_rate);
|
||||
let meter = session.tempo.meter_at_tick(at_tick);
|
||||
let mut ticks = if value == NoteValue::Bar { meter.ticks_per_bar() } else { value.ticks() };
|
||||
if dotted {
|
||||
ticks = ticks * 3 / 2;
|
||||
}
|
||||
if triplet {
|
||||
ticks = ticks * 2 / 3;
|
||||
}
|
||||
let per_bar = meter.ticks_per_bar().max(1);
|
||||
let per_beat = meter.ticks_per_beat().max(1);
|
||||
let bars = ticks / per_bar;
|
||||
let remaining = ticks % per_bar;
|
||||
format!("{bars}|{}|{:03}", remaining / per_beat, remaining % per_beat)
|
||||
}
|
||||
GridValue::Seconds(seconds) => {
|
||||
let samples = session.sample_rate.samples(seconds);
|
||||
format_length(session.edit.selection.start, samples, TimeFormat::MinSecs, session.sample_rate, &session.tempo, session.frame_rate)
|
||||
}
|
||||
GridValue::Frames(frames) => {
|
||||
let samples = session.frame_rate.samples_at_frame(frames, session.sample_rate);
|
||||
format!(
|
||||
"{}.00",
|
||||
format_length(session.edit.selection.start, samples, TimeFormat::Timecode, session.sample_rate, &session.tempo, session.frame_rate)
|
||||
)
|
||||
}
|
||||
GridValue::Timecode(value) => match value {
|
||||
TimecodeValue::Second => "00:00:01:00.00",
|
||||
TimecodeValue::FiveFrames => "00:00:00:05.00",
|
||||
TimecodeValue::Frame => "00:00:00:01.00",
|
||||
TimecodeValue::HalfFrame => "00:00:00:00.50",
|
||||
TimecodeValue::QuarterFrame => "00:00:00:00.25",
|
||||
TimecodeValue::SubFrame => "00:00:00:00.01",
|
||||
}
|
||||
.to_string(),
|
||||
GridValue::FeetFrames(value) => match value {
|
||||
FeetFramesValue::Foot => "1+00",
|
||||
FeetFramesValue::Frame => "0+01",
|
||||
FeetFramesValue::QuarterFrame => "0+00.25",
|
||||
FeetFramesValue::SubFrame => "0+00.01",
|
||||
}
|
||||
.to_string(),
|
||||
GridValue::Samples(samples) => samples.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the musical symbol beside a compact Bars|Beats value.
|
||||
fn draw_compact_note_icon(painter: &Painter, rect: Rect, value: GridValue, color: Color32) {
|
||||
let GridValue::Note { value, dotted, triplet } = value else { return };
|
||||
draw_note_value_icon(painter, Rect::from_min_size(pos2(rect.min.x + 1.0, rect.min.y + 2.0), vec2(14.0, 16.0)), value, dotted, triplet, color);
|
||||
}
|
||||
|
||||
/// Draws a musical duration and its optional dotted or triplet modifier.
|
||||
fn draw_note_value_icon(painter: &Painter, rect: Rect, value: NoteValue, dotted: bool, triplet: bool, color: Color32) {
|
||||
let stroke = Stroke::new(1.2, color);
|
||||
let head = pos2(rect.min.x + 4.0, rect.max.y - 3.5);
|
||||
if value == NoteValue::Bar {
|
||||
painter.line_segment([pos2(rect.min.x + 2.0, rect.min.y + 2.0), pos2(rect.min.x + 2.0, rect.max.y - 2.0)], stroke);
|
||||
painter.line_segment([pos2(rect.min.x + 5.0, rect.min.y + 2.0), pos2(rect.min.x + 5.0, rect.max.y - 2.0)], stroke);
|
||||
painter.line_segment([pos2(rect.min.x + 2.0, rect.min.y + 3.0), pos2(rect.min.x + 10.0, rect.min.y + 3.0)], stroke);
|
||||
} else {
|
||||
let hollow = matches!(value, NoteValue::Whole | NoteValue::Half);
|
||||
if hollow {
|
||||
painter.circle_stroke(head, 2.2, stroke);
|
||||
} else {
|
||||
painter.circle_filled(head, 2.2, color);
|
||||
}
|
||||
if value != NoteValue::Whole {
|
||||
let stem_x = head.x + 2.0;
|
||||
painter.line_segment([pos2(stem_x, head.y), pos2(stem_x, rect.min.y + 2.0)], stroke);
|
||||
let flags = match value {
|
||||
NoteValue::Eighth => 1,
|
||||
NoteValue::Sixteenth => 2,
|
||||
NoteValue::ThirtySecond => 3,
|
||||
NoteValue::SixtyFourth => 4,
|
||||
_ => 0,
|
||||
};
|
||||
for flag in 0..flags {
|
||||
let y = rect.min.y + 2.0 + flag as f32 * 2.0;
|
||||
painter.line_segment([pos2(stem_x, y), pos2(stem_x + 4.0, y + 2.5)], stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
if dotted {
|
||||
painter.circle_filled(pos2(rect.max.x - 1.5, head.y), 1.0, color);
|
||||
}
|
||||
if triplet {
|
||||
painter.text(pos2(rect.min.x, rect.min.y), Align2::LEFT_TOP, "3", regular(7.0), color);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the complete Grid or Nudge increment, scale, and follow-mode menu.
|
||||
fn value_menu(app: &mut SoundApp, resp: &egui::Response, cmd: &str, current: GridValue, follow_main: bool, clips_markers: bool, allow_clips: bool) {
|
||||
egui::Popup::menu(resp).show(|ui| {
|
||||
ui.set_min_width(210.0);
|
||||
match current.scale() {
|
||||
GridScale::BarsBeats => {
|
||||
let selected = match current {
|
||||
GridValue::Note { value, .. } => value,
|
||||
_ => NoteValue::Sixteenth,
|
||||
};
|
||||
let suffix = match current {
|
||||
GridValue::Note { dotted: true, .. } => ".",
|
||||
GridValue::Note { triplet: true, .. } => "t",
|
||||
_ => "",
|
||||
};
|
||||
for value in NoteValue::ALL {
|
||||
let id = match value {
|
||||
NoteValue::Bar => "1 bar",
|
||||
NoteValue::Whole => "whole",
|
||||
NoteValue::Half => "1/2",
|
||||
NoteValue::Quarter => "1/4",
|
||||
NoteValue::Eighth => "1/8",
|
||||
NoteValue::Sixteenth => "1/16",
|
||||
NoteValue::ThirtySecond => "1/32",
|
||||
NoteValue::SixtyFourth => "1/64",
|
||||
};
|
||||
menu_note_value(ui, app, cmd, selected == value, value, json!(format!("{id}{suffix}")));
|
||||
}
|
||||
ui.separator();
|
||||
let (value, dotted, triplet) = match current {
|
||||
GridValue::Note { value, dotted, triplet } => (value, dotted, triplet),
|
||||
_ => (NoteValue::Sixteenth, false, false),
|
||||
};
|
||||
let base = match value {
|
||||
NoteValue::Bar => "1 bar",
|
||||
NoteValue::Whole => "whole",
|
||||
NoteValue::Half => "1/2",
|
||||
NoteValue::Quarter => "1/4",
|
||||
NoteValue::Eighth => "1/8",
|
||||
NoteValue::Sixteenth => "1/16",
|
||||
NoteValue::ThirtySecond => "1/32",
|
||||
NoteValue::SixtyFourth => "1/64",
|
||||
};
|
||||
menu_modifier(ui, app, cmd, dotted, "Dotted", "·", json!(if dotted { base.to_string() } else { format!("{base}.") }));
|
||||
menu_modifier(ui, app, cmd, triplet, "Triplet", "3", json!(if triplet { base.to_string() } else { format!("{base}t") }));
|
||||
}
|
||||
GridScale::MinSecs => {
|
||||
for seconds in [1.0, 0.5, 0.1, 0.01, 0.001] {
|
||||
let value = GridValue::Seconds(seconds);
|
||||
menu_value(ui, app, cmd, current == value, &value.label(), json!({"seconds": seconds}));
|
||||
}
|
||||
}
|
||||
GridScale::Timecode => {
|
||||
for value in TimecodeValue::ALL {
|
||||
let selected = current == GridValue::Timecode(value)
|
||||
|| matches!(
|
||||
(current, value),
|
||||
(GridValue::Frames(5), TimecodeValue::FiveFrames) | (GridValue::Frames(1), TimecodeValue::Frame)
|
||||
);
|
||||
menu_value(ui, app, cmd, selected, value.label(), json!({"timecode": value.id()}));
|
||||
}
|
||||
}
|
||||
GridScale::FeetFrames => {
|
||||
for value in FeetFramesValue::ALL {
|
||||
menu_value(ui, app, cmd, current == GridValue::FeetFrames(value), value.label(), json!({"feet_frames": value.id()}));
|
||||
}
|
||||
}
|
||||
GridScale::Samples => {
|
||||
for samples in [10_000, 1_000, 100, 10, 2, 1] {
|
||||
let value = GridValue::Samples(samples);
|
||||
menu_value(ui, app, cmd, current == value, &value.label(), json!({"samples": samples}));
|
||||
}
|
||||
}
|
||||
GridScale::ClipsMarkers => {}
|
||||
}
|
||||
ui.separator();
|
||||
for (label, v) in [
|
||||
("1 msec", json!({"seconds": 0.001})),
|
||||
("10 msec", json!({"seconds": 0.01})),
|
||||
("100 msec", json!({"seconds": 0.1})),
|
||||
("1 second", json!({"seconds": 1.0})),
|
||||
("1 frame", json!({"frames": 1})),
|
||||
("100 samples", json!({"samples": 100})),
|
||||
] {
|
||||
if ui.button(label).clicked() {
|
||||
let _ = app.run(cmd, json!({"value": v}));
|
||||
for scale in GridScale::TIME {
|
||||
let selected = !clips_markers && current.scale() == scale;
|
||||
if ui.selectable_label(selected, scale.label()).clicked() {
|
||||
let _ = app.run(cmd, json!({"format": scale.id(), "follow_main": false}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if allow_clips && ui.selectable_label(clips_markers, GridScale::ClipsMarkers.label()).clicked() {
|
||||
let _ = app.run(cmd, json!({"format": GridScale::ClipsMarkers.id(), "follow_main": false}));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.selectable_label(follow_main, "Follow Main Time Scale").clicked() {
|
||||
let _ = app.run(cmd, json!({"follow_main": !follow_main}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Adds one text menu value and dispatches its command when selected.
|
||||
fn menu_value(ui: &mut Ui, app: &mut SoundApp, cmd: &str, selected: bool, label: &str, value: serde_json::Value) {
|
||||
if ui.selectable_label(selected, label).clicked() {
|
||||
let _ = app.run(cmd, json!({"value": value}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds one musical value with its duration symbol.
|
||||
fn menu_note_value(ui: &mut Ui, app: &mut SoundApp, cmd: &str, selected: bool, note: NoteValue, value: serde_json::Value) {
|
||||
ui.horizontal(|ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());
|
||||
draw_note_value_icon(ui.painter(), rect, note, false, false, ui.visuals().text_color());
|
||||
menu_value(ui, app, cmd, selected, note.label(), value);
|
||||
});
|
||||
}
|
||||
|
||||
/// Adds a dotted or triplet modifier with its compact symbol.
|
||||
fn menu_modifier(ui: &mut Ui, app: &mut SoundApp, cmd: &str, selected: bool, label: &str, symbol: &str, value: serde_json::Value) {
|
||||
ui.horizontal(|ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());
|
||||
ui.painter().text(rect.center(), Align2::CENTER_CENTER, symbol, regular(11.0), ui.visuals().text_color());
|
||||
menu_value(ui, app, cmd, selected, label, value);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -390,8 +594,7 @@ fn transport(app: &mut SoundApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Count-off, meter and tempo readouts; the tempo value is editable in place for the tempo event at or before the
|
||||
/// playhead.
|
||||
/// Count-off, meter and tempo readouts; the tempo value edits the event at or before the playhead.
|
||||
fn tempo_meter(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let t = Tokens::current();
|
||||
let (bpm, meter, countoff, click, bars) = {
|
||||
@@ -453,6 +656,7 @@ fn tempo_value(app: &mut SoundApp, ui: &mut Ui, right: f32, y: f32, bpm: f64) {
|
||||
resp.on_hover_text("Drag to change the tempo (Shift: fine steps), or click to type it");
|
||||
}
|
||||
|
||||
/// Draws the compact stereo main-output meter.
|
||||
fn output_meter(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(26.0, 64.0), Sense::hover());
|
||||
let m = app.main_meter;
|
||||
@@ -466,6 +670,114 @@ fn output_meter(app: &mut SoundApp, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Services;
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
|
||||
/// Builds a compact Grid/Nudge toolbar test harness.
|
||||
fn harness() -> Harness<'static, SoundApp> {
|
||||
let app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
let mut harness = Harness::builder().with_size(vec2(700.0, 700.0)).build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
let edit = &app.engine.session().edit;
|
||||
let (grid, grid_follow, clips, nudge, nudge_follow) =
|
||||
(edit.grid, edit.grid_follow_main, edit.grid_clips_markers, edit.nudge, edit.nudge_follow_main);
|
||||
let grid_anchor = ui.button("Grid menu");
|
||||
value_menu(app, &grid_anchor, "view.grid", grid, grid_follow, clips, true);
|
||||
let nudge_anchor = ui.button("Nudge menu");
|
||||
value_menu(app, &nudge_anchor, "view.nudge", nudge, nudge_follow, false, false);
|
||||
},
|
||||
app,
|
||||
);
|
||||
harness.run_steps(3);
|
||||
harness
|
||||
}
|
||||
|
||||
/// Opens a toolbar value menu and lets the popup settle.
|
||||
fn open(harness: &mut Harness<SoundApp>, label: &str) {
|
||||
harness.get_by_label(label).click();
|
||||
harness.run_steps(3);
|
||||
}
|
||||
|
||||
/// Compact values use their corresponding counter formats and symbols.
|
||||
#[test]
|
||||
fn compact_grid_values_use_their_counter_formats() {
|
||||
let session = Session::default();
|
||||
let note = |value, dotted, triplet| GridValue::Note { value, dotted, triplet };
|
||||
assert_eq!(compact_grid_label(&session, note(NoteValue::Quarter, false, false)), "0|1|000");
|
||||
assert_eq!(compact_grid_label(&session, note(NoteValue::Eighth, false, true)), "0|0|320");
|
||||
assert_eq!(compact_grid_label(&session, GridValue::Seconds(0.001)), "0:00.001");
|
||||
assert_eq!(compact_grid_label(&session, GridValue::Timecode(TimecodeValue::Second)), "00:00:01:00.00");
|
||||
assert_eq!(compact_grid_label(&session, GridValue::Timecode(TimecodeValue::QuarterFrame)), "00:00:00:00.25");
|
||||
assert_eq!(compact_grid_label(&session, GridValue::FeetFrames(FeetFramesValue::Foot)), "1+00");
|
||||
assert_eq!(compact_grid_label(&session, GridValue::Samples(10_000)), "10000");
|
||||
}
|
||||
|
||||
/// The Grid menu exposes every scale and retains its numeric value in Clips/Markers mode.
|
||||
#[test]
|
||||
fn grid_menu_exposes_each_scale_and_keeps_the_increment_in_clips_markers_mode() {
|
||||
let mut harness = harness();
|
||||
open(&mut harness, "Grid menu");
|
||||
for label in ["Bars|Beats", "Min:Secs", "Timecode", "Feet+Frames", "Samples", "Clips/Markers", "Follow Main Time Scale"] {
|
||||
let _ = harness.get_by_label(label);
|
||||
}
|
||||
for label in ["1 bar", "Whole note", "1/2 note", "1/4 note", "1/8 note", "1/16 note", "1/32 note", "1/64 note", "Dotted", "Triplet"] {
|
||||
let _ = harness.get_by_label(label);
|
||||
}
|
||||
|
||||
harness.get_by_label("Timecode").click();
|
||||
harness.run_steps(3);
|
||||
open(&mut harness, "Grid menu");
|
||||
for label in ["1 second", "5 frames", "1 frame", "1/2 frame", "1/4 frame", "1 subframe"] {
|
||||
let _ = harness.get_by_label(label);
|
||||
}
|
||||
harness.get_by_label("1/4 frame").click();
|
||||
harness.run_steps(3);
|
||||
open(&mut harness, "Grid menu");
|
||||
harness.get_by_label("Clips/Markers").click();
|
||||
harness.run_steps(3);
|
||||
let edit = &harness.state().engine.session().edit;
|
||||
assert_eq!(edit.grid, GridValue::Timecode(TimecodeValue::QuarterFrame));
|
||||
assert!(edit.grid_clips_markers);
|
||||
open(&mut harness, "Grid menu");
|
||||
harness.get_by_label("1/2 frame").click();
|
||||
harness.run_steps(3);
|
||||
let edit = &harness.state().engine.session().edit;
|
||||
assert_eq!(edit.grid, GridValue::Timecode(TimecodeValue::HalfFrame));
|
||||
assert!(!edit.grid_clips_markers);
|
||||
}
|
||||
|
||||
/// Selecting another musical increment preserves the active dotted or triplet modifier.
|
||||
#[test]
|
||||
fn note_menu_keeps_the_current_modifier_when_changing_value() {
|
||||
let mut harness = harness();
|
||||
harness.state_mut().run("view.grid", json!({"value": "1/8t"})).unwrap();
|
||||
harness.run_steps(3);
|
||||
open(&mut harness, "Grid menu");
|
||||
harness.get_by_label("1/16 note").click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().engine.session().edit.grid, GridValue::Note { value: NoteValue::Sixteenth, dotted: false, triplet: true });
|
||||
open(&mut harness, "Grid menu");
|
||||
harness.get_by_label("Whole note").click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().engine.session().edit.grid, GridValue::Note { value: NoteValue::Whole, dotted: false, triplet: true });
|
||||
}
|
||||
|
||||
/// The Nudge menu exposes every numeric scale without the Grid-only Clips/Markers mode.
|
||||
#[test]
|
||||
fn nudge_menu_has_every_numeric_scale_but_no_clips_markers_mode() {
|
||||
let mut harness = harness();
|
||||
open(&mut harness, "Nudge menu");
|
||||
for label in ["Bars|Beats", "Min:Secs", "Timecode", "Feet+Frames", "Samples", "Follow Main Time Scale"] {
|
||||
let _ = harness.get_by_label(label);
|
||||
}
|
||||
assert_eq!(harness.query_all_by_label("Clips/Markers").count(), 0);
|
||||
harness.get_by_label("Samples").click();
|
||||
harness.run_steps(3);
|
||||
open(&mut harness, "Nudge menu");
|
||||
for label in ["10000 samples", "1000 samples", "100 samples", "10 samples", "2 samples", "1 sample"] {
|
||||
let _ = harness.get_by_label(label);
|
||||
}
|
||||
}
|
||||
|
||||
/// #1262: the two link toggles differ only by their icon, so each option toggle needs its own.
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use egui::{Color32, FullOutput, Pos2, RawInput, Rect, Shape, pos2, vec2};
|
||||
use serde_json::json;
|
||||
use soundcraft_model::{ChannelFormat, Clip, TrackId, TrackKind};
|
||||
use soundcraft_ui_egui::theme::Tokens;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, edit_window};
|
||||
|
||||
@@ -22,6 +23,7 @@ fn near(a: [i32; 3], b: Color32) -> bool {
|
||||
a.iter().zip([b.r(), b.g(), b.b()]).all(|(x, y)| (x - i32::from(y)).abs() <= 6)
|
||||
}
|
||||
|
||||
/// Numeric Grid lines retain their stacking order over clips in both themes.
|
||||
#[test]
|
||||
fn grid_lines_are_drawn_over_clips_while_shown() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
@@ -68,3 +70,94 @@ fn grid_lines_are_drawn_over_clips_while_shown() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clips/Markers grid lines reach the timeline at memory-location boundaries.
|
||||
#[test]
|
||||
fn clips_markers_grid_draws_a_line_at_a_memory_location() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
let kick = app.engine.session().track_by_name("Kick").unwrap();
|
||||
let clip = &kick.clips()[0];
|
||||
let marker = clip.start + clip.length / 3;
|
||||
app.run("markers.add", json!({"at": marker, "name": "Grid target"})).unwrap();
|
||||
app.run("view.grid", json!({"format": "clips_markers", "lines": true})).unwrap();
|
||||
|
||||
frame(&ctx, &mut app);
|
||||
let out = frame(&ctx, &mut app);
|
||||
let session = app.engine.session();
|
||||
let kick = session.track_by_name("Kick").unwrap();
|
||||
let [x0, y0, x1, y1] = app.edit_layout.timeline;
|
||||
let timeline = Rect::from_min_max(pos2(x0, y0), pos2(x1, y1));
|
||||
let row = app.edit_layout.rows.iter().find(|(id, _)| *id == kick.id.0).unwrap().1;
|
||||
let lane = Rect::from_min_max(pos2(timeline.min.x, row[1]), pos2(timeline.max.x, row[1] + kick.height.points()));
|
||||
let expected_x = edit_window::x_of(session, timeline, marker);
|
||||
|
||||
assert!(out.shapes.iter().any(|shape| {
|
||||
matches!(
|
||||
&shape.shape,
|
||||
Shape::LineSegment { points: [a, b], .. }
|
||||
if a.x == expected_x && b.x == expected_x && a.y == lane.min.y && b.y == lane.max.y
|
||||
)
|
||||
}));
|
||||
}
|
||||
|
||||
/// Whether a vertical grid line spans the main lane of a visible track at the requested sample.
|
||||
fn line_on_track(out: &FullOutput, app: &SoundApp, track: TrackId, at: i64) -> bool {
|
||||
let s = app.engine.session();
|
||||
let [x0, y0, x1, y1] = app.edit_layout.timeline;
|
||||
let timeline = Rect::from_min_max(pos2(x0, y0), pos2(x1, y1));
|
||||
let row = app.edit_layout.rows.iter().find(|(id, _)| *id == track.0).unwrap().1;
|
||||
let bottom = row[1] + s.track(track).unwrap().height.points();
|
||||
let x = edit_window::x_of(s, timeline, at);
|
||||
out.shapes.iter().any(|shape| {
|
||||
matches!(&shape.shape, Shape::LineSegment { points: [a, b], .. }
|
||||
if a.x == x && b.x == x && a.y == row[1] && b.y == bottom)
|
||||
})
|
||||
}
|
||||
|
||||
/// Shared frame lines reflect visible children, edited boundaries, scrolling and zoom on every lane.
|
||||
#[test]
|
||||
fn clips_markers_lines_refresh_across_lanes_and_hidden_open_folders() {
|
||||
let mut engine = soundcraft_engine::Engine::default();
|
||||
let s = engine.session_mut();
|
||||
let folder = s.add_track(TrackKind::Folder, ChannelFormat::Stereo, None);
|
||||
let child = s.add_track(TrackKind::Midi, ChannelFormat::Mono, None);
|
||||
let other = s.add_track(TrackKind::Midi, ChannelFormat::Mono, None);
|
||||
s.track_mut(folder).unwrap().hidden = true;
|
||||
s.track_mut(child).unwrap().folder = Some(folder);
|
||||
let clip = Clip::midi(s.new_clip_id(), "Visible", 1_200, 5_000, Default::default());
|
||||
let clip_id = clip.id;
|
||||
s.track_mut(child).unwrap().playlist_mut().unwrap().clips.push(clip);
|
||||
s.add_marker("Boundary", soundcraft_model::MarkerKind::Marker, 9_000, 9_000);
|
||||
s.edit.grid_clips_markers = true;
|
||||
s.edit.grid_lines = true;
|
||||
let mut app = SoundApp::new(engine, None, Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
|
||||
for (start, marker, scroll, zoom) in [(1_200, 9_000, 0, 20.0), (3_000, 11_000, 0, 20.0), (3_000, 11_000, 1_000, 40.0)] {
|
||||
let s = app.engine.session_mut();
|
||||
s.find_clip_mut(clip_id).unwrap().start = start;
|
||||
s.markers[0].start = marker;
|
||||
s.markers[0].end = marker;
|
||||
s.edit.zoom.scroll = scroll;
|
||||
s.edit.zoom.samples_per_px = zoom;
|
||||
frame(&ctx, &mut app);
|
||||
let out = frame(&ctx, &mut app);
|
||||
assert!(!app.edit_layout.rows.iter().any(|(id, _)| *id == folder.0));
|
||||
for track in [child, other] {
|
||||
assert!(line_on_track(&out, &app, track, start));
|
||||
assert!(line_on_track(&out, &app, track, marker));
|
||||
if start != 1_200 {
|
||||
assert!(!line_on_track(&out, &app, track, 1_200));
|
||||
assert!(!line_on_track(&out, &app, track, 9_000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app.engine.session_mut().track_mut(folder).unwrap().folder_open = false;
|
||||
frame(&ctx, &mut app);
|
||||
let out = frame(&ctx, &mut app);
|
||||
assert!(!app.edit_layout.rows.iter().any(|(id, _)| *id == child.0));
|
||||
assert!(!line_on_track(&out, &app, other, 3_000));
|
||||
assert!(line_on_track(&out, &app, other, 11_000));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use egui::{Event, Key, Modifiers, vec2};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use serde_json::json;
|
||||
use soundcraft_model::TrackId;
|
||||
use soundcraft_ui_egui::dialogs::Dialog;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, menus};
|
||||
|
||||
/// Selects the whole Kick track and opens Edit > Strip Silence from the menu.
|
||||
@@ -89,3 +90,58 @@ fn strip_silence_strip_removes_the_silence() {
|
||||
assert_eq!(strip, stripped(track));
|
||||
assert!(covered(&strip) < covered(&before));
|
||||
}
|
||||
|
||||
/// Values other than the ones Strip Silence first opens with.
|
||||
const CHANGED: [f64; 4] = [-30.0, 120.0, 12.0, 40.0];
|
||||
|
||||
/// Sets the open Strip Silence window's values, as dragging its sliders would.
|
||||
fn set_values(h: &mut Harness<'_, SoundApp>, values: [f64; 4]) {
|
||||
let Some(Dialog::StripSilence { threshold, min_ms, pre_ms, post_ms }) = &mut h.state_mut().dialogs.open else {
|
||||
panic!("Strip Silence is not open")
|
||||
};
|
||||
[*threshold, *min_ms, *pre_ms, *post_ms] = values;
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// Opens Edit > Strip Silence again from the menu and returns the values it shows.
|
||||
fn reopen(h: &mut Harness<'_, SoundApp>) -> [f64; 4] {
|
||||
assert_eq!(h.state().dialogs.open_name(), None, "Strip Silence is closed before it opens again");
|
||||
menus::invoke_menu(h.state_mut(), "edit.strip_silence", "Edit > Strip Silence");
|
||||
h.run_steps(2);
|
||||
let Some(Dialog::StripSilence { threshold, min_ms, pre_ms, post_ms }) = h.state().dialogs.open.clone() else {
|
||||
panic!("Strip Silence did not open again")
|
||||
};
|
||||
[threshold, min_ms, pre_ms, post_ms]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_silence_opens_with_the_values_escape_closed_it_with() {
|
||||
let (mut h, _, _) = strip_silence_dialog();
|
||||
set_values(&mut h, CHANGED);
|
||||
h.event(Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(reopen(&mut h), CHANGED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_silence_opens_with_the_values_strip_used() {
|
||||
let (mut h, _, _) = strip_silence_dialog();
|
||||
set_values(&mut h, CHANGED);
|
||||
h.get_by_role_and_label(Role::Button, "Strip").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(reopen(&mut h), CHANGED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_silence_keeps_its_values_through_rename_and_cancel() {
|
||||
let (mut h, _, _) = strip_silence_dialog();
|
||||
set_values(&mut h, CHANGED);
|
||||
h.get_by_role_and_label(Role::Button, "Rename…").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().dialogs.open_name(), Some("strip_silence"), "Cancel in Rename goes back to Strip Silence");
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(reopen(&mut h), CHANGED);
|
||||
}
|
||||
|
||||
+135
-14
@@ -72,6 +72,22 @@ impl Dpb {
|
||||
self.entries.retain(|e| e.needed_for_output || e.mark != RefMark::Unused);
|
||||
}
|
||||
|
||||
/// Make room for a picture: output one (C.4.5.3), or, when none waits for output and
|
||||
/// references alone fill the DPB (marking that keeps more than it holds), drop the reference
|
||||
/// decoded longest ago. False when the DPB is empty.
|
||||
fn make_room(&mut self, out: &mut Vec<Output>) -> bool {
|
||||
if self.bump(out) {
|
||||
return true;
|
||||
}
|
||||
let Some(i) = self.entries.iter().enumerate().filter(|(_, e)| e.mark != RefMark::Unused).min_by_key(|(_, e)| e.frame.id).map(|(i, _)| i)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.entries[i].mark = RefMark::Unused;
|
||||
self.prune();
|
||||
true
|
||||
}
|
||||
|
||||
/// Output the picture with the smallest POC (C.4.5.3 "bumping"). Returns false if none waits.
|
||||
fn bump(&mut self, out: &mut Vec<Output>) -> bool {
|
||||
let Some(i) = self.entries.iter().enumerate().filter(|(_, e)| e.needed_for_output).min_by_key(|(_, e)| e.poc).map(|(i, _)| i) else {
|
||||
@@ -134,21 +150,29 @@ impl Dpb {
|
||||
poc_state: &mut dyn FnMut(u32),
|
||||
) {
|
||||
let mut unused = (prev_ref_frame_num + 1) % max_frame_num;
|
||||
// Only the last `max_num_ref_frames` missing frames can still be references when the gap
|
||||
// ends: the sliding window drops the earlier ones first, so building their pictures would
|
||||
// be work (up to 65 535 frame copies from one slice header) thrown straight away. They
|
||||
// advance the POC state only.
|
||||
let gap = (frame_num + max_frame_num - unused) % max_frame_num;
|
||||
let skip = gap.saturating_sub(u32::try_from(max_num_ref_frames.max(1)).unwrap_or(u32::MAX));
|
||||
let mut guard = 0;
|
||||
while unused != frame_num && guard < max_frame_num {
|
||||
self.sliding_window(unused, max_frame_num, max_num_ref_frames);
|
||||
let (frame, meta) = make_frame(unused);
|
||||
poc_state(unused);
|
||||
self.entries.push(DpbEntry {
|
||||
poc: frame.poc,
|
||||
frame,
|
||||
frame_num: unused,
|
||||
long_term_frame_idx: 0,
|
||||
mark: RefMark::Short,
|
||||
needed_for_output: false,
|
||||
non_existing: true,
|
||||
meta,
|
||||
});
|
||||
if guard >= skip {
|
||||
self.sliding_window(unused, max_frame_num, max_num_ref_frames);
|
||||
let (frame, meta) = make_frame(unused);
|
||||
self.entries.push(DpbEntry {
|
||||
poc: frame.poc,
|
||||
frame,
|
||||
frame_num: unused,
|
||||
long_term_frame_idx: 0,
|
||||
mark: RefMark::Short,
|
||||
needed_for_output: false,
|
||||
non_existing: true,
|
||||
meta,
|
||||
});
|
||||
}
|
||||
unused = (unused + 1) % max_frame_num;
|
||||
guard += 1;
|
||||
}
|
||||
@@ -277,6 +301,11 @@ impl Dpb {
|
||||
}
|
||||
}
|
||||
}
|
||||
3 | 6 if self.max_long_term_frame_idx.is_none_or(|max| m.long_term_frame_idx > max) => {
|
||||
// A long-term index outside what MMCO 4 (or the IDR) allowed (8.2.5.4.3): a
|
||||
// conforming stream never sends one, and honouring it would let distinct
|
||||
// indices retain references past the DPB's capacity.
|
||||
}
|
||||
3 => {
|
||||
let pn = i64::from(curr_pic_num) - (i64::from(m.difference_of_pic_nums_minus1) + 1);
|
||||
for e in &mut self.entries {
|
||||
@@ -384,13 +413,13 @@ impl Dpb {
|
||||
out.push(Output { frame, poc, meta });
|
||||
return;
|
||||
}
|
||||
if !self.bump(out) {
|
||||
if !self.make_room(out) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
while self.entries.len() >= self.capacity {
|
||||
if !self.bump(out) {
|
||||
if !self.make_room(out) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -429,6 +458,98 @@ mod tests {
|
||||
Mmco { op, difference_of_pic_nums_minus1: diff, long_term_pic_num: 0, long_term_frame_idx: 0, max_long_term_frame_idx_plus1: 0 }
|
||||
}
|
||||
|
||||
fn frame(id: u32) -> (FrameRef, Arc<OutputMeta>) {
|
||||
let meta = OutputMeta {
|
||||
pts: 0,
|
||||
key: false,
|
||||
crop: (0, 0, 0, 0),
|
||||
full_range: false,
|
||||
colour_primaries: 0,
|
||||
transfer_characteristics: 0,
|
||||
matrix_coefficients: 0,
|
||||
sar: (1, 1),
|
||||
draft: false,
|
||||
};
|
||||
(Arc::new(crate::h264::picture::Frame::new(id, 0, 1, 1)), Arc::new(meta))
|
||||
}
|
||||
|
||||
/// A P slice header of a reference picture, with nothing else set.
|
||||
fn reference_slice() -> SliceHeader {
|
||||
SliceHeader {
|
||||
nal_ref_idc: 1,
|
||||
nal_unit_type: 1,
|
||||
idr: false,
|
||||
first_mb_in_slice: 0,
|
||||
slice_type_raw: 0,
|
||||
slice_type: SliceType::P,
|
||||
pps_id: 0,
|
||||
colour_plane_id: 0,
|
||||
frame_num: 0,
|
||||
field_pic: false,
|
||||
bottom_field: false,
|
||||
idr_pic_id: 0,
|
||||
pic_order_cnt_lsb: 0,
|
||||
delta_pic_order_cnt_bottom: 0,
|
||||
delta_pic_order_cnt: [0; 2],
|
||||
redundant_pic_cnt: 0,
|
||||
direct_spatial_mv_pred: false,
|
||||
num_ref_idx_active: [1, 0],
|
||||
ref_pic_list_mod: [Vec::new(), Vec::new()],
|
||||
pred_weight_table: None,
|
||||
no_output_of_prior_pics: false,
|
||||
long_term_reference: false,
|
||||
adaptive_ref_pic_marking: false,
|
||||
mmcos: Vec::new(),
|
||||
cabac_init_idc: 0,
|
||||
slice_qp_delta: 0,
|
||||
sp_for_switch: false,
|
||||
slice_qs_delta: 0,
|
||||
disable_deblocking_filter_idc: 0,
|
||||
slice_alpha_c0_offset_div2: 0,
|
||||
slice_beta_offset_div2: 0,
|
||||
slice_group_change_cycle: 0,
|
||||
header_bits: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_num_gap_builds_only_the_frames_that_stay_references() {
|
||||
let mut dpb = Dpb::new();
|
||||
let (mut built, mut poc_updates) = (Vec::new(), 0u32);
|
||||
// frame_num 0 was the last reference; the next slice says 60_000: 59 999 missing frames.
|
||||
dpb.fill_frame_num_gap(0, 60_000, 1 << 16, 4, &mut |n| (built.push(n), frame(n)).1, &mut |_| poc_updates += 1);
|
||||
assert_eq!(poc_updates, 59_999, "every missing frame advances the POC state");
|
||||
assert_eq!(built, vec![59_996, 59_997, 59_998, 59_999], "only the ones the sliding window would keep are built");
|
||||
assert_eq!(dpb.entries.iter().map(|e| e.frame_num).collect::<Vec<_>>(), built);
|
||||
// A gap shorter than the window builds every frame, as before.
|
||||
let mut dpb = Dpb::new();
|
||||
let mut built = Vec::new();
|
||||
dpb.fill_frame_num_gap(7, 10, 16, 4, &mut |n| (built.push(n), frame(n)).1, &mut |_| {});
|
||||
assert_eq!(built, vec![8, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_term_marking_cannot_grow_the_dpb_past_its_capacity() {
|
||||
let mut dpb = Dpb::new();
|
||||
dpb.capacity = 4;
|
||||
let mut out = Vec::new();
|
||||
let mut sh = SliceHeader { adaptive_ref_pic_marking: true, ..reference_slice() };
|
||||
// Each picture takes a distinct long-term index, after MMCO 4 allowed 1000 of them.
|
||||
for n in 0..40u32 {
|
||||
sh.frame_num = n;
|
||||
sh.mmcos = vec![Mmco { op: 4, max_long_term_frame_idx_plus1: 1000, ..mmco(0, 0) }, Mmco { op: 6, long_term_frame_idx: n, ..mmco(0, 0) }];
|
||||
let (f, meta) = frame(n);
|
||||
dpb.store_picture(&sh, f, n as i32, 1 << 16, 16, meta, &mut out);
|
||||
assert!(dpb.entries.len() <= 4, "{} entries after picture {n}", dpb.entries.len());
|
||||
}
|
||||
// An index past what MMCO 4 allowed is ignored: the picture is a short-term reference.
|
||||
sh.frame_num = 40;
|
||||
sh.mmcos = vec![Mmco { op: 6, long_term_frame_idx: 5000, ..mmco(0, 0) }];
|
||||
let (f, meta) = frame(40);
|
||||
dpb.store_picture(&sh, f, 40, 1 << 16, 16, meta, &mut out);
|
||||
assert_eq!(dpb.entries.iter().find(|e| e.frame_num == 40).map(|e| e.mark), Some(RefMark::Short));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mmco_huge_difference_does_not_panic() {
|
||||
for op in [1, 3] {
|
||||
|
||||
@@ -397,6 +397,10 @@ impl Sps {
|
||||
let pic_height_in_map_units = plus(r.read_ue()?, 1, "picture too large")?;
|
||||
ensure!(pic_width_in_mbs <= 1024 && pic_height_in_map_units <= 1024, "picture too large");
|
||||
let frame_mbs_only = r.read_flag()?;
|
||||
// Picture state is allocated from these before any macroblock is read: the movie's pixel
|
||||
// budget applies here too, so a 16 384-square SPS can't claim its planes.
|
||||
let coded_mbs = u64::from(pic_width_in_mbs) * u64::from(pic_height_in_map_units) * if frame_mbs_only { 1 } else { 2 };
|
||||
ensure!(coded_mbs * 256 <= crate::movie::MAX_PIXELS, "picture too large");
|
||||
let mb_adaptive_frame_field = if !frame_mbs_only { r.read_flag()? } else { false };
|
||||
let direct_8x8_inference = r.read_flag()?;
|
||||
let frame_crop = if r.read_flag()? { Some((r.read_ue()?, r.read_ue()?, r.read_ue()?, r.read_ue()?)) } else { None };
|
||||
@@ -699,6 +703,37 @@ mod tests {
|
||||
assert_eq!(l, [10; 16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_sps_past_the_pixel_budget_is_refused_before_allocation() {
|
||||
// As `parse_minimal_baseline_sps`, with `mbs` × `mbs` macroblocks.
|
||||
let sps = |mbs: u32, frame_mbs_only: bool| {
|
||||
let mut w = BitWriter::new();
|
||||
w.write_bits(66, 8);
|
||||
w.write_bits(0xC0, 8);
|
||||
w.write_bits(30, 8);
|
||||
w.write_ue(0);
|
||||
w.write_ue(0);
|
||||
w.write_ue(2);
|
||||
w.write_ue(1);
|
||||
w.write_bit(false);
|
||||
w.write_ue(mbs - 1);
|
||||
w.write_ue(mbs - 1);
|
||||
w.write_bit(frame_mbs_only);
|
||||
if !frame_mbs_only {
|
||||
w.write_bit(false); // mb_adaptive_frame_field
|
||||
}
|
||||
w.write_bit(true);
|
||||
w.write_bit(false);
|
||||
w.write_bit(false);
|
||||
w.rbsp_trailing();
|
||||
Sps::parse(&w.finish())
|
||||
};
|
||||
assert!(sps(512, true).is_ok(), "8192 × 8192 is the budget");
|
||||
assert!(sps(513, true).is_err(), "one macroblock column more is past it");
|
||||
assert!(sps(512, false).is_err(), "field pictures double the map units");
|
||||
assert!(sps(362, false).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_minimal_baseline_sps() {
|
||||
// profile 66, level 30, sps_id 0, log2_max_frame_num_minus4 0, poc type 2, 1 ref, 11x9 MBs.
|
||||
|
||||
+10
-7
@@ -14,7 +14,7 @@ flags, values and defaults. This page does not repeat them.
|
||||
| `convert` | Converts an audio file: resample, change the bit depth, normalize |
|
||||
| `run` | Runs engine commands on a new, demo or saved session; can bounce, save and inspect |
|
||||
| `script` | Runs a file of engine commands, one `ID JSON` per line |
|
||||
| `commands` | Lists the engine commands |
|
||||
| `commands` | Lists the engine commands; with `--json`, each one's details as `describe` prints them |
|
||||
| `describe` | Prints one engine command's details as JSON |
|
||||
| `app` | Calls a running app's control channel (see [the control protocol](control-protocol.md)) |
|
||||
| `mcp` | Serves MCP on stdin and stdout (see [the MCP guide](mcp.md)) |
|
||||
@@ -29,16 +29,19 @@ soundcraft-cli convert in.wav out.flac --bit-depth 16 --rate 44100
|
||||
soundcraft-cli run --demo --cmd 'mix.volume={"track":"Kick","db":-6}' --bounce mix.wav
|
||||
soundcraft-cli script steps.txt --demo --keep-going --save out.scraft
|
||||
soundcraft-cli commands bounce
|
||||
soundcraft-cli commands --json --compact
|
||||
soundcraft-cli describe file.bounce_mix
|
||||
```
|
||||
|
||||
## Output and exit codes
|
||||
|
||||
Results go to standard output, as JSON where a program is meant to read them. `info` (on an audio
|
||||
file), `describe`, `app` and the `--inspect` output of `run` and `script` pretty-print it; `--compact`
|
||||
prints the same JSON on one line. The result lines of `run` and `script` (`ID: JSON`) and the
|
||||
`--bounce` and `--save` results are always one line each. `commands`, `plugins`, `parity` and the
|
||||
`.scraft` summary of `info` are text. Errors go to standard error as `error: <message>`, and so do the warnings and errors SoundCraft and the plugin hosts log (`warning: <message>`, `error: <message>`), such as a plugin that fails to load. `mcp` writes only the protocol
|
||||
file), `describe`, `commands --json`, `app` and the `--inspect` output of `run` and `script`
|
||||
pretty-print it; `--compact` prints the same JSON on one line. The result lines of `run` and
|
||||
`script` (`ID: JSON`) and the `--bounce` and `--save` results are always one line each. `commands`
|
||||
(without `--json`), `plugins`, `parity` and the `.scraft` summary of `info` are text. The
|
||||
`enabled` and `disabled_reason` fields of `describe` and `commands --json` are worked out against
|
||||
an empty session, not a session you have open. Errors go to standard error as `error: <message>`, and so do the warnings and errors SoundCraft and the plugin hosts log (`warning: <message>`, `error: <message>`), such as a plugin that fails to load. `mcp` writes only the protocol
|
||||
to standard output.
|
||||
|
||||
| Exit code | Meaning |
|
||||
@@ -138,8 +141,8 @@ output replacing an input without `--in-place`, and the ast-grep rules in `lint/
|
||||
|
||||
Rules not followed yet:
|
||||
|
||||
- **JSON flag (rule 1.3).** `commands`, `plugins`, `parity` and the `info` summary of a `.scraft`
|
||||
session print text and have no `--json` flag. Whether such listings need one is an open question
|
||||
- **JSON flag (rule 1.3).** `plugins`, `parity` and the `info` summary of a `.scraft` session
|
||||
print text and have no `--json` flag (`commands` has one). Whether such listings need one is an open question
|
||||
in the RFC itself.
|
||||
- **`string-error` rule (section 3).** Its ast-grep rule is on for the CLI code and the shared flags,
|
||||
not yet for the rest of the workspace.
|
||||
|
||||
@@ -72,6 +72,8 @@ Legend: ✅ matches · 🟡 partial · ❌ missing.
|
||||
|---|---|---|
|
||||
| 2026-10-25 | minor | Zoom Toggle row: Alt+Shift+E and Alt-click cancel Zoom Toggle and keep the view. Readiness estimate unchanged |
|
||||
| 2026-10-25 | minor | Edit and Mix windows: Tracks and Groups and Clips in full-height dock columns. Readiness estimate unchanged |
|
||||
| 2026-10-20 | minor | Preferences uses one fixed non-scrolling size with compact stacked choices, removes the duplicate meter-type list, and command-backs visual-effects reduction and undo depth alongside the UI theme |
|
||||
| 2026-10-19 | minor | Preferences opens from Setup with nine searchable pages, compact grouped controls, staged apply/cancel, platform tab shortcuts and disabled placeholders for unavailable settings |
|
||||
| 2026-10-16 | minor | Track name menu: Scroll Into View brings the track to the top of the Edit window and the left of the Mix. Readiness estimate unchanged |
|
||||
| 2026-10-13 | minor | A plugin opens when it's inserted (#486) |
|
||||
| 2026-10-13 | minor | Drag across checkboxes (#399) |
|
||||
|
||||
@@ -197,8 +197,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_failed_update_restores_the_manifest() {
|
||||
let root = std::env::temp_dir().join(format!("xtask-version-restore-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
// Created exclusively: a folder already there (planted, or left by a failed run) would be
|
||||
// someone else's, and a link inside it could redirect the writes below.
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
|
||||
let root = std::env::temp_dir().join(format!("xtask-version-restore-{}-{nanos}", std::process::id()));
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let path = root.join("Cargo.toml");
|
||||
std::fs::write(&path, MANIFEST).unwrap();
|
||||
let err = set(&root, &path, MANIFEST, "2.0.0", || Err("cargo update failed".into())).unwrap_err();
|
||||
|
||||
Reference in New Issue
Block a user