mirror of
https://github.com/storytold/soundcraft.git
synced 2026-11-18 11:52:24 -06:00
Compare commits
65
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56d5c38547 | ||
|
|
7289de8e07 | ||
|
|
4e50956769 | ||
|
|
42d7fa390b | ||
|
|
62ace3e0fe | ||
|
|
b5392da2a2 | ||
|
|
0bf8fe27b9 | ||
|
|
d570045b63 | ||
|
|
c27ccac979 | ||
|
|
248f0e4e25 | ||
|
|
dc21f5ee10 | ||
|
|
0c85e784d2 | ||
|
|
8ee63dc695 | ||
|
|
b47a58653c | ||
|
|
19acf6f21a | ||
|
|
16bd7327f3 | ||
|
|
9676d492db | ||
|
|
63dfe72b1f | ||
|
|
0500172d2b | ||
|
|
648ed9db9a | ||
|
|
d0479e609c | ||
|
|
fc4dddd7c7 | ||
|
|
5976545fe1 | ||
|
|
559c2b9fc2 | ||
|
|
9fa3754a13 | ||
|
|
aba1cdcdfc | ||
|
|
4898ff03ee | ||
|
|
1a09c16295 | ||
|
|
498849745a | ||
|
|
4bdda5ffad | ||
|
|
5d1fa9a69d | ||
|
|
244dcd7767 | ||
|
|
cd743a8d59 | ||
|
|
dd14d15f55 | ||
|
|
33917ea79a | ||
|
|
8a5647ab49 | ||
|
|
8ddda478fd | ||
|
|
20c4038cb3 | ||
|
|
194f63b4b6 | ||
|
|
35cc20c457 | ||
|
|
ae5ec2ee54 | ||
|
|
7236035284 | ||
|
|
3cc12a0758 | ||
|
|
bf6f1166d1 | ||
|
|
d4468ff935 | ||
|
|
3e6714d59f | ||
|
|
dd7f3188aa | ||
|
|
9e37794db7 | ||
|
|
976ea150b7 | ||
|
|
9506ad6039 | ||
|
|
51c3159ff1 | ||
|
|
a743f5b4ef | ||
|
|
3158855080 | ||
|
|
d842ee7421 | ||
|
|
b2f8978387 | ||
|
|
dafcc16c32 | ||
|
|
6d7fec682b | ||
|
|
705697178c | ||
|
|
bb988dc7ff | ||
|
|
2a45435254 | ||
|
|
cca413bd32 | ||
|
|
60fbbcb4e5 | ||
|
|
c3f51a6030 | ||
|
|
d06bd91ff6 | ||
|
|
d3331784ee |
@@ -109,9 +109,16 @@ Parity is measured, not guessed: `crates/engine/catalog/menus.txt` lists the inc
|
||||
- Drive it: JSON lines over TCP, e.g. `{"id":1,"method":"engine.execute","params":{"command":"track.new","params":{"count":2,"format":"stereo"}}}`, then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`.
|
||||
- Offscreen UI render (no window, no focus stealing): `cargo run -p soundcraft-ui-egui --example ui_shot -- out.png [script.jsonl]`.
|
||||
- Headless: `soundcraft-cli run --demo --cmd 'mix.volume={"track":"Kick","db":-6}' --bounce out.wav`; MCP: `soundcraft-cli mcp [--connect PORT]`.
|
||||
- **For UI work, look at the result** (render, read the PNG) and compare with `plan/protools/screenshots/`.
|
||||
- **Language / localization:** the interface is English by default; Brazilian Portuguese
|
||||
(`pt-BR`) is selected under `Setup › Appearance › Language` (or the `ui.language` command with
|
||||
`{"language":"pt-BR"}`). The pt-BR catalog is complete for every fixed UI string — tests cover
|
||||
placeholder parity, unique keys and source coverage, and the `cargo test` suite passes.
|
||||
- Commands: build `cargo build -p soundcraft --bin soundcraft`; test
|
||||
`cargo test -p soundcraft --bin soundcraft`; run `DISPLAY=:0 ./target/debug/soundcraft`. The
|
||||
`cargo xtask ci` gate runs formatting, clippy, tests, assets, layering and the WebAssembly build.
|
||||
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write
|
||||
manifests atomically; delete your target dir when done (disk).
|
||||
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
|
||||
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically; delete your target dir when done (disk).
|
||||
|
||||
## Quality gates (before every commit)
|
||||
`cargo xtask ci` = fmt check, `clippy --workspace --all-targets -D warnings`, tests, assets, layers, wasm check. Commit after each arc of work that builds; one topic per commit.
|
||||
@@ -143,3 +150,7 @@ Push to the `release` branch to build signed installers for macOS (universal DMG
|
||||
- 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.
|
||||
|
||||
## Shared Craft libraries
|
||||
|
||||
Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.
|
||||
|
||||
Generated
+428
-29
@@ -138,6 +138,24 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aligned"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"
|
||||
dependencies = [
|
||||
"as-slice",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aligned-vec"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
|
||||
dependencies = [
|
||||
"equator",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
@@ -256,6 +274,12 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -277,6 +301,17 @@ dependencies = [
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arg_enum_proc_macro"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayref"
|
||||
version = "0.3.9"
|
||||
@@ -295,6 +330,15 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
|
||||
|
||||
[[package]]
|
||||
name = "as-slice"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ash"
|
||||
version = "0.38.0+1.3.281"
|
||||
@@ -497,6 +541,40 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "av-scenechange"
|
||||
version = "0.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
|
||||
dependencies = [
|
||||
"aligned",
|
||||
"anyhow",
|
||||
"arg_enum_proc_macro",
|
||||
"arrayvec",
|
||||
"log",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
"pastey",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
"v_frame",
|
||||
"y4m",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "av1-grain"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arrayvec",
|
||||
"log",
|
||||
"nom 8.0.0",
|
||||
"num-rational",
|
||||
"v_frame",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
@@ -569,6 +647,15 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "bitstream-io"
|
||||
version = "4.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f"
|
||||
dependencies = [
|
||||
"no_std_io2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -633,6 +720,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "built"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -771,7 +864,7 @@ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1066,13 +1159,18 @@ name = "craft-audio"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
|
||||
dependencies = [
|
||||
"craft-media",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c)",
|
||||
"log",
|
||||
"serde",
|
||||
"symphonia",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
@@ -1106,6 +1204,14 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ddbe78231b5b23273b3d191f04b1a38f4c0445b3#ddbe78231b5b23273b3d191f04b1a38f4c0445b3"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-media"
|
||||
version = "0.1.0"
|
||||
@@ -1115,6 +1221,11 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-media"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ddbe78231b5b23273b3d191f04b1a38f4c0445b3#ddbe78231b5b23273b3d191f04b1a38f4c0445b3"
|
||||
|
||||
[[package]]
|
||||
name = "craft-midi"
|
||||
version = "0.1.0"
|
||||
@@ -1124,6 +1235,24 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-score"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=3a1a627dc69c677d3a26c22b72e070242ee6b841#3a1a627dc69c677d3a26c22b72e070242ee6b841"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3a1a627dc69c677d3a26c22b72e070242ee6b841)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-scraft-format"
|
||||
version = "0.1.0"
|
||||
@@ -1198,13 +1327,34 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-video"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ddbe78231b5b23273b3d191f04b1a38f4c0445b3#ddbe78231b5b23273b3d191f04b1a38f4c0445b3"
|
||||
dependencies = [
|
||||
"craft-media",
|
||||
"craft-jpeg",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ddbe78231b5b23273b3d191f04b1a38f4c0445b3)",
|
||||
"rav1e",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=3a1a627dc69c677d3a26c22b72e070242ee6b841#3a1a627dc69c677d3a26c22b72e070242ee6b841"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
@@ -1548,6 +1698,20 @@ dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"core_detect",
|
||||
"multiversion_no_op",
|
||||
"rustversion",
|
||||
"scopeguard",
|
||||
"simdutf8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "endi"
|
||||
version = "1.1.1"
|
||||
@@ -1626,6 +1790,26 @@ name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
|
||||
dependencies = [
|
||||
"equator-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equator-macro"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
@@ -1943,7 +2127,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -2378,8 +2562,6 @@ dependencies = [
|
||||
"num-traits",
|
||||
"png",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2392,6 +2574,17 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "interpolate_name"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-docker"
|
||||
version = "0.2.0"
|
||||
@@ -2426,6 +2619,15 @@ dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.15.0"
|
||||
@@ -2581,6 +2783,16 @@ version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "libfuzzer-sys"
|
||||
version = "0.4.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.8.9"
|
||||
@@ -2673,6 +2885,16 @@ version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
|
||||
|
||||
[[package]]
|
||||
name = "maybe-rayon"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -2751,6 +2973,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
@@ -2819,6 +3047,12 @@ dependencies = [
|
||||
"jni-sys 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "new_debug_unreachable"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.31.3"
|
||||
@@ -2831,6 +3065,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "no_std_io2"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nohash-hasher"
|
||||
version = "0.2.0"
|
||||
@@ -2856,6 +3099,22 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "noop_proc_macro"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
@@ -2891,6 +3150,17 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -3382,6 +3652,18 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
|
||||
|
||||
[[package]]
|
||||
name = "peniko"
|
||||
version = "0.6.1"
|
||||
@@ -3607,6 +3889,15 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "presser"
|
||||
version = "0.3.1"
|
||||
@@ -3655,6 +3946,19 @@ name = "profiling"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
|
||||
dependencies = [
|
||||
"profiling-procmacros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "profiling-procmacros"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
@@ -3668,7 +3972,7 @@ dependencies = [
|
||||
"chacha20",
|
||||
"core_detect",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand 0.10.3",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
@@ -3733,6 +4037,16 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.3"
|
||||
@@ -3740,7 +4054,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3755,7 +4088,7 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3764,6 +4097,40 @@ version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
|
||||
|
||||
[[package]]
|
||||
name = "rav1e"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
|
||||
dependencies = [
|
||||
"aligned-vec",
|
||||
"arbitrary",
|
||||
"arg_enum_proc_macro",
|
||||
"arrayvec",
|
||||
"av-scenechange",
|
||||
"av1-grain",
|
||||
"bitstream-io",
|
||||
"built",
|
||||
"cfg-if",
|
||||
"interpolate_name",
|
||||
"itertools 0.14.0",
|
||||
"libc",
|
||||
"libfuzzer-sys",
|
||||
"log",
|
||||
"maybe-rayon",
|
||||
"new_debug_unreachable",
|
||||
"noop_proc_macro",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"paste",
|
||||
"profiling",
|
||||
"rand 0.9.5",
|
||||
"rand_chacha",
|
||||
"simd_helpers",
|
||||
"thiserror 2.0.21",
|
||||
"v_frame",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
@@ -4279,6 +4646,15 @@ dependencies = [
|
||||
"simdutf8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd_helpers"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
|
||||
dependencies = [
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simdutf8"
|
||||
version = "0.1.5"
|
||||
@@ -4396,7 +4772,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
@@ -4420,7 +4796,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-au-host"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
@@ -4430,7 +4806,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-automation"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"craft-audio",
|
||||
@@ -4443,20 +4819,22 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-clap-host"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"libc",
|
||||
"libloading 0.9.0",
|
||||
"log",
|
||||
"serde",
|
||||
"soundcraft-dsp",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-cli"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
@@ -4474,7 +4852,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-dsp"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -4485,11 +4863,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-engine"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-docpath",
|
||||
"craft-score",
|
||||
"craft-scraft-format",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -4510,7 +4890,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-midi"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-midi",
|
||||
"proptest",
|
||||
@@ -4518,7 +4898,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-mix"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"log",
|
||||
@@ -4534,14 +4914,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-model"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-scraft-format",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-playback"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"cpal",
|
||||
"craft-audio",
|
||||
@@ -4556,16 +4936,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-time"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-ui-egui"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-mime",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"egui",
|
||||
@@ -4593,11 +4974,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-video"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-media",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c)",
|
||||
"craft-video",
|
||||
"image",
|
||||
"proptest",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -4605,8 +4985,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-vst3-host"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"libloading 0.9.0",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
@@ -4617,11 +4998,12 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"vst3",
|
||||
"windows-sys 0.61.2",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-web"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"eframe",
|
||||
@@ -5347,6 +5729,17 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "v_frame"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
|
||||
dependencies = [
|
||||
"aligned-vec",
|
||||
"num-traits",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.2.0"
|
||||
@@ -6269,11 +6662,17 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "y4m"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.4"
|
||||
|
||||
+5
-2
@@ -4,13 +4,16 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.21.0"
|
||||
version = "0.20.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/soundcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "3a1a627dc69c677d3a26c22b72e070242ee6b841" }
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
|
||||
# internal
|
||||
soundcraft-time = { path = "crates/time" }
|
||||
soundcraft-midi = { path = "crates/midi" }
|
||||
@@ -53,7 +56,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
|
||||
# Video containers and bitstreams, shared with the other craft apps.
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c" }
|
||||
# H.264 and ProRes codecs shared with the other Craft apps.
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c", default-features = false, features = ["h264-decode", "prores"] }
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ddbe78231b5b23273b3d191f04b1a38f4c0445b3", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
|
||||
# Audio file formats, codecs and waveform overviews, shared with the other craft apps. It shares
|
||||
# types with craft-media, so both stay on one rev.
|
||||
# Standard MIDI Files and the note/controller model, shared with the other craft apps.
|
||||
|
||||
@@ -123,10 +123,11 @@ where things are.
|
||||
Trim passes recorded live from the faders; thin, glide, coalesce and convert to clip gain.
|
||||
- **Plugins:** 7-band and 1-band EQ, compressor/limiter, expander/gate, de-esser, maximizer,
|
||||
channel strip, room and plate reverbs, mod delay, auto pan, chorus, flanger, phaser, ring
|
||||
modulator, saturator, lo-fi, rectifier, subharmonic, pitch shifter, time shift, gain, trim,
|
||||
invert, DC removal, signal generator, dither, a subtractive synth, a drum synth and a sampler
|
||||
(plays any WAV, AIFF, FLAC, MP3 or OGG across the keyboard), all original. **CLAP plugins**
|
||||
load too. Any processor runs offline as AudioSuite, and user presets save per plugin.
|
||||
modulator, frequency shifter, saturator, lo-fi, rectifier, subharmonic, pitch shifter, time
|
||||
shift, gain, trim, invert, DC removal, signal generator, dither, a subtractive synth, a drum
|
||||
synth and a sampler (plays any WAV, AIFF, FLAC, MP3 or OGG across the keyboard), all original.
|
||||
**CLAP plugins** load too. Any processor runs offline as AudioSuite, and user presets save
|
||||
per plugin.
|
||||
- **MIDI:** instrument and MIDI tracks, a piano-roll MIDI editor with a velocity lane, an event
|
||||
list, a score view, step input, quantize, transpose, real-time properties, Standard MIDI Files,
|
||||
and Audio-to-MIDI from a sung or played melody.
|
||||
@@ -263,8 +264,18 @@ SoundCraft is **pre-alpha**: it covers 94 % of the incumbent's menu items (measu
|
||||
its features by presence, and is roughly 40 % of the way to replacing it for real work: record,
|
||||
edit, mix and bounce work end to end, but choosing an audio interface and buffer size,
|
||||
recording MIDI from a controller and session interchange (AAF/OMF) are still missing, and those
|
||||
are the alpha checklist. Translations are missing too. The status, the stage and our effort
|
||||
estimates are in [`ROADMAP.md`](ROADMAP.md); the full assessment is in
|
||||
are the alpha checklist.
|
||||
|
||||
**Translations:** the Brazilian Portuguese (`pt-BR`) catalog is **100 % complete** for every fixed
|
||||
UI string found in the current source — menus, dialogs and buttons, tooltips (including those
|
||||
localized inside buttons and toggles), accessibility names, the Edit-window status bar, the
|
||||
remove-session question, formatted messages, engine error templates and engine error text at display
|
||||
time. All these entries are covered by a test, placeholders match, keys are unique, and the
|
||||
`pt-BR` catalog is chosen automatically when `ui.language` is `pt-BR` (or "Portuguese (Brazil)")
|
||||
under `Setup › Appearance`. Engine errors keep their run-time values and a decimal comma in
|
||||
`pt-BR`. The remaining localization work is a native-speaker (human) review of wording plus CJK /
|
||||
Devanagari / Arabic font fallbacks and RTL layout — not new UI translation. The status, the stage
|
||||
and our effort estimates are in [`ROADMAP.md`](ROADMAP.md); the full assessment is in
|
||||
[`docs/target-app-parity.md`](docs/target-app-parity.md), the ranked list of what's missing in
|
||||
[`docs/gaps.md`](docs/gaps.md), and the menu-by-menu comparison in
|
||||
[`docs/parity-checklist.md`](docs/parity-checklist.md). Bug reports and wish lists are
|
||||
|
||||
+16
-5
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
|
||||
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-27 · **Change:** trivial (Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-09 · **Change:** trivial (Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
|
||||
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
|
||||
@@ -50,7 +50,7 @@ measures readiness and adds hardware, localization and field bug reports.
|
||||
| UI/UX fidelity | ~55 % | 60–100 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| File formats | ~40 % | 70–120 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Hardware (interfaces, MIDI, surfaces, sync) | ~12 % | 110–180 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization | ~12 % (1 of Pro Tools' 8 languages) | 70–110 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Localization | ~12 % (1 of Pro Tools' 8 languages; English and pt-BR fixed UI strings, no CJK/RTL font fallback or native review) | 70–110 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | ~35 % (unmeasured) | 40–70 | [hardware-parity.md](docs/hardware-parity.md#performance) |
|
||||
| Stability | ~45 % | 50–80 | [gaps.md](docs/gaps.md) |
|
||||
| Platforms | ~65 % (5 platforms built, macOS exercised) | 20–40 | [gaps.md](docs/gaps.md) |
|
||||
@@ -89,14 +89,14 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
|
||||
| Hindi | hi | none | 0 % |
|
||||
| Arabic | ar | none | 0 % |
|
||||
| French | fr | none (PR #143 open) | 0 % |
|
||||
| Portuguese | pt | none | 0 % |
|
||||
| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
|
||||
| Indonesian | id | none | 0 % |
|
||||
| Japanese | ja | none | 0 % |
|
||||
| German | de | none | 0 % |
|
||||
| Korean | ko | none | 0 % |
|
||||
| Vietnamese | vi | none | 0 % |
|
||||
|
||||
Other languages shipped: 0. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
Other languages shipped: 0 complete. Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -105,7 +105,7 @@ Ranked; the alpha gate, the alpha checklist and the beta plan are in [docs/roadm
|
||||
1. **Alpha blocker:** audio interfaces: device and buffer-size choice, duplex stream, ASIO; record to disk (G-01, G-06). 35–55 h.
|
||||
2. **Alpha blocker:** MIDI devices: record from keyboards, play instruments live, output (G-02). 20–35 h.
|
||||
3. **Alpha blocker:** AAF/OMF import and export (G-03). 50–90 h.
|
||||
4. macOS plugin entitlement (#153), then AU editors (G-05). 1 h for the entitlement (needed for the mix row), then 15–25 h.
|
||||
4. macOS plugin entitlement (#153), then AU editors and embedded CLAP editors on macOS (G-05). 1 h for the entitlement (needed for the mix row), then 10–15 h.
|
||||
5. Land the open bug-fix PRs and clear the correctness backlog (G-04). 15–25 h.
|
||||
6. PR CI running `cargo xtask ci` on three OSes (G-14). 5–10 h.
|
||||
7. Fidelity harness against Pro Tools (G-07). 20–30 h.
|
||||
@@ -122,6 +122,10 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-11-09:** A built-in Frequency Shifter (`freq_shifter`) moves every frequency in the signal by the same number of hertz, from 0.01 Hz to 5 kHz: up, down, both ways at once, or down on the left and up on the right of a stereo track. The unwanted sideband stays at least 100 dB down from 20 Hz to 20 Hz below Nyquist at 44.1 to 96 kHz. Feedback sends the output round again for a trail of further shifts, Mix blends in the dry signal, and every change glides without a click. No readiness percentage change.
|
||||
- **2026-11-08:** Command-click near an existing automation breakpoint keeps that point as the click target with every active tool, and existing fade and clip-gain controls retain their normal priority. Empty automation space shows a crosshair and an insertion hint while Command is held. The active tool's drag gestures stay unchanged. No readiness percentage change.
|
||||
- **2026-11-05:** Command-click in an automation lane adds a point at the clicked time and value with the current editing tool (#1394), using the existing Pencil mapping. Command-click preserves the existing selection and also works on the fallback volume lanes of Master, Aux and VCA tracks. Plain clicks and clip contents stay unchanged, and one Undo removes the new point. No readiness percentage change.
|
||||
- **2026-10-27 (plugin editors on Linux):** VST3 editors and embedded CLAP editors open in a SoundCraft X11 host window on Linux and the BSDs (XWayland on Wayland desktops), resized on request and closed from its title bar; the host run loop (VST3 `Linux::IRunLoop`, CLAP `timer-support` and `posix-fd-support`) lets X11 editors read their display connection and repaint. Verified with Graillon 3 and Surge XT Effects (JUCE) in both formats (#527). No readiness percentage change.
|
||||
- **2026-10-25:** Alt+Shift+E (`view.zoom_toggle_cancel`) and an Alt-click on the Zoom Toggle button cancel Zoom Toggle and keep the current view: the zoom, the scroll and the track heights stay as they are, and the button is no longer lit. The next Zoom Toggle zooms in from that view and goes back to it. No readiness percentage change.
|
||||
- **2026-10-25:** Tracks and Groups and the Clip List sit in dock columns that run the Edit window's full height at its left and right edges, with the MIDI Editor under the session view between them; Mix docks Tracks and Groups at its left edge. A panel dragged onto a dock group joins it as a tab, stacks above or below it, or makes a new column; one dragged to an empty window edge makes a dock there. A list with no saved place reopens in its dock, and makes the dock again when it is gone. Preferences and window configurations saved with the earlier split-frame layouts load with the new default layouts and keep their other settings. No readiness percentage change.
|
||||
- **2026-10-25:** Auto Pan moves the balance of a stereo track: the left channel's level falls as the position moves right and the right channel's as it moves left, at constant power, and each channel stays on its own side. At the center the track passes unchanged, so a wide or out-of-phase stereo image keeps its width, and the envelope follower follows the louder channel. No readiness percentage change.
|
||||
@@ -180,6 +184,11 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
|
||||
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
|
||||
| 2026-11-05 | trivial | Progress log: Command-click adds an undoable automation point (#1394); readiness estimates unchanged |
|
||||
| 2026-11-05 | trivial | Languages table: Brazilian Portuguese (pt-BR) near complete for fixed UI strings via PR #1346; needs native review. Estimates unchanged |
|
||||
| 2026-10-27 | trivial | VST3 and embedded CLAP editors on Linux/X11 (#527); G-05 estimate down to 10–15 h; readiness estimates unchanged |
|
||||
| 2026-10-25 | trivial | Progress log: Cancel Zoom Toggle; readiness estimates unchanged |
|
||||
| 2026-10-25 | trivial | Progress log: side panels in dock columns; readiness estimates unchanged |
|
||||
| 2026-10-25 | trivial | Progress log: Auto Pan stereo balance; readiness estimates unchanged |
|
||||
@@ -203,6 +212,8 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
| 2026-10-14 | trivial | Progress log: oversized MCP batches rejected before execution (#460) |
|
||||
| 2026-10-13 | trivial | Progress log: empty WAV data chunk followed by metadata (#466) |
|
||||
| 2026-10-13 | trivial | Progress log: sampler ping-pong phase for wide steps (#463) |
|
||||
| 2026-10-13 | trivial | Progress log: Delete key clears the selection (#404) |
|
||||
| 2026-10-13 | The Delete and Backspace keys clear the edit selection in the Edit window, as Pro Tools' Delete does (Edit › Clear is Cmd+B); the MIDI editor keeps them for its selected notes (#404) |
|
||||
| 2026-10-13 | trivial | Progress log: mix.instrument params, unknown fields refused (#265) |
|
||||
| 2026-10-13 | trivial | Progress log: bus bounce compensates aux returns (#246) |
|
||||
| 2026-10-13 | trivial | Progress log: master insert latency compensated (#351) |
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use soundcraft_engine::{Engine, io};
|
||||
use soundcraft_ui_egui::dialogs::Dialog;
|
||||
use soundcraft_ui_egui::localization::{self, Language};
|
||||
use soundcraft_ui_egui::localized_format;
|
||||
use soundcraft_ui_egui::sampler_window::SampleRead;
|
||||
use soundcraft_ui_egui::{Services, SoundApp};
|
||||
use std::cell::RefCell;
|
||||
@@ -12,10 +14,19 @@ use wasm_bindgen::JsCast as _;
|
||||
const CANVAS_ID: &str = "soundcraft_canvas";
|
||||
const LOADING_ID: &str = "soundcraft_loading";
|
||||
|
||||
/// The language the browser asks for, for text shown before or outside a running app.
|
||||
fn browser_language() -> Language {
|
||||
web_sys::window().and_then(|w| w.navigator().language()).and_then(|tag| Language::parse(&tag)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn start() {
|
||||
eframe::WebLogger::init(log::LevelFilter::Info).ok();
|
||||
io::set_deliver(download);
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let _language = localization::enter(browser_language());
|
||||
if let Some(el) = web_sys::window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id(LOADING_ID)) {
|
||||
el.set_text_content(Some(localization::text("Loading SoundCraft…")));
|
||||
}
|
||||
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
|
||||
log::error!("no document");
|
||||
return;
|
||||
@@ -48,7 +59,11 @@ pub fn start() {
|
||||
if let Some(el) = document.get_element_by_id(LOADING_ID) {
|
||||
match result {
|
||||
Ok(()) => el.remove(),
|
||||
Err(e) => el.set_inner_html(&format!("<p>SoundCraft failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>")),
|
||||
Err(e) => el.set_text_content(Some(&format!(
|
||||
"{} {}",
|
||||
localized_format!("SoundCraft failed to start: {}", format!("{e:?}")),
|
||||
localization::text("A browser with WebGPU or WebGL2 is required.")
|
||||
))),
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -92,11 +107,11 @@ impl Purpose {
|
||||
}
|
||||
}
|
||||
|
||||
fn filter(self) -> (&'static str, Vec<&'static str>) {
|
||||
fn filter(self) -> (String, Vec<&'static str>) {
|
||||
match self {
|
||||
Self::Session => ("SoundCraft Session", SESSION_EXTS.to_vec()),
|
||||
Self::Audio => ("Audio", craft_audio::DECODE_EXTENSIONS.to_vec()),
|
||||
Self::Midi => ("MIDI", MIDI_EXTS.to_vec()),
|
||||
Self::Session => (localization::text("SoundCraft Session").to_owned(), SESSION_EXTS.to_vec()),
|
||||
Self::Audio => (localization::text("Audio").to_owned(), craft_audio::DECODE_EXTENSIONS.to_vec()),
|
||||
Self::Midi => (localization::text("MIDI").to_owned(), MIDI_EXTS.to_vec()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,9 +141,12 @@ impl WebShell {
|
||||
let Some(purpose) = purpose else { return };
|
||||
self.app.dialogs.open = None;
|
||||
let (inbox, ctx) = (self.inbox.clone(), ctx.clone());
|
||||
let (label, exts) = {
|
||||
let _language = localization::enter(self.app.ui.language);
|
||||
purpose.filter()
|
||||
};
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let (label, exts) = purpose.filter();
|
||||
let Some(file) = rfd::AsyncFileDialog::new().add_filter(label, &exts).pick_file().await else { return };
|
||||
let Some(file) = rfd::AsyncFileDialog::new().add_filter(&label, &exts).pick_file().await else { return };
|
||||
let bytes = file.read().await;
|
||||
inbox.borrow_mut().push((purpose, file.file_name(), bytes));
|
||||
ctx.request_repaint();
|
||||
@@ -165,6 +183,7 @@ impl WebShell {
|
||||
}
|
||||
|
||||
fn handle(&mut self, purpose: Purpose, name: String, bytes: Vec<u8>) {
|
||||
let _language = localization::enter(self.app.ui.language);
|
||||
let e = &mut self.app.engine;
|
||||
let at = e.session().edit.selection.start.max(0);
|
||||
let result = match purpose {
|
||||
@@ -174,15 +193,15 @@ impl WebShell {
|
||||
Purpose::Audio => {
|
||||
let before = e.session_arc();
|
||||
io::import_audio_bytes(e, &name, &bytes, None, None, at).map(|_| {
|
||||
e.push_undo("Import Audio", before);
|
||||
format!("Imported {name}")
|
||||
e.push_undo(localization::text("Import Audio"), before);
|
||||
localized_format!("Imported {name}", name = name)
|
||||
})
|
||||
}
|
||||
Purpose::Midi => {
|
||||
let before = e.session_arc();
|
||||
io::import_midi_bytes(e, &bytes, at, true).map(|_| {
|
||||
e.push_undo("Import MIDI", before);
|
||||
format!("Imported {name}")
|
||||
e.push_undo(localization::text("Import MIDI"), before);
|
||||
localized_format!("Imported {name}", name = name)
|
||||
})
|
||||
}
|
||||
};
|
||||
@@ -221,7 +240,8 @@ impl eframe::App for WebShell {
|
||||
/// Hand a saved or exported file to the person as a download named `name` (the engine's delivery
|
||||
/// hook on the web).
|
||||
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("download failed: {e:?}");
|
||||
let _language = localization::enter(browser_language());
|
||||
let js = |e: wasm_bindgen::JsValue| localized_format!("Download failed: {}", format!("{e:?}"));
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
|
||||
@@ -17,6 +17,12 @@ log.workspace = true
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
# The X11 host window for embedded editors on Linux and the BSDs, and the polling behind
|
||||
# `clap.posix-fd-support`.
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
x11rb = "0.13"
|
||||
libc = "0.2"
|
||||
|
||||
[[test]]
|
||||
name = "editor_main_thread"
|
||||
harness = false
|
||||
|
||||
@@ -20,7 +20,7 @@ use clap_sys::events::{
|
||||
clap_event_transport, clap_input_events, clap_output_events,
|
||||
};
|
||||
use clap_sys::ext::audio_ports::{CLAP_AUDIO_PORT_IS_MAIN, CLAP_EXT_AUDIO_PORTS, clap_audio_port_info, clap_plugin_audio_ports};
|
||||
use clap_sys::ext::gui::{CLAP_EXT_GUI, clap_host_gui, clap_plugin_gui, clap_window, clap_window_handle};
|
||||
use clap_sys::ext::gui::{CLAP_EXT_GUI, clap_host_gui, clap_plugin_gui, clap_window};
|
||||
use clap_sys::ext::latency::{CLAP_EXT_LATENCY, clap_host_latency, clap_plugin_latency};
|
||||
use clap_sys::ext::log::{CLAP_EXT_LOG, CLAP_LOG_ERROR, CLAP_LOG_FATAL, CLAP_LOG_WARNING, clap_host_log, clap_log_severity};
|
||||
use clap_sys::ext::note_ports::{CLAP_EXT_NOTE_PORTS, clap_note_port_info, clap_plugin_note_ports};
|
||||
@@ -29,6 +29,11 @@ use clap_sys::ext::params::{
|
||||
};
|
||||
use clap_sys::ext::render::{CLAP_EXT_RENDER, CLAP_RENDER_OFFLINE, CLAP_RENDER_REALTIME, clap_plugin_render};
|
||||
use clap_sys::ext::state::{CLAP_EXT_STATE, clap_host_state, clap_plugin_state};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
use clap_sys::ext::{
|
||||
posix_fd_support::{CLAP_EXT_POSIX_FD_SUPPORT, clap_host_posix_fd_support, clap_plugin_posix_fd_support},
|
||||
timer_support::{CLAP_EXT_TIMER_SUPPORT, clap_host_timer_support, clap_plugin_timer_support},
|
||||
};
|
||||
use clap_sys::factory::plugin_factory::{CLAP_PLUGIN_FACTORY_ID, clap_plugin_factory};
|
||||
use clap_sys::fixedpoint::{CLAP_BEATTIME_FACTOR, CLAP_SECTIME_FACTOR};
|
||||
use clap_sys::host::clap_host;
|
||||
@@ -49,6 +54,13 @@ mod events;
|
||||
mod gui;
|
||||
mod host;
|
||||
mod instance;
|
||||
/// The timers and descriptors a plugin registered through `clap.timer-support` and
|
||||
/// `clap.posix-fd-support`. X11 editors have no event loop of their own: they register their
|
||||
/// display connection's descriptor and their repaint timers, and the host calls them back on the
|
||||
/// main thread. SoundCraft does that from the editor's `idle`, once per UI frame (the UI repaints
|
||||
/// at least every 30 ms while an editor is open).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod run_loop;
|
||||
|
||||
pub(crate) use bundle::Bundle;
|
||||
pub(crate) use events::Event;
|
||||
@@ -105,8 +117,17 @@ fn read_name(buf: &[c_char]) -> String {
|
||||
#[path = "ffi/hostwin/windows.rs"]
|
||||
mod hostwin;
|
||||
|
||||
/// The X11 host window for embedded editors (Linux and the BSDs): a top-level window on our own
|
||||
/// connection to the X server (XWayland on Wayland desktops) that the plugin parents its GUI in.
|
||||
/// The close button only hides it (`WM_DELETE_WINDOW`); the editor link notices in `idle`,
|
||||
/// destroys the plugin's GUI, then the window. Our connection's events are read whenever a
|
||||
/// window's visibility is asked, which the UI does every frame while an editor is open.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[path = "ffi/hostwin/x11.rs"]
|
||||
mod hostwin;
|
||||
|
||||
/// Other platforms: embedded editors are not hosted (floating ones still are).
|
||||
#[cfg(not(windows))]
|
||||
#[cfg(not(any(windows, all(unix, not(target_os = "macos")))))]
|
||||
#[path = "ffi/hostwin/other.rs"]
|
||||
mod hostwin;
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ use super::{
|
||||
clap_host, clap_plugin_audio_ports, clap_plugin_entry, clap_plugin_factory, clap_plugin_gui, clap_plugin_latency, clap_plugin_note_ports,
|
||||
clap_plugin_params, clap_plugin_state, clap_version_is_compatible, read_cstr, scan,
|
||||
};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
use super::{CLAP_EXT_POSIX_FD_SUPPORT, CLAP_EXT_TIMER_SUPPORT, clap_plugin_posix_fd_support, clap_plugin_timer_support};
|
||||
use super::{CLAP_EXT_RENDER, clap_plugin_render};
|
||||
|
||||
// ---- loaded binaries -----------------------------------------------------------------------
|
||||
@@ -220,7 +222,19 @@ impl Bundle {
|
||||
inst.render = inst.extension::<clap_plugin_render>(CLAP_EXT_RENDER);
|
||||
let gui = inst.extension::<clap_plugin_gui>(CLAP_EXT_GUI);
|
||||
inst.gui = Arc::new(GuiLink {
|
||||
inner: Mutex::new(GuiInner { plugin, gui, state: inst.state_ext, alive: true, created: false, visible: false, window: None }),
|
||||
inner: Mutex::new(GuiInner {
|
||||
plugin,
|
||||
gui,
|
||||
state: inst.state_ext,
|
||||
alive: true,
|
||||
created: false,
|
||||
visible: false,
|
||||
window: None,
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
timer: inst.extension::<clap_plugin_timer_support>(CLAP_EXT_TIMER_SUPPORT),
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fd: inst.extension::<clap_plugin_posix_fd_support>(CLAP_EXT_POSIX_FD_SUPPORT),
|
||||
}),
|
||||
host: Arc::clone(&inst.state),
|
||||
});
|
||||
Ok(inst)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::events::ostream_write;
|
||||
use super::host::HostState;
|
||||
use super::{
|
||||
Arc, CStr, CString, Mutex, Ordering, PoisonError, c_void, clap_ostream, clap_plugin, clap_plugin_gui, clap_plugin_state, clap_window,
|
||||
clap_window_handle, hostwin,
|
||||
Arc, CStr, CString, Mutex, Ordering, PoisonError, c_void, clap_ostream, clap_plugin, clap_plugin_gui, clap_plugin_state, clap_window, hostwin,
|
||||
};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
use super::{clap_plugin_posix_fd_support, clap_plugin_timer_support};
|
||||
|
||||
// ---- editor (clap.gui) ---------------------------------------------------------------------
|
||||
|
||||
@@ -47,6 +48,11 @@ pub(super) struct GuiInner {
|
||||
pub(super) visible: bool,
|
||||
/// The host window of an embedded editor (`None` for floating editors).
|
||||
pub(super) window: Option<hostwin::HostWindow>,
|
||||
/// The plugin's `clap.timer-support` and `clap.posix-fd-support` (null without them).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub(super) timer: *const clap_plugin_timer_support,
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub(super) fd: *const clap_plugin_posix_fd_support,
|
||||
}
|
||||
|
||||
/// The link between an instance and its editor and state handles. The instance may process on
|
||||
@@ -71,6 +77,10 @@ impl Default for GuiLink {
|
||||
created: false,
|
||||
visible: false,
|
||||
window: None,
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
timer: std::ptr::null(),
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fd: std::ptr::null(),
|
||||
}),
|
||||
host: Arc::new(HostState::default()),
|
||||
}
|
||||
@@ -126,7 +136,7 @@ impl GuiLink {
|
||||
if hostwin::SUPPORTED && unsafe { supported(g.plugin, api.as_ptr(), false) } {
|
||||
return self.open_embedded(&mut g, vt, api, title);
|
||||
}
|
||||
return Err("this plugin offers only an embedded editor, which SoundCraft hosts on Windows only".into());
|
||||
return Err("this plugin offers only an embedded editor, which SoundCraft hosts on Windows and X11 (Linux, BSDs) only".into());
|
||||
}
|
||||
self.host.gui_closed.store(false, Ordering::Relaxed);
|
||||
self.host.gui_destroyed.store(false, Ordering::Relaxed);
|
||||
@@ -188,7 +198,7 @@ impl GuiLink {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let parent = clap_window { api: api.as_ptr(), specific: clap_window_handle { win32: win.parent() } };
|
||||
let parent = clap_window { api: api.as_ptr(), specific: win.handle() };
|
||||
// SAFETY: live plugin with a created embedded GUI; `parent` names our live window and
|
||||
// outlives the call.
|
||||
if !unsafe { set_parent(g.plugin, &parent) } {
|
||||
@@ -274,6 +284,8 @@ impl GuiLink {
|
||||
unsafe { f(g.plugin) };
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
self.dispatch(&g);
|
||||
if g.created {
|
||||
let resize = self.host.gui_resize.swap(0, Ordering::Relaxed);
|
||||
if resize != 0
|
||||
@@ -330,5 +342,35 @@ impl GuiLink {
|
||||
}
|
||||
}
|
||||
g.alive = false;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
self.host.run_loop.clear();
|
||||
}
|
||||
|
||||
/// Calls the plugin back for its ready descriptors and due timers (main thread, under the
|
||||
/// lock, plugin alive). One unregistered earlier in the same pass is skipped.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn dispatch(&self, g: &GuiInner) {
|
||||
if !g.alive {
|
||||
return;
|
||||
}
|
||||
let rl = &self.host.run_loop;
|
||||
// SAFETY: null or the plugin's static extension vtables, valid while `alive`.
|
||||
let (timer, fd) = unsafe { (g.timer.as_ref().and_then(|t| t.on_timer), g.fd.as_ref().and_then(|f| f.on_fd)) };
|
||||
if let Some(on_fd) = fd {
|
||||
for (d, flags) in rl.ready() {
|
||||
if rl.has_fd(d) {
|
||||
// SAFETY: live plugin, main thread, a descriptor it registered.
|
||||
unsafe { on_fd(g.plugin, d, flags) };
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(on_timer) = timer {
|
||||
for id in rl.due(std::time::Instant::now()) {
|
||||
if rl.has_timer(id) {
|
||||
// SAFETY: live plugin, main thread, a timer it registered.
|
||||
unsafe { on_timer(g.plugin, id) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ use super::{
|
||||
CLAP_LOG_WARNING, CStr, EDIT_CAP, Mutex, Ordering, c_char, c_void, clap_host, clap_host_gui, clap_host_latency, clap_host_log, clap_host_params,
|
||||
clap_host_state, clap_id, clap_log_severity, clap_param_clear_flags, clap_param_rescan_flags, read_cstr,
|
||||
};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
use super::{CLAP_EXT_POSIX_FD_SUPPORT, CLAP_EXT_TIMER_SUPPORT, clap_host_posix_fd_support, clap_host_timer_support};
|
||||
|
||||
// ---- host side -----------------------------------------------------------------------------
|
||||
|
||||
@@ -25,6 +27,10 @@ pub(crate) struct HostState {
|
||||
/// Parameter changes the plugin reported (output events: typically edits in its GUI),
|
||||
/// waiting for the UI. Bounded by `EDIT_CAP`; the audio thread only `try_lock`s it.
|
||||
pub edits: Mutex<Vec<(u32, f64)>>,
|
||||
/// The timers and descriptors the plugin registered (`clap.timer-support`,
|
||||
/// `clap.posix-fd-support`), serviced by the editor's `idle` on the main thread.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub run_loop: super::run_loop::RunLoop,
|
||||
}
|
||||
|
||||
impl Default for HostState {
|
||||
@@ -42,6 +48,8 @@ impl Default for HostState {
|
||||
gui_hide: AtomicBool::new(false),
|
||||
gui_resize: AtomicU64::new(0),
|
||||
edits: Mutex::new(Vec::with_capacity(EDIT_CAP)),
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
run_loop: super::run_loop::RunLoop::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,8 +207,74 @@ pub(super) unsafe extern "C" fn host_get_extension(_host: *const clap_host, id:
|
||||
(&HOST_STATE as *const clap_host_state).cast()
|
||||
} else if id == CLAP_EXT_GUI {
|
||||
(&HOST_GUI as *const clap_host_gui).cast()
|
||||
} else if let Some(ext) = run_loop_extension(id) {
|
||||
ext
|
||||
} else {
|
||||
// Everything else (thread-check, timers, fd support, …) is unsupported: CLAP allows null.
|
||||
// Everything else (thread-check, …) is unsupported: CLAP allows null.
|
||||
std::ptr::null()
|
||||
}
|
||||
}
|
||||
|
||||
/// `clap.timer-support` and `clap.posix-fd-support`: X11 editors have no event loop of their own
|
||||
/// and rely on the host's to read their display connection and to repaint.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn run_loop_extension(id: &CStr) -> Option<*const c_void> {
|
||||
if id == CLAP_EXT_TIMER_SUPPORT {
|
||||
Some((&HOST_TIMER as *const clap_host_timer_support).cast())
|
||||
} else if id == CLAP_EXT_POSIX_FD_SUPPORT {
|
||||
Some((&HOST_FD as *const clap_host_posix_fd_support).cast())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
fn run_loop_extension(_id: &CStr) -> Option<*const c_void> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
static HOST_TIMER: clap_host_timer_support =
|
||||
clap_host_timer_support { register_timer: Some(host_register_timer), unregister_timer: Some(host_unregister_timer) };
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
static HOST_FD: clap_host_posix_fd_support =
|
||||
clap_host_posix_fd_support { register_fd: Some(host_register_fd), modify_fd: Some(host_modify_fd), unregister_fd: Some(host_unregister_fd) };
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
unsafe extern "C" fn host_register_timer(host: *const clap_host, period_ms: u32, timer_id: *mut clap_id) -> bool {
|
||||
// SAFETY: the plugin passes back the host pointer we gave it.
|
||||
let Some(s) = (unsafe { state(host) }) else { return false };
|
||||
// SAFETY: an out-pointer from the plugin (or null, handled).
|
||||
let Some(out) = (unsafe { timer_id.as_mut() }) else { return false };
|
||||
match s.run_loop.add_timer(period_ms) {
|
||||
Some(id) => {
|
||||
*out = id;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
unsafe extern "C" fn host_unregister_timer(host: *const clap_host, timer_id: clap_id) -> bool {
|
||||
// SAFETY: the plugin passes back the host pointer we gave it.
|
||||
unsafe { state(host) }.is_some_and(|s| s.run_loop.remove_timer(timer_id))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
unsafe extern "C" fn host_register_fd(host: *const clap_host, fd: i32, flags: u32) -> bool {
|
||||
// SAFETY: the plugin passes back the host pointer we gave it.
|
||||
unsafe { state(host) }.is_some_and(|s| s.run_loop.add_fd(fd, flags))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
unsafe extern "C" fn host_modify_fd(host: *const clap_host, fd: i32, flags: u32) -> bool {
|
||||
// SAFETY: the plugin passes back the host pointer we gave it.
|
||||
unsafe { state(host) }.is_some_and(|s| s.run_loop.modify_fd(fd, flags))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
unsafe extern "C" fn host_unregister_fd(host: *const clap_host, fd: i32) -> bool {
|
||||
// SAFETY: the plugin passes back the host pointer we gave it.
|
||||
unsafe { state(host) }.is_some_and(|s| s.run_loop.remove_fd(fd))
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use clap_sys::ext::gui::clap_window_handle;
|
||||
use std::ffi::c_void;
|
||||
|
||||
pub const SUPPORTED: bool = false;
|
||||
@@ -11,8 +12,8 @@ impl HostWindow {
|
||||
pub fn raw(&self) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
pub fn parent(&self) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
pub fn handle(&self) -> clap_window_handle {
|
||||
clap_window_handle { ptr: std::ptr::null_mut() }
|
||||
}
|
||||
pub fn raise(&self) {}
|
||||
pub fn is_visible(&self) -> bool {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use clap_sys::ext::gui::clap_window_handle;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::OnceLock;
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
|
||||
@@ -128,6 +129,10 @@ impl HostWindow {
|
||||
self.live().unwrap_or(std::ptr::null_mut())
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> clap_window_handle {
|
||||
clap_window_handle { win32: self.parent() }
|
||||
}
|
||||
|
||||
pub fn raise(&self) {
|
||||
if let Some(h) = self.live() {
|
||||
// SAFETY: a live window of this thread.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
use clap_sys::ext::gui::clap_window_handle;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::properties::WmSizeHints;
|
||||
use x11rb::protocol::Event;
|
||||
use x11rb::protocol::xproto::{
|
||||
AtomEnum, ConfigureWindowAux, ConnectionExt as _, CreateWindowAux, EventMask, PropMode, StackMode, Window, WindowClass,
|
||||
};
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
use x11rb::wrapper::ConnectionExt as _;
|
||||
|
||||
pub const SUPPORTED: bool = true;
|
||||
|
||||
/// Rust names the process's first thread "main"; the app runs its UI (and event loop) there.
|
||||
fn on_main_thread() -> bool {
|
||||
std::thread::current().name() == Some("main")
|
||||
}
|
||||
|
||||
struct X {
|
||||
conn: RustConnection,
|
||||
root: Window,
|
||||
visual: u32,
|
||||
background: u32,
|
||||
wm_protocols: u32,
|
||||
wm_delete: u32,
|
||||
net_wm_name: u32,
|
||||
utf8: u32,
|
||||
/// Windows whose close button was pressed (hidden, not yet destroyed).
|
||||
closed: Mutex<HashSet<Window>>,
|
||||
}
|
||||
|
||||
/// The process-wide connection, opened on first use (`None` without an X server).
|
||||
fn x() -> Option<&'static X> {
|
||||
static X: OnceLock<Option<X>> = OnceLock::new();
|
||||
X.get_or_init(|| match connect() {
|
||||
Ok(x) => Some(x),
|
||||
Err(e) => {
|
||||
log::warn!("clap: no X11 display for plugin editors: {e}");
|
||||
None
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn connect() -> Result<X, Box<dyn std::error::Error>> {
|
||||
let (conn, screen) = x11rb::connect(None)?;
|
||||
let s = conn.setup().roots.get(screen).ok_or("no X11 screen")?;
|
||||
let (root, visual, background) = (s.root, s.root_visual, s.black_pixel);
|
||||
let atom = |name: &[u8]| -> Result<u32, Box<dyn std::error::Error>> { Ok(conn.intern_atom(false, name)?.reply()?.atom) };
|
||||
Ok(X {
|
||||
wm_protocols: atom(b"WM_PROTOCOLS")?,
|
||||
wm_delete: atom(b"WM_DELETE_WINDOW")?,
|
||||
net_wm_name: atom(b"_NET_WM_NAME")?,
|
||||
utf8: atom(b"UTF8_STRING")?,
|
||||
root,
|
||||
visual,
|
||||
background,
|
||||
closed: Mutex::new(HashSet::new()),
|
||||
conn,
|
||||
})
|
||||
}
|
||||
|
||||
impl X {
|
||||
fn closed(&self) -> std::sync::MutexGuard<'_, HashSet<Window>> {
|
||||
self.closed.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Reads pending events: a close request hides its window and marks it closed.
|
||||
fn pump(&self) {
|
||||
while let Ok(Some(ev)) = self.conn.poll_for_event() {
|
||||
if let Event::ClientMessage(m) = ev
|
||||
&& m.type_ == self.wm_protocols
|
||||
&& m.format == 32
|
||||
&& m.data.as_data32().first() == Some(&self.wm_delete)
|
||||
{
|
||||
let _ = self.conn.unmap_window(m.window);
|
||||
self.closed().insert(m.window);
|
||||
}
|
||||
}
|
||||
let _ = self.conn.flush();
|
||||
}
|
||||
|
||||
/// Fixes the window's size for the window manager (plugins resize through the host).
|
||||
fn size_hints(&self, w: Window, width: u32, height: u32) {
|
||||
let (width, height) = (width as i32, height as i32);
|
||||
let hints = WmSizeHints { min_size: Some((width, height)), max_size: Some((width, height)), ..WmSizeHints::new() };
|
||||
let _ = hints.set_normal_hints(&self.conn, w);
|
||||
}
|
||||
}
|
||||
|
||||
fn dims(w: f64, h: f64) -> (u16, u16) {
|
||||
(w.clamp(1.0, 16_384.0) as u16, h.clamp(1.0, 16_384.0) as u16)
|
||||
}
|
||||
|
||||
pub struct HostWindow {
|
||||
id: Window,
|
||||
shown: AtomicBool,
|
||||
}
|
||||
|
||||
impl HostWindow {
|
||||
pub fn new(title: &str, w: f64, h: f64) -> Result<HostWindow, String> {
|
||||
if !on_main_thread() {
|
||||
return Err("plugin editors must be opened on the main thread".into());
|
||||
}
|
||||
let x = x().ok_or_else(|| "plugin editors need an X11 display (XWayland on Wayland desktops)".to_string())?;
|
||||
let err = |e: &dyn std::fmt::Display| format!("cannot create the editor window: {e}");
|
||||
let id = x.conn.generate_id().map_err(|e| err(&e))?;
|
||||
let (width, height) = dims(w, h);
|
||||
let aux = CreateWindowAux::new().background_pixel(x.background).event_mask(EventMask::STRUCTURE_NOTIFY);
|
||||
x.conn
|
||||
.create_window(x11rb::COPY_DEPTH_FROM_PARENT, id, x.root, 0, 0, width, height, 0, WindowClass::INPUT_OUTPUT, x.visual, &aux)
|
||||
.map_err(|e| err(&e))?;
|
||||
let _ = x.conn.change_property8(PropMode::REPLACE, id, AtomEnum::WM_NAME, AtomEnum::STRING, title.as_bytes());
|
||||
let _ = x.conn.change_property8(PropMode::REPLACE, id, x.net_wm_name, x.utf8, title.as_bytes());
|
||||
let _ = x.conn.change_property8(PropMode::REPLACE, id, AtomEnum::WM_CLASS, AtomEnum::STRING, b"soundcraft\0SoundCraft\0");
|
||||
let _ = x.conn.change_property32(PropMode::REPLACE, id, x.wm_protocols, AtomEnum::ATOM, &[x.wm_delete]);
|
||||
x.size_hints(id, width.into(), height.into());
|
||||
// A round trip, so the window exists before the plugin (on its own connection)
|
||||
// parents its GUI in it.
|
||||
x.conn.get_input_focus().map_err(|e| err(&e))?.reply().map_err(|e| err(&e))?;
|
||||
Ok(HostWindow { id, shown: AtomicBool::new(false) })
|
||||
}
|
||||
|
||||
/// The window id (for resizes).
|
||||
pub fn raw(&self) -> *mut c_void {
|
||||
self.id as usize as *mut c_void
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> clap_window_handle {
|
||||
clap_window_handle { x11: std::ffi::c_ulong::from(self.id) }
|
||||
}
|
||||
|
||||
pub fn raise(&self) {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return };
|
||||
x.closed().remove(&self.id);
|
||||
let _ = x.conn.map_window(self.id);
|
||||
let _ = x.conn.configure_window(self.id, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE));
|
||||
let _ = x.conn.flush();
|
||||
self.shown.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return false };
|
||||
x.pump();
|
||||
self.shown.load(Ordering::Relaxed) && !x.closed().contains(&self.id)
|
||||
}
|
||||
|
||||
pub fn close(self) {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return };
|
||||
x.closed().remove(&self.id);
|
||||
let _ = x.conn.destroy_window(self.id);
|
||||
let _ = x.conn.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resizes a host window (`window` from [`HostWindow::raw`]); main thread only.
|
||||
pub fn resize(window: *mut c_void, w: f64, h: f64) {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return };
|
||||
let Ok(id) = Window::try_from(window as usize) else { return };
|
||||
if id == 0 {
|
||||
return;
|
||||
}
|
||||
let (width, height) = dims(w, h);
|
||||
x.size_hints(id, width.into(), height.into());
|
||||
let _ = x.conn.configure_window(id, &ConfigureWindowAux::new().width(u32::from(width)).height(u32::from(height)));
|
||||
let _ = x.conn.flush();
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use clap_sys::ext::posix_fd_support::{CLAP_POSIX_FD_ERROR, CLAP_POSIX_FD_READ, CLAP_POSIX_FD_WRITE, clap_posix_fd_flags};
|
||||
use clap_sys::id::clap_id;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Registrations kept per instance; a plugin needs a handful.
|
||||
const MAX_ENTRIES: usize = 256;
|
||||
/// Longest timer period accepted (one hour).
|
||||
const MAX_PERIOD_MS: u32 = 3_600_000;
|
||||
|
||||
struct Timer {
|
||||
id: clap_id,
|
||||
every: Duration,
|
||||
next: Instant,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Entries {
|
||||
timers: Vec<Timer>,
|
||||
fds: Vec<(i32, clap_posix_fd_flags)>,
|
||||
next_id: clap_id,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RunLoop {
|
||||
entries: Mutex<Entries>,
|
||||
}
|
||||
|
||||
impl RunLoop {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Entries> {
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub fn add_timer(&self, period_ms: u32) -> Option<clap_id> {
|
||||
let mut e = self.lock();
|
||||
if e.timers.len() >= MAX_ENTRIES {
|
||||
return None;
|
||||
}
|
||||
// Ids are never reused within an instance (`CLAP_INVALID_ID` is u32::MAX).
|
||||
let id = e.next_id;
|
||||
e.next_id = e.next_id.checked_add(1).filter(|&n| n != clap_id::MAX)?;
|
||||
let every = Duration::from_millis(u64::from(period_ms.clamp(1, MAX_PERIOD_MS)));
|
||||
e.timers.push(Timer { id, every, next: Instant::now() + every });
|
||||
log::debug!("clap: run loop: timer {id} every {} ms", every.as_millis());
|
||||
Some(id)
|
||||
}
|
||||
|
||||
pub fn remove_timer(&self, id: clap_id) -> bool {
|
||||
let mut e = self.lock();
|
||||
let before = e.timers.len();
|
||||
e.timers.retain(|t| t.id != id);
|
||||
e.timers.len() != before
|
||||
}
|
||||
|
||||
pub fn add_fd(&self, fd: i32, flags: clap_posix_fd_flags) -> bool {
|
||||
let mut e = self.lock();
|
||||
if fd < 0 || e.fds.len() >= MAX_ENTRIES || e.fds.iter().any(|&(f, _)| f == fd) {
|
||||
return false;
|
||||
}
|
||||
e.fds.push((fd, flags));
|
||||
log::debug!("clap: run loop: watching fd {fd}");
|
||||
true
|
||||
}
|
||||
|
||||
pub fn modify_fd(&self, fd: i32, flags: clap_posix_fd_flags) -> bool {
|
||||
let mut e = self.lock();
|
||||
match e.fds.iter_mut().find(|(f, _)| *f == fd) {
|
||||
Some(entry) => {
|
||||
entry.1 = flags;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_fd(&self, fd: i32) -> bool {
|
||||
let mut e = self.lock();
|
||||
let before = e.fds.len();
|
||||
e.fds.retain(|&(f, _)| f != fd);
|
||||
e.fds.len() != before
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
let mut e = self.lock();
|
||||
e.timers.clear();
|
||||
e.fds.clear();
|
||||
}
|
||||
|
||||
pub fn has_timer(&self, id: clap_id) -> bool {
|
||||
self.lock().timers.iter().any(|t| t.id == id)
|
||||
}
|
||||
|
||||
pub fn has_fd(&self, fd: i32) -> bool {
|
||||
self.lock().fds.iter().any(|&(f, _)| f == fd)
|
||||
}
|
||||
|
||||
/// The timers due at `now`, rescheduled from `now` (a late UI frame fires each once
|
||||
/// rather than replaying missed ticks).
|
||||
pub fn due(&self, now: Instant) -> Vec<clap_id> {
|
||||
let mut e = self.lock();
|
||||
let mut out = Vec::new();
|
||||
for t in e.timers.iter_mut().filter(|t| t.next <= now) {
|
||||
t.next = now + t.every;
|
||||
out.push(t.id);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The registered descriptors that are ready for what they asked for (or failed), with
|
||||
/// the matching CLAP flags, without waiting.
|
||||
pub fn ready(&self) -> Vec<(i32, clap_posix_fd_flags)> {
|
||||
let fds = self.lock().fds.clone();
|
||||
if fds.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut polled: Vec<libc::pollfd> = fds
|
||||
.iter()
|
||||
.map(|&(fd, flags)| {
|
||||
let mut events = 0;
|
||||
if flags & CLAP_POSIX_FD_READ != 0 {
|
||||
events |= libc::POLLIN;
|
||||
}
|
||||
if flags & CLAP_POSIX_FD_WRITE != 0 {
|
||||
events |= libc::POLLOUT;
|
||||
}
|
||||
libc::pollfd { fd, events, revents: 0 }
|
||||
})
|
||||
.collect();
|
||||
// SAFETY: `polled` is a valid, writable array of `polled.len()` entries; a zero
|
||||
// timeout never blocks.
|
||||
if unsafe { libc::poll(polled.as_mut_ptr(), polled.len() as libc::nfds_t, 0) } <= 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
polled
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let mut flags = 0;
|
||||
if p.revents & libc::POLLIN != 0 {
|
||||
flags |= CLAP_POSIX_FD_READ;
|
||||
}
|
||||
if p.revents & libc::POLLOUT != 0 {
|
||||
flags |= CLAP_POSIX_FD_WRITE;
|
||||
}
|
||||
if p.revents & (libc::POLLERR | libc::POLLHUP) != 0 {
|
||||
flags |= CLAP_POSIX_FD_ERROR;
|
||||
}
|
||||
(flags != 0).then_some((p.fd, flags))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn timers_and_descriptors_follow_registration() {
|
||||
let rl = RunLoop::default();
|
||||
// Before registering: every timer's first tick is then later than `t0`.
|
||||
let t0 = Instant::now();
|
||||
let a = rl.add_timer(10).unwrap();
|
||||
let b = rl.add_timer(0).unwrap();
|
||||
assert_ne!(a, b, "ids are unique");
|
||||
assert!(rl.due(t0).is_empty(), "not due yet");
|
||||
let mut due = rl.due(t0 + Duration::from_secs(1));
|
||||
due.sort_unstable();
|
||||
assert_eq!(due, vec![a, b], "a late frame fires each timer once");
|
||||
assert!(rl.remove_timer(a) && !rl.remove_timer(a));
|
||||
assert_eq!(rl.due(t0 + Duration::from_secs(2)), vec![b]);
|
||||
let mut fds = [0; 2];
|
||||
// SAFETY: `fds` holds the two descriptors `pipe` writes.
|
||||
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
|
||||
assert!(rl.add_fd(fds[0], CLAP_POSIX_FD_READ));
|
||||
assert!(!rl.add_fd(fds[0], CLAP_POSIX_FD_READ), "registered once");
|
||||
assert!(!rl.add_fd(-1, CLAP_POSIX_FD_READ));
|
||||
assert!(rl.ready().is_empty(), "nothing to read");
|
||||
// SAFETY: a valid one-byte buffer written to our own pipe.
|
||||
assert_eq!(unsafe { libc::write(fds[1], b"x".as_ptr().cast(), 1) }, 1);
|
||||
assert_eq!(rl.ready(), vec![(fds[0], CLAP_POSIX_FD_READ)]);
|
||||
assert!(rl.modify_fd(fds[0], CLAP_POSIX_FD_WRITE));
|
||||
assert!(rl.ready().is_empty(), "a read end never becomes writable");
|
||||
assert!(rl.remove_fd(fds[0]) && !rl.has_fd(fds[0]));
|
||||
rl.clear();
|
||||
assert!(!rl.has_timer(b));
|
||||
// SAFETY: closing the pipe we opened.
|
||||
unsafe {
|
||||
libc::close(fds[0]);
|
||||
libc::close(fds[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,11 @@
|
||||
//! [`Plugin::load_state`] as an opaque blob. Plugin editors (`clap.gui`) open as the plugin's own
|
||||
//! floating window ([`Plugin::open_editor`], or [`Plugin::editor`] for a handle usable on the main
|
||||
//! thread while the instance processes on the audio thread). Plugins that offer only an embedded
|
||||
//! editor get a host window of SoundCraft's on Windows (resized on `request_resize`, closed by
|
||||
//! its title bar); elsewhere they are not hosted yet, and SoundCraft's generic parameter editor
|
||||
//! still works for them.
|
||||
//! editor get a host window of SoundCraft's on Windows and on X11 (Linux, BSDs; resized on
|
||||
//! `request_resize`, closed by its title bar); on macOS they are not hosted yet, and SoundCraft's
|
||||
//! generic parameter editor still works for them. On X11 the host also offers
|
||||
//! `clap.timer-support` and `clap.posix-fd-support`, serviced by the editor's `idle`, since X11
|
||||
//! editors have no event loop of their own.
|
||||
//! Parameter changes made in the plugin's GUI arrive as output events while the plugin processes
|
||||
//! and are reported by the editor's `idle`.
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod auto_pan;
|
||||
pub mod drums;
|
||||
pub mod dynamics;
|
||||
pub mod eq;
|
||||
pub mod freq_shifter;
|
||||
pub mod harmonic;
|
||||
pub mod modulation;
|
||||
pub mod pitch;
|
||||
@@ -32,6 +33,7 @@ pub(crate) static REGISTRY: &[&PluginInfo] = &[
|
||||
&modulation::FLANGER_INFO,
|
||||
&modulation::PHASER_INFO,
|
||||
&modulation::RING_INFO,
|
||||
&freq_shifter::FREQ_SHIFTER_INFO,
|
||||
&harmonic::SAT_INFO,
|
||||
&harmonic::LOFI_INFO,
|
||||
&harmonic::RECT_INFO,
|
||||
@@ -67,6 +69,7 @@ pub(crate) fn instantiate(id: &str) -> Option<Box<dyn Plugin>> {
|
||||
"flanger" => Box::new(modulation::ModFx::flanger()),
|
||||
"phaser" => Box::new(modulation::Phaser::new()),
|
||||
"ring_mod" => Box::new(modulation::RingMod::new()),
|
||||
"freq_shifter" => Box::new(freq_shifter::FreqShifter::new()),
|
||||
"saturator" => Box::new(harmonic::Saturator::new()),
|
||||
"lofi" => Box::new(harmonic::LoFi::new()),
|
||||
"rectifier" => Box::new(harmonic::Rectifier::new()),
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
//! Frequency Shifter: moves every frequency in the signal by the same number of hertz.
|
||||
//!
|
||||
//! Unlike a pitch shifter, which multiplies frequencies, a frequency shifter adds a constant to
|
||||
//! them, so harmonic sounds become inharmonic. The signal goes through two chains of allpass
|
||||
//! filters whose outputs differ in phase by 90° (the in-phase and quadrature parts of the
|
||||
//! analytic signal). Multiplying them by a cosine and a sine at the shift frequency and adding or
|
||||
//! subtracting the products keeps only the upper or only the lower sideband (single-sideband
|
||||
//! modulation). The filters run in `f64`.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
use crate::params::{Params, choice, lin, log, param_plumbing};
|
||||
use crate::util::{FALLBACK_SR, Smoother, frames_in, sane_channels, sane_sr};
|
||||
use crate::{Category, ParamInfo, Plugin, PluginInfo, Unit};
|
||||
|
||||
const MODE_CHOICES: &[&str] = &["Up", "Down", "Up & Down", "Stereo"];
|
||||
const MODE_DOWN: usize = 1;
|
||||
const MODE_BOTH: usize = 2;
|
||||
const MODE_STEREO: usize = 3;
|
||||
|
||||
/// Allpass sections in each of the two chains.
|
||||
const SECTIONS: usize = 10;
|
||||
/// The 90° phase difference holds from this frequency to the same distance below Nyquist.
|
||||
const QUADRATURE_LOW_HZ: f64 = 20.0;
|
||||
/// Largest Feedback, in percent. The shift raises a signal's energy by at most √2 (the
|
||||
/// quadrature pair has twice the energy of its input, and the output is never larger than
|
||||
/// their magnitude), so with feedback below 1/√2 the loop gain stays under one and the
|
||||
/// feedback loop is stable for any input, mode and frequency (small-gain theorem).
|
||||
const MAX_FEEDBACK: f32 = 70.0;
|
||||
/// The level, relative to the input, at which `tail_samples` considers the ringing over (-80 dB).
|
||||
const TAIL_FLOOR: f64 = 1.0e-4;
|
||||
|
||||
static FS_PARAMS: [ParamInfo; 4] = [
|
||||
log("frequency", "Frequency", 0.01, 5000.0, 100.0, Unit::Hz),
|
||||
choice("mode", "Mode", MODE_CHOICES, 0),
|
||||
lin("feedback", "Feedback", 0.0, MAX_FEEDBACK, 0.0, Unit::Percent),
|
||||
lin("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent),
|
||||
];
|
||||
|
||||
pub static FREQ_SHIFTER_INFO: PluginInfo = PluginInfo {
|
||||
id: "freq_shifter",
|
||||
name: "Frequency Shifter",
|
||||
short_name: "FreqShft",
|
||||
category: Category::Modulation,
|
||||
params: &FS_PARAMS,
|
||||
is_instrument: false,
|
||||
audiosuite: true,
|
||||
};
|
||||
|
||||
/// Arithmetic-geometric mean of `a` and `b` (both positive).
|
||||
fn agm(mut a: f64, mut b: f64) -> f64 {
|
||||
for _ in 0..64 {
|
||||
let (m, g) = (0.5 * (a + b), (a * b).sqrt());
|
||||
a = m;
|
||||
b = g;
|
||||
if (a - b).abs() <= 1.0e-15 * a {
|
||||
break;
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Allpass coefficients for a 90° phase-difference network at `sr`, accurate from
|
||||
/// [`QUADRATURE_LOW_HZ`] to `sr / 2 - QUADRATURE_LOW_HZ`.
|
||||
///
|
||||
/// They are the coefficients of an elliptic half-band filter built from two allpass chains
|
||||
/// (Valenzuela and Constantinides, "Digital signal processing schemes for efficient
|
||||
/// interpolation and decimation", IEE Proceedings G 130(6), 1983). Moving that filter's
|
||||
/// response by a quarter of the sample rate turns its two branches into a phase splitter: each
|
||||
/// section becomes `(a - z⁻²) / (1 - a z⁻²)`. Even-numbered coefficients go to the in-phase
|
||||
/// chain, odd-numbered ones to the quadrature chain, which also has a one-sample delay.
|
||||
///
|
||||
/// The half-band filter has a transition band of `tb = 2 · low / sr` (as a fraction of the
|
||||
/// sample rate) centred on `sr / 4`, so after the shift the phase error is equiripple between
|
||||
/// `low` and `sr / 2 - low`. Its selectivity is `k = tan²(π (1 - 2 tb) / 4)` and its nome
|
||||
/// `q = exp(-π K(k') / K(k))`, with `K` the complete elliptic integral of the first kind computed
|
||||
/// by the arithmetic-geometric mean. Coefficient `i` of `n` comes from the theta-function sums
|
||||
///
|
||||
/// ```text
|
||||
/// w = q^¼ · Σₘ (-1)ᵐ q^(m(m+1)) sin((2m+1) i π / (2n+1)) / (½ + Σₘ₌₁ (-1)ᵐ q^(m²) cos(2 m i π / (2n+1)))
|
||||
/// x = √((1 - w² k)(1 - w² / k)) / (1 + w²), a = (1 - x) / (1 + x).
|
||||
/// ```
|
||||
///
|
||||
/// `None` when the rate is unusable or a coefficient comes out of `[0, 1)`.
|
||||
fn design_quadrature(sr: f64) -> Option<[f64; 2 * SECTIONS]> {
|
||||
let tb = 2.0 * QUADRATURE_LOW_HZ / sr;
|
||||
if !tb.is_finite() || tb <= 0.0 || tb >= 0.25 {
|
||||
return None;
|
||||
}
|
||||
let k = ((1.0 - 2.0 * tb) * PI / 4.0).tan().powi(2);
|
||||
let kc = ((1.0 - k) * (1.0 + k)).sqrt();
|
||||
// K(k') / K(k) = agm(1, k') / agm(1, k), since K(k) = π / (2 agm(1, k')).
|
||||
let q = (-PI * agm(1.0, kc) / agm(1.0, k)).exp();
|
||||
// The half-band filter has one coefficient per section of both chains: order 2 · 2 SECTIONS + 1.
|
||||
let order = (4 * SECTIONS + 1) as f64;
|
||||
let mut coefs = [0.0f64; 2 * SECTIONS];
|
||||
for (idx, coef) in coefs.iter_mut().enumerate() {
|
||||
let i = (idx + 1) as f64;
|
||||
let mut num = 0.0;
|
||||
for m in 0..64i32 {
|
||||
let sign = if m % 2 == 0 { 1.0 } else { -1.0 };
|
||||
let term = sign * q.powi(m * (m + 1)) * ((2 * m + 1) as f64 * i * PI / order).sin();
|
||||
num += term;
|
||||
if term.abs() < 1.0e-30 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut den = 0.5;
|
||||
for m in 1..64i32 {
|
||||
let sign = if m % 2 == 0 { 1.0 } else { -1.0 };
|
||||
let term = sign * q.powi(m * m) * (2.0 * f64::from(m) * i * PI / order).cos();
|
||||
den += term;
|
||||
if term.abs() < 1.0e-30 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let w = q.powf(0.25) * num / den;
|
||||
let w2 = w * w;
|
||||
let x = ((1.0 - w2 * k) * (1.0 - w2 / k)).max(0.0).sqrt() / (1.0 + w2);
|
||||
*coef = (1.0 - x) / (1.0 + x);
|
||||
}
|
||||
coefs.iter().all(|a| a.is_finite() && (0.0..1.0).contains(a)).then_some(coefs)
|
||||
}
|
||||
|
||||
/// The network for `sr`, falling back to the default rate's (and, failing that, to plain
|
||||
/// delays) so that a strange host rate can never leave the plugin without coefficients.
|
||||
fn quadrature_coefs(sr: f64) -> [f64; 2 * SECTIONS] {
|
||||
design_quadrature(sr).or_else(|| design_quadrature(f64::from(FALLBACK_SR))).unwrap_or([0.0; 2 * SECTIONS])
|
||||
}
|
||||
|
||||
/// Flushes values too small to hear (and any non-finite value) to zero, so silence does not
|
||||
/// leave the filter states running on denormals.
|
||||
#[inline]
|
||||
fn flush64(x: f64) -> f64 {
|
||||
if x.abs() > 1.0e-30 && x.is_finite() { x } else { 0.0 }
|
||||
}
|
||||
|
||||
/// One `(a - z⁻²) / (1 - a z⁻²)` allpass section.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
struct Section {
|
||||
x1: f64,
|
||||
x2: f64,
|
||||
y1: f64,
|
||||
y2: f64,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
/// One sample through the section: `y[n] = a (x[n] + y[n-2]) - x[n-2]`.
|
||||
#[inline]
|
||||
fn tick(&mut self, a: f64, x: f64) -> f64 {
|
||||
let y = flush64(a * (x + self.y2) - self.x2);
|
||||
self.x2 = self.x1;
|
||||
self.x1 = x;
|
||||
self.y2 = self.y1;
|
||||
self.y1 = y;
|
||||
y
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `x` through a chain of sections with the coefficients `coefs`.
|
||||
#[inline]
|
||||
fn chain(sections: &mut [Section; SECTIONS], coefs: &[f64; SECTIONS], x: f64) -> f64 {
|
||||
sections.iter_mut().zip(coefs.iter()).fold(x, |v, (s, &a)| s.tick(a, v))
|
||||
}
|
||||
|
||||
/// The state of one channel.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
struct Channel {
|
||||
in_phase: [Section; SECTIONS],
|
||||
quadrature: [Section; SECTIONS],
|
||||
/// The quadrature chain's input from the previous sample (its one-sample delay).
|
||||
delayed: f64,
|
||||
/// The previous wet output, fed back into the input.
|
||||
last: f64,
|
||||
}
|
||||
|
||||
/// Which sideband `channel` of `channels` keeps, as the weight of the quadrature product:
|
||||
/// `1` keeps the upper sideband, `-1` the lower one and `0` both at half level. The output is
|
||||
/// `i cos - s q sin`, so it is linear in `s`, and moving `s` smoothly from one mode's value to
|
||||
/// another's crossfades the two modes without a click.
|
||||
///
|
||||
/// Stereo shifts the left channel down and the right one up. Only a two-channel insert has a
|
||||
/// known left and right; a plugin is not told the speaker layout of a wider one (channel 1 is
|
||||
/// the centre in LCR and 5.1, the right in quad), so mono and multichannel inserts play both
|
||||
/// sidebands on every channel.
|
||||
fn sideband(mode: usize, channel: usize, channels: usize) -> f32 {
|
||||
match mode {
|
||||
MODE_DOWN => -1.0,
|
||||
MODE_BOTH => 0.0,
|
||||
MODE_STEREO if channels != 2 => 0.0,
|
||||
MODE_STEREO if channel == 0 => -1.0,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Single-sideband frequency shifter with feedback.
|
||||
///
|
||||
/// - **Up** adds Frequency to every component and **Down** subtracts it; a component that goes
|
||||
/// below 0 Hz comes back mirrored, and one pushed past Nyquist folds back from it.
|
||||
/// - **Up & Down** plays both sidebands at half level each (the in-phase signal times the
|
||||
/// carrier), which is a ring modulation without the quadrature chain's error.
|
||||
/// - **Stereo** shifts the left channel down and the right channel up (see [`sideband`]).
|
||||
/// - **Feedback** sends the shifted output back into the input, so a tone leaves a trail of
|
||||
/// components one more shift away each time, each `feedback` times the level of the last.
|
||||
///
|
||||
/// The phase difference is accurate to within a few millionths of a radian from 20 Hz to 20 Hz
|
||||
/// below Nyquist at 44.1 to 96 kHz, which leaves the unwanted sideband more than 100 dB down;
|
||||
/// below 20 Hz both sidebands come through. The plugin has no latency.
|
||||
///
|
||||
/// Frequency, Feedback and Mix glide to a new value over about 20 ms, and the carrier phase runs
|
||||
/// on, so a change does not click. A new Mode crossfades from the old sidebands in the same time.
|
||||
pub struct FreqShifter {
|
||||
p: Params,
|
||||
sr: f64,
|
||||
in_phase_coefs: [f64; SECTIONS],
|
||||
quadrature_coefs: [f64; SECTIONS],
|
||||
channels: Vec<Channel>,
|
||||
/// Carrier phase in cycles, in `[0, 1)`.
|
||||
phase: f64,
|
||||
freq: Smoother,
|
||||
feedback: Smoother,
|
||||
mix: Smoother,
|
||||
/// Each channel's sideband weight (see [`sideband`]).
|
||||
sides: Vec<Smoother>,
|
||||
tail: usize,
|
||||
}
|
||||
|
||||
impl Default for FreqShifter {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FreqShifter {
|
||||
/// A shifter with the default parameters and the network for the default rate; [`Plugin::prepare`]
|
||||
/// designs the network for the host rate.
|
||||
pub fn new() -> Self {
|
||||
let mut s = Self {
|
||||
p: Params::new(&FS_PARAMS),
|
||||
sr: f64::from(FALLBACK_SR),
|
||||
in_phase_coefs: [0.0; SECTIONS],
|
||||
quadrature_coefs: [0.0; SECTIONS],
|
||||
channels: Vec::new(),
|
||||
phase: 0.0,
|
||||
freq: Smoother::new(100.0),
|
||||
feedback: Smoother::new(0.0),
|
||||
mix: Smoother::new(1.0),
|
||||
sides: Vec::new(),
|
||||
tail: 0,
|
||||
};
|
||||
s.design();
|
||||
s.update();
|
||||
s
|
||||
}
|
||||
|
||||
/// Designs the network for `self.sr` and deals its coefficients out: even-numbered ones to the
|
||||
/// in-phase chain, odd-numbered ones to the quadrature chain.
|
||||
fn design(&mut self) {
|
||||
let coefs = quadrature_coefs(self.sr);
|
||||
for (i, a) in coefs.iter().enumerate() {
|
||||
let side = if i % 2 == 0 { &mut self.in_phase_coefs } else { &mut self.quadrature_coefs };
|
||||
if let Some(slot) = side.get_mut(i / 2) {
|
||||
*slot = *a;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Points the smoothers at the current parameter values, each channel's sideband weight at the
|
||||
/// current Mode, and works the tail out again. Runs on every parameter change.
|
||||
fn update(&mut self) {
|
||||
self.freq.set(self.p.v(0));
|
||||
self.feedback.set(self.p.v(2) / 100.0);
|
||||
self.mix.set(self.p.v(3) / 100.0);
|
||||
let (mode, channels) = (self.p.choice(1), self.sides.len());
|
||||
for (c, s) in self.sides.iter_mut().enumerate() {
|
||||
s.set(sideband(mode, c, channels));
|
||||
}
|
||||
self.tail = self.ring_samples();
|
||||
}
|
||||
|
||||
/// How long the network rings after an impulse until it falls below [`TAIL_FLOOR`], from its
|
||||
/// slowest pole (the section `a` closest to 1 decays by `a` every two samples), stretched by
|
||||
/// the feedback, which sends each pass through the network again.
|
||||
fn ring_samples(&self) -> usize {
|
||||
let slowest = self.in_phase_coefs.iter().chain(self.quadrature_coefs.iter()).fold(0.0f64, |m, &a| m.max(a));
|
||||
let ring = if slowest > 0.0 && slowest < 1.0 { 2.0 * TAIL_FLOOR.ln() / slowest.ln() } else { 0.0 };
|
||||
let fb = f64::from(self.p.v(2) / 100.0).clamp(0.0, 0.99);
|
||||
let n = (ring / (1.0 - fb)).ceil();
|
||||
if n.is_finite() && n > 0.0 { n.min(f64::from(u32::MAX)) as usize } else { 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Plugin for FreqShifter {
|
||||
param_plumbing!(FREQ_SHIFTER_INFO);
|
||||
|
||||
/// Designs the network for the host rate, sizes the per-channel state and starts from silence
|
||||
/// at the current parameters.
|
||||
fn prepare(&mut self, sample_rate: f32, _max_block: usize, channels: usize) {
|
||||
self.sr = f64::from(sane_sr(sample_rate));
|
||||
self.design();
|
||||
let channels = sane_channels(channels);
|
||||
self.channels = vec![Channel::default(); channels];
|
||||
self.sides = vec![Smoother::new(0.0); channels];
|
||||
let sr = self.sr as f32;
|
||||
for s in [&mut self.freq, &mut self.feedback, &mut self.mix].into_iter().chain(self.sides.iter_mut()) {
|
||||
s.set_time(20.0, sr);
|
||||
}
|
||||
self.update();
|
||||
self.reset();
|
||||
}
|
||||
|
||||
/// Clears the filter states and the carrier phase and snaps the smoothers to their targets, so
|
||||
/// the next block starts as a new plugin's would.
|
||||
fn reset(&mut self) {
|
||||
self.channels.iter_mut().for_each(|c| *c = Channel::default());
|
||||
self.phase = 0.0;
|
||||
for s in [&mut self.freq, &mut self.feedback, &mut self.mix].into_iter().chain(self.sides.iter_mut()) {
|
||||
s.snap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Shifts `frames` samples of each channel in place. One carrier and one set of smoothed
|
||||
/// parameters serve every channel; each channel has its own filters, feedback sample and
|
||||
/// sideband weight.
|
||||
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
|
||||
let ch = self.channels.len().min(io.len());
|
||||
let frames = frames_in(io, frames, ch);
|
||||
for n in 0..frames {
|
||||
let (sin, cos) = (TAU * self.phase).sin_cos();
|
||||
let step = f64::from(self.freq.next()) / self.sr;
|
||||
self.phase = (self.phase + step).fract();
|
||||
let fb = f64::from(self.feedback.next());
|
||||
let mix = self.mix.next();
|
||||
for c in 0..ch {
|
||||
let (Some(buf), Some(st), Some(side)) = (io.get_mut(c), self.channels.get_mut(c), self.sides.get_mut(c)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(x) = buf.get_mut(n) else { continue };
|
||||
let dry = if x.is_finite() { *x } else { 0.0 };
|
||||
let input = f64::from(dry) + fb * st.last;
|
||||
let i = chain(&mut st.in_phase, &self.in_phase_coefs, input);
|
||||
let q = chain(&mut st.quadrature, &self.quadrature_coefs, st.delayed);
|
||||
st.delayed = input;
|
||||
let wet = i * cos - f64::from(side.next()) * q * sin;
|
||||
st.last = flush64(wet);
|
||||
*x = dry * (1.0 - mix) + st.last as f32 * mix;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tail_samples(&self) -> usize {
|
||||
self.tail
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The in-phase and quadrature responses of the network at `f` cycles per sample.
|
||||
fn response(coefs: &[f64; 2 * SECTIONS], f: f64) -> ((f64, f64), (f64, f64)) {
|
||||
let mul = |(a, b): (f64, f64), (c, d): (f64, f64)| (a * c - b * d, a * d + b * c);
|
||||
let div = |(a, b): (f64, f64), (c, d): (f64, f64)| {
|
||||
let m = c * c + d * d;
|
||||
((a * c + b * d) / m, (b * c - a * d) / m)
|
||||
};
|
||||
// z⁻² = e^(-j 4π f)
|
||||
let z2 = ((2.0 * TAU * f).cos(), -(2.0 * TAU * f).sin());
|
||||
let mut paths = [(1.0, 0.0), (1.0, 0.0)];
|
||||
for (i, &a) in coefs.iter().enumerate() {
|
||||
let h = div((a - z2.0, -z2.1), (1.0 - a * z2.0, -a * z2.1));
|
||||
if let Some(p) = paths.get_mut(i % 2) {
|
||||
*p = mul(*p, h);
|
||||
}
|
||||
}
|
||||
let [i, q] = paths;
|
||||
(i, mul(q, ((TAU * f).cos(), -(TAU * f).sin())))
|
||||
}
|
||||
|
||||
/// The level of the unwanted sideband, in dB, for a phase error of `err` radians.
|
||||
fn image_db(err: f64) -> f64 {
|
||||
20.0 * (err / 2.0).abs().tan().max(1e-300).log10()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_is_ninety_degrees_across_the_band_at_every_rate() {
|
||||
// Worst unwanted sideband at each rate from 20 Hz to 20 Hz below Nyquist.
|
||||
for (sr, limit) in [(8_000.0, -140.0), (44_100.0, -110.0), (48_000.0, -110.0), (96_000.0, -100.0), (192_000.0, -90.0), (384_000.0, -85.0)] {
|
||||
let coefs = design_quadrature(sr).unwrap();
|
||||
let (lo, hi) = (QUADRATURE_LOW_HZ / sr, 0.5 - QUADRATURE_LOW_HZ / sr);
|
||||
let mut worst = f64::MIN;
|
||||
for k in 0..=4000 {
|
||||
let f = lo * (hi / lo).powf(k as f64 / 4000.0);
|
||||
let ((ir, ii), (qr, qi)) = response(&coefs, f);
|
||||
// Both chains are allpass: unit gain everywhere.
|
||||
assert!(((ir * ir + ii * ii).sqrt() - 1.0).abs() < 1e-9, "{sr} Hz rate: in-phase gain at {f}");
|
||||
assert!(((qr * qr + qi * qi).sqrt() - 1.0).abs() < 1e-9, "{sr} Hz rate: quadrature gain at {f}");
|
||||
// The quadrature chain lags the in-phase chain by 90°.
|
||||
let diff = qi.atan2(qr) - ii.atan2(ir);
|
||||
let diff = (diff + PI).rem_euclid(TAU) - PI;
|
||||
worst = worst.max(image_db(diff + PI / 2.0));
|
||||
}
|
||||
assert!(worst < limit, "{sr} Hz rate: unwanted sideband at {worst:.1} dB, limit {limit} dB");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_fails_outside_its_band_as_designed() {
|
||||
// At 5 Hz, a quarter of the lowest accurate frequency, the phase difference is far off 90°:
|
||||
// the band edge really is at 20 Hz, not somewhere lower by accident.
|
||||
let coefs = design_quadrature(48_000.0).unwrap();
|
||||
let ((ir, ii), (qr, qi)) = response(&coefs, 5.0 / 48_000.0);
|
||||
let diff = (qi.atan2(qr) - ii.atan2(ir) + PI).rem_euclid(TAU) - PI;
|
||||
assert!(image_db(diff + PI / 2.0) > -40.0, "5 Hz: {diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coefficients_exist_for_every_host_rate() {
|
||||
for sr in [1_000.0f32, 8_000.0, 22_050.0, 44_100.0, 48_000.0, 88_200.0, 176_400.0, 352_800.0, 768_000.0, 1_536_000.0] {
|
||||
let coefs = design_quadrature(f64::from(sr)).unwrap_or_else(|| panic!("no network at {sr}"));
|
||||
assert!(coefs.windows(2).all(|w| w[0] < w[1]), "{sr}: coefficients not increasing: {coefs:?}");
|
||||
}
|
||||
// Rates the design cannot serve fall back to the default network, never to nothing.
|
||||
assert_eq!(design_quadrature(100.0), None);
|
||||
assert_eq!(design_quadrature(f64::NAN), None);
|
||||
assert_eq!(quadrature_coefs(100.0), quadrature_coefs(48_000.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence_after_sound_flushes_the_filter_states() {
|
||||
let mut p = FreqShifter::new();
|
||||
p.prepare(48_000.0, 512, 2);
|
||||
let mut io = vec![vec![0.0f32; 512]; 2];
|
||||
io[0][0] = 1.0;
|
||||
io[1][0] = 1.0;
|
||||
p.process(&mut io, 512);
|
||||
for _ in 0..2_000 {
|
||||
let mut io = vec![vec![0.0f32; 512]; 2];
|
||||
p.process(&mut io, 512);
|
||||
}
|
||||
for c in &p.channels {
|
||||
for s in c.in_phase.iter().chain(c.quadrature.iter()) {
|
||||
for v in [s.x1, s.x2, s.y1, s.y2] {
|
||||
assert!(v == 0.0 || v.is_normal(), "state {v:e} is denormal");
|
||||
}
|
||||
}
|
||||
assert_eq!(c.last, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_mode_shifts_left_down_and_right_up_on_two_channels_only() {
|
||||
assert_eq!(sideband(MODE_STEREO, 0, 2), -1.0);
|
||||
assert_eq!(sideband(MODE_STEREO, 1, 2), 1.0);
|
||||
for channels in [1, 3, 4, 6, 16] {
|
||||
for c in 0..channels {
|
||||
assert_eq!(sideband(MODE_STEREO, c, channels), 0.0, "{c} of {channels}");
|
||||
}
|
||||
}
|
||||
for channels in [1, 2, 6] {
|
||||
for c in 0..channels {
|
||||
assert_eq!(sideband(0, c, channels), 1.0);
|
||||
assert_eq!(sideband(MODE_DOWN, c, channels), -1.0);
|
||||
assert_eq!(sideband(MODE_BOTH, c, channels), 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -631,15 +631,22 @@ fn lofi_quantizes() {
|
||||
assert!(levels.len() <= 5, "{levels:?}");
|
||||
}
|
||||
|
||||
fn ring_mod(params: &[(&str, f32)]) -> Box<dyn Plugin> {
|
||||
let mut p = prepared("ring_mod");
|
||||
for &(id, v) in params {
|
||||
assert!(p.set_param(id, v), "ring_mod.{id}");
|
||||
/// A plugin prepared at 48 kHz for `channels` channels with `params` set, then reset so the
|
||||
/// smoothers start at the new values.
|
||||
fn configured(id: &str, channels: usize, params: &[(&str, f32)]) -> Box<dyn Plugin> {
|
||||
let mut p = create(id).unwrap();
|
||||
p.prepare(SR, BLOCK, channels);
|
||||
for &(param, v) in params {
|
||||
assert!(p.set_param(param, v), "{id}.{param}");
|
||||
}
|
||||
p.reset();
|
||||
p
|
||||
}
|
||||
|
||||
fn ring_mod(params: &[(&str, f32)]) -> Box<dyn Plugin> {
|
||||
configured("ring_mod", 2, params)
|
||||
}
|
||||
|
||||
/// Loudest bin within two bins of `hz` in an 8192-point spectrum.
|
||||
fn band_db(spec: &[f32], hz: f32) -> f32 {
|
||||
let bin = (hz / (SR / 8192.0)).round() as usize;
|
||||
@@ -722,3 +729,227 @@ fn ring_mod_modulation_sources_move_the_frequency() {
|
||||
steps.dedup_by(|a, b| a.abs_diff(*b) <= 2);
|
||||
assert!(steps.len() >= 3, "sample and hold steps: {steps:?}");
|
||||
}
|
||||
|
||||
/// Amplitude of the whole-hertz tone `hz` in the one second of `x` that starts at `from`, sampled
|
||||
/// at `sr` (a whole number of hertz). Every whole-hertz tone completes whole cycles in that
|
||||
/// window, so the single-bin DFT measures each one exactly, without window leakage.
|
||||
fn tone_amplitude(x: &[f32], sr: usize, from: usize, hz: f64) -> f64 {
|
||||
let w = std::f64::consts::TAU * hz / sr as f64;
|
||||
let (re, im) = x[from..from + sr].iter().enumerate().fold((0.0f64, 0.0f64), |(re, im), (n, &v)| {
|
||||
let (s, c) = (w * n as f64).sin_cos();
|
||||
(re + f64::from(v) * c, im - f64::from(v) * s)
|
||||
});
|
||||
2.0 / sr as f64 * re.hypot(im)
|
||||
}
|
||||
|
||||
/// Asserts the levels of whole-hertz tones in the second second of `x` (the first lets the
|
||||
/// filters settle): each `(hz, amplitude)` within 0.001 dB, and each of `absent` at least
|
||||
/// 100 dB below `reference`.
|
||||
fn assert_tones(x: &[f32], sr: usize, tones: &[(f64, f64)], absent: &[f64], reference: f64, what: &str) {
|
||||
assert_tones_below(x, sr, tones, absent, reference, -100.0, what);
|
||||
}
|
||||
|
||||
/// [`assert_tones`] with the level `absent` tones must stay under, in dB relative to `reference`.
|
||||
fn assert_tones_below(x: &[f32], sr: usize, tones: &[(f64, f64)], absent: &[f64], reference: f64, limit_db: f64, what: &str) {
|
||||
for &(hz, want) in tones {
|
||||
let got = tone_amplitude(x, sr, sr, hz);
|
||||
let err_db = 20.0 * (got / want).log10();
|
||||
assert!(err_db.abs() < 0.001, "{what}: {hz} Hz at {got}, want {want} ({err_db:+.5} dB)");
|
||||
}
|
||||
for &hz in absent {
|
||||
let rel = 20.0 * (tone_amplitude(x, sr, sr, hz) / reference).log10();
|
||||
assert!(rel < limit_db, "{what}: {hz} Hz only {rel:.1} dB down, limit {limit_db} dB");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 0.5-amplitude sine at `hz` and `sr`, with the phase computed in `f64` so that rounding of
|
||||
/// a large `f32` phase does not add jitter sidebands to the measurements.
|
||||
fn pure_sine(hz: f64, sr: usize, len: usize) -> Vec<f32> {
|
||||
(0..len).map(|i| (0.5 * (std::f64::consts::TAU * hz * i as f64 / sr as f64).sin()) as f32).collect()
|
||||
}
|
||||
|
||||
fn freq_shifter(channels: usize, params: &[(&str, f32)]) -> Box<dyn Plugin> {
|
||||
configured("freq_shifter", channels, params)
|
||||
}
|
||||
|
||||
const FS_SR: usize = SR as usize;
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_moves_a_tone_up_or_down_by_the_frequency() {
|
||||
let x = pure_sine(1000.0, FS_SR, 2 * FS_SR);
|
||||
let mut up = freq_shifter(1, &[("frequency", 200.0), ("mode", 0.0)]);
|
||||
let out = run(up.as_mut(), std::slice::from_ref(&x));
|
||||
assert_tones(&out[0], FS_SR, &[(1200.0, 0.5)], &[800.0, 1000.0, 1400.0], 0.5, "up 200 Hz");
|
||||
|
||||
let mut down = freq_shifter(1, &[("frequency", 200.0), ("mode", 1.0)]);
|
||||
let out = run(down.as_mut(), std::slice::from_ref(&x));
|
||||
assert_tones(&out[0], FS_SR, &[(800.0, 0.5)], &[600.0, 1000.0, 1200.0], 0.5, "down 200 Hz");
|
||||
|
||||
// A component pushed below 0 Hz comes back mirrored: 200 Hz down by 300 Hz is 100 Hz.
|
||||
let low = pure_sine(200.0, FS_SR, 2 * FS_SR);
|
||||
let mut p = freq_shifter(1, &[("frequency", 300.0), ("mode", 1.0)]);
|
||||
let out = run(p.as_mut(), &[low]);
|
||||
assert_tones(&out[0], FS_SR, &[(100.0, 0.5)], &[200.0, 500.0], 0.5, "down past 0 Hz");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_up_and_down_and_stereo_modes() {
|
||||
let x = pure_sine(1000.0, FS_SR, 2 * FS_SR);
|
||||
// Up & Down: both sidebands at half level, nothing left at the input frequency.
|
||||
let mut p = freq_shifter(2, &[("frequency", 150.0), ("mode", 2.0)]);
|
||||
let out = run(p.as_mut(), &[x.clone(), x.clone()]);
|
||||
for c in &out {
|
||||
assert_tones(c, FS_SR, &[(850.0, 0.25), (1150.0, 0.25)], &[1000.0], 0.25, "up & down");
|
||||
}
|
||||
|
||||
// Stereo: the left channel goes down and the right channel up.
|
||||
let mut p = freq_shifter(2, &[("frequency", 150.0), ("mode", 3.0)]);
|
||||
let out = run(p.as_mut(), &[x.clone(), x.clone()]);
|
||||
assert_tones(&out[0], FS_SR, &[(850.0, 0.5)], &[1000.0, 1150.0], 0.5, "stereo left");
|
||||
assert_tones(&out[1], FS_SR, &[(1150.0, 0.5)], &[850.0, 1000.0], 0.5, "stereo right");
|
||||
|
||||
// A mono insert has no sides, so Stereo plays both sidebands, like Up & Down.
|
||||
let mut p = freq_shifter(1, &[("frequency", 150.0), ("mode", 3.0)]);
|
||||
let out = run(p.as_mut(), std::slice::from_ref(&x));
|
||||
assert_tones(&out[0], FS_SR, &[(850.0, 0.25), (1150.0, 0.25)], &[1000.0], 0.25, "stereo on mono");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_feedback_adds_one_more_shift_per_pass() {
|
||||
// Each pass through the loop shifts again and scales by the feedback: 1.2, 1.4, 1.6 and 1.8 kHz
|
||||
// at 1/2, 1/4, 1/8 and 1/16.
|
||||
let x = pure_sine(1000.0, FS_SR, 2 * FS_SR);
|
||||
let mut p = freq_shifter(1, &[("frequency", 200.0), ("feedback", 50.0)]);
|
||||
let out = run(p.as_mut(), &[x]);
|
||||
let trail = [(1200.0, 0.5), (1400.0, 0.25), (1600.0, 0.125), (1800.0, 0.0625)];
|
||||
assert_tones(&out[0], FS_SR, &trail, &[800.0, 1000.0], 0.5, "feedback 50 %");
|
||||
// Feedback stops at 70 %, the most the loop is proven stable with.
|
||||
assert!(p.set_param("feedback", 100.0));
|
||||
assert_eq!(p.param("feedback"), Some(70.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_mix_blends_the_dry_input() {
|
||||
let x = pure_sine(1000.0, FS_SR, 2 * FS_SR);
|
||||
let mut p = freq_shifter(1, &[("frequency", 200.0), ("mix", 50.0)]);
|
||||
let out = run(p.as_mut(), &[x]);
|
||||
assert_tones(&out[0], FS_SR, &[(1000.0, 0.25), (1200.0, 0.25)], &[800.0], 0.25, "mix 50 %");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_is_accurate_near_both_band_edges() {
|
||||
// 44.1 kHz: a 40 Hz tone up by 10 Hz, and a 20 kHz tone down by 1 kHz.
|
||||
let sr = 44_100usize;
|
||||
for (from, by, mode, to, image) in [(40.0f32, 10.0f32, 0.0f32, 50.0, 30.0), (20_000.0, 1_000.0, 1.0, 19_000.0, 21_000.0)] {
|
||||
let mut p = create("freq_shifter").unwrap();
|
||||
p.prepare(sr as f32, BLOCK, 1);
|
||||
p.set_param("frequency", by);
|
||||
p.set_param("mode", mode);
|
||||
p.reset();
|
||||
let x = pure_sine(f64::from(from), sr, 2 * sr);
|
||||
let out = run(p.as_mut(), &[x]);
|
||||
assert_tones(&out[0], sr, &[(to, 0.5)], &[image, f64::from(from)], 0.5, &format!("{from} Hz by {by} Hz"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_output_does_not_depend_on_the_block_size_and_reset_restarts_it() {
|
||||
let x = pure_sine(440.0, FS_SR, 6000);
|
||||
let params = [("frequency", 37.0), ("mode", 3.0), ("feedback", 60.0), ("mix", 80.0)];
|
||||
let mut p = freq_shifter(2, ¶ms);
|
||||
let whole = run(p.as_mut(), &[x.clone(), x.clone()]);
|
||||
let mut one = freq_shifter(2, ¶ms);
|
||||
let mut by_sample = vec![Vec::new(), Vec::new()];
|
||||
for &v in &x {
|
||||
let mut buf = vec![vec![v], vec![v]];
|
||||
one.process(&mut buf, 1);
|
||||
by_sample[0].push(buf[0][0]);
|
||||
by_sample[1].push(buf[1][0]);
|
||||
}
|
||||
assert_eq!(whole, by_sample);
|
||||
p.reset();
|
||||
assert_eq!(run(p.as_mut(), &[x.clone(), x]), whole);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_tail_covers_the_ringing() {
|
||||
for feedback in [0.0, 70.0] {
|
||||
let mut p = freq_shifter(1, &[("frequency", 5.0), ("feedback", feedback)]);
|
||||
let mut x = vec![0.0f32; 4 * FS_SR];
|
||||
x[0] = 1.0;
|
||||
let out = run(p.as_mut(), &[x]);
|
||||
let last = out[0].iter().rposition(|v| v.abs() > 1e-4).unwrap();
|
||||
assert!(last < p.tail_samples(), "feedback {feedback}: ringing at {last}, tail {}", p.tail_samples());
|
||||
}
|
||||
}
|
||||
|
||||
/// A plugin prepared at `sr` for `channels` channels with `params` set, then reset.
|
||||
fn freq_shifter_at(sr: usize, channels: usize, params: &[(&str, f32)]) -> Box<dyn Plugin> {
|
||||
let mut p = create("freq_shifter").unwrap();
|
||||
p.prepare(sr as f32, BLOCK, channels);
|
||||
for &(param, v) in params {
|
||||
assert!(p.set_param(param, v), "freq_shifter.{param}");
|
||||
}
|
||||
p.reset();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_rejects_the_image_at_every_common_rate() {
|
||||
// A 1 kHz tone shifted up and down by 200 Hz: the shifted tone at full level within 0.001 dB,
|
||||
// and the other sideband and the input at least 100 dB down up to 96 kHz and 95 dB at 192 kHz
|
||||
// (the 20 Hz band edge is a smaller fraction of a higher rate).
|
||||
for (sr, limit) in [(22_050, -100.0), (44_100, -100.0), (48_000, -100.0), (88_200, -100.0), (96_000, -100.0), (192_000, -95.0)] {
|
||||
let x = pure_sine(1000.0, sr, 2 * sr);
|
||||
for (mode, to, image) in [(0.0, 1200.0, 800.0), (1.0, 800.0, 1200.0)] {
|
||||
let mut p = freq_shifter_at(sr, 1, &[("frequency", 200.0), ("mode", mode)]);
|
||||
let out = run(p.as_mut(), std::slice::from_ref(&x));
|
||||
assert_tones_below(&out[0], sr, &[(to, 0.5)], &[image, 1000.0], 0.5, limit, &format!("{sr} Hz, mode {mode}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_processes_every_channel_of_a_multichannel_insert() {
|
||||
// A 5.1-wide insert: Up shifts all six channels. Stereo needs a known left and right, which only
|
||||
// a two-channel insert has, so on six channels it plays both sidebands everywhere.
|
||||
let x = pure_sine(1000.0, FS_SR, 2 * FS_SR);
|
||||
let input = vec![x; 6];
|
||||
let mut p = freq_shifter(6, &[("frequency", 150.0), ("mode", 0.0)]);
|
||||
for (c, out) in run(p.as_mut(), &input).iter().enumerate() {
|
||||
assert_tones(out, FS_SR, &[(1150.0, 0.5)], &[850.0, 1000.0], 0.5, &format!("up, channel {c}"));
|
||||
}
|
||||
let mut p = freq_shifter(6, &[("frequency", 150.0), ("mode", 3.0)]);
|
||||
for (c, out) in run(p.as_mut(), &input).iter().enumerate() {
|
||||
assert_tones(out, FS_SR, &[(850.0, 0.25), (1150.0, 0.25)], &[1000.0], 0.25, &format!("stereo, channel {c}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest change between two neighbouring samples of `x`.
|
||||
fn max_step(x: &[f32]) -> f32 {
|
||||
x.windows(2).fold(0.0f32, |m, w| m.max((w[1] - w[0]).abs()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freq_shifter_parameter_changes_do_not_click() {
|
||||
// Each change lands mid-block on a running 1 kHz sine, a quarter of a 200 Hz carrier cycle
|
||||
// after a whole one, where its sine is at its peak and an instant sideband switch would jump
|
||||
// the furthest. Across the change, no step between two samples may be more than 5 % larger
|
||||
// than the largest step of the settled output before or after it.
|
||||
const AT: usize = 24_060;
|
||||
let x = sine(1000.0, 0.5, 48_000);
|
||||
let changes =
|
||||
[("mode", 0.0, 1.0), ("mode", 1.0, 3.0), ("mode", 3.0, 2.0), ("frequency", 200.0, 4000.0), ("mix", 100.0, 0.0), ("feedback", 0.0, 70.0)];
|
||||
for (id, from, to) in changes {
|
||||
let mut p = freq_shifter(2, &[("frequency", 200.0), (id, from)]);
|
||||
let before = run(p.as_mut(), &[x[..AT].to_vec(), x[..AT].to_vec()]);
|
||||
assert!(p.set_param(id, to));
|
||||
let after = run(p.as_mut(), &[x[AT..].to_vec(), x[AT..].to_vec()]);
|
||||
for c in 0..2 {
|
||||
let limit = 1.05 * max_step(&before[c][12_000..]).max(max_step(&after[c][12_000..]));
|
||||
let across: Vec<f32> = before[c][12_000..].iter().chain(&after[c][..12_000]).copied().collect();
|
||||
let step = max_step(&across);
|
||||
assert!(step <= limit, "{id} {from} -> {to}, channel {c}: step {step}, limit {limit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-score.workspace = true
|
||||
craft-xml.workspace = true
|
||||
soundcraft-time.workspace = true
|
||||
craft-audio.workspace = true
|
||||
craft-scraft-format.workspace = true
|
||||
|
||||
@@ -150,10 +150,7 @@ fn process(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
nc.gain_db = 0.0;
|
||||
nc.gain_env.clear();
|
||||
}
|
||||
if let Some(pl) = s.track_mut(track).and_then(|t| t.playlist_mut()) {
|
||||
pl.clips.retain(|c| c.id != id);
|
||||
}
|
||||
crate::edit::place_clip(s, track, nc);
|
||||
super::more_util::replace_clip(s, track, id, nc);
|
||||
done += 1;
|
||||
}
|
||||
Ok(json!({"processed": done, "process": name}))
|
||||
|
||||
@@ -186,12 +186,35 @@ pub fn render_stretched(s: &mut Session, cmd: &str, c: &Clip, out_len: Samples)
|
||||
Ok(Some(crate::io::add_source(s, &format!("{}-TCE", c.name), buf, None, FileFormat::Wav)))
|
||||
}
|
||||
|
||||
/// Replace clip `old` on track `t` with `new` (overwriting whatever `new` covers).
|
||||
/// Replace clip `old` on track `t` with `new`, overwriting whatever `new` covers, except a clip that
|
||||
/// overlapped `old` across one edge that `new` does not reach past: the other half of a crossfade keeps
|
||||
/// its overlap and its fade, so processing a clip in place does not turn the crossfade into a dip.
|
||||
pub fn replace_clip(s: &mut Session, t: TrackId, old: soundcraft_model::ClipId, new: Clip) {
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.retain(|c| c.id != old);
|
||||
}
|
||||
let kept: Vec<Clip> = match s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
Some(pl) => {
|
||||
let was = pl.clips.iter().find(|c| c.id == old).map(Clip::range);
|
||||
let to = new.range();
|
||||
// The other half of a crossfade: it overlaps `old` across one edge only, starting before `old` and ending
|
||||
// inside it, or starting inside it and ending after it, and `new` does not reach past that edge. A clip
|
||||
// inside `old`, or covering all of it, shares no crossfade with it and is overwritten as usual.
|
||||
let keep = |c: &Clip| {
|
||||
was.is_some_and(|w| {
|
||||
let earlier = c.start < w.start && c.end() < w.end && to.start >= w.start;
|
||||
let later = c.start > w.start && c.end() > w.end && to.end <= w.end;
|
||||
c.range().intersect(&w).is_some() && (earlier || later)
|
||||
})
|
||||
};
|
||||
let (kept, rest) = std::mem::take(&mut pl.clips).into_iter().filter(|c| c.id != old).partition(keep);
|
||||
pl.clips = rest;
|
||||
kept
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
crate::edit::place_clip(s, t, new);
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.extend(kept);
|
||||
pl.sort();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+178
-414
@@ -1,19 +1,20 @@
|
||||
//! Notation: MIDI tracks laid out as measures of notes and rests, written as MusicXML
|
||||
//! (File › Export › Sibelius, File › Send To › Sibelius) or engraved to SVG (File › Print Score).
|
||||
//!
|
||||
//! Notes are quantized to sixteenths. Each part is a single voice: notes that start together form
|
||||
//! a chord, overlapping notes are cut at the next onset, and anything crossing a bar line is split
|
||||
//! and tied.
|
||||
//! Notes are quantized to sixteenths. Each part is a sequence of chords split at note onsets,
|
||||
//! note ends and bar lines. Per-pitch ties preserve the duration of each note, including
|
||||
//! overlapping notes. A chord keeps at most [`MAX_PITCHES_PER_CHORD`] pitches.
|
||||
|
||||
pub use craft_score::{Item, Measure, Part};
|
||||
use soundcraft_model::{ClipContent, Session, TrackId, TrackKind};
|
||||
use soundcraft_time::TICKS_PER_QUARTER;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// Ticks per score unit (a sixteenth).
|
||||
const UNIT: i64 = TICKS_PER_QUARTER / 4;
|
||||
/// Upper bound on engraved measures, so a hostile session cannot make a huge document.
|
||||
const MAX_MEASURES: usize = 2000;
|
||||
/// Upper bound on output size, so a hostile session cannot make a huge document.
|
||||
#[cfg(test)]
|
||||
const MAX_OUTPUT_BYTES: usize = 256 * 1024 * 1024; // 256 MiB
|
||||
/// Upper bound on items per measure, so a hostile session cannot make a huge document.
|
||||
const MAX_ITEMS_PER_MEASURE: usize = 128;
|
||||
@@ -25,14 +26,6 @@ const MAX_NOTES_PER_PART: usize = 100_000;
|
||||
/// Note values a single notehead can show, in sixteenths (longest first).
|
||||
const VALUES: [u32; 8] = [16, 12, 8, 6, 4, 3, 2, 1];
|
||||
|
||||
/// The output has grown past the byte budget: refuse to grow it further.
|
||||
fn over_budget(buf: &str, budget: usize) -> Result<(), String> {
|
||||
if buf.len() > budget {
|
||||
return Err(format!("score too large: over {} bytes", budget));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Score Setup (File › Score Setup…). Stored in the session's edit flags/values.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ScoreSetup {
|
||||
@@ -67,32 +60,6 @@ impl ScoreSetup {
|
||||
}
|
||||
}
|
||||
|
||||
/// One measure: its meter and its items (notes, chords or rests), in sixteenths.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Measure {
|
||||
pub numerator: u32,
|
||||
pub denominator: u32,
|
||||
pub items: Vec<Item>,
|
||||
}
|
||||
|
||||
/// A notehead group (chord) or a rest (no pitches).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Item {
|
||||
pub pitches: Vec<u8>,
|
||||
/// Duration in sixteenths; always one of [`VALUES`].
|
||||
pub units: u32,
|
||||
pub tie_start: bool,
|
||||
pub tie_stop: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Part {
|
||||
pub name: String,
|
||||
/// True when the part reads best in bass clef.
|
||||
pub bass: bool,
|
||||
pub measures: Vec<Measure>,
|
||||
}
|
||||
|
||||
/// Lay out the MIDI (and instrument) tracks `tracks` (all of them when empty).
|
||||
pub fn layout(s: &Session, tracks: &[TrackId]) -> Vec<Part> {
|
||||
let sr = s.sample_rate;
|
||||
@@ -179,70 +146,106 @@ fn split_units(mut units: i64) -> Vec<u32> {
|
||||
}
|
||||
|
||||
fn fill(bars: &[(i64, i64, u32, u32)], notes: &[(i64, i64, u8)]) -> Vec<Measure> {
|
||||
// Onsets → chords, each held until its longest *retained* note ends or the next onset. A pitch
|
||||
// the cap rejects must not extend the onset end.
|
||||
let mut onsets: std::collections::BTreeMap<i64, (i64, Vec<u8>)> = std::collections::BTreeMap::new();
|
||||
for (a, b, p) in notes {
|
||||
let (ends, pitches) = onsets.entry(*a).or_insert((*b, Vec::new()));
|
||||
let new_pitch = !pitches.contains(p);
|
||||
if new_pitch && pitches.len() >= MAX_PITCHES_PER_CHORD {
|
||||
// Chord full and this pitch is absent: it is dropped and must not extend the onset end.
|
||||
#[derive(Default)]
|
||||
struct Events {
|
||||
starts: Vec<(usize, u8)>,
|
||||
ends: Vec<(usize, u8)>,
|
||||
}
|
||||
let limit = bars.last().map_or(0, |(start, length, _, _)| start.saturating_add(*length));
|
||||
let mut events: std::collections::BTreeMap<i64, Events> = std::collections::BTreeMap::new();
|
||||
for (id, &(a, b, pitch)) in notes.iter().enumerate() {
|
||||
if a >= b || a >= limit || b <= 0 || pitch > 127 {
|
||||
continue;
|
||||
}
|
||||
// A retained pitch (already in the chord, or one the cap accepts) may extend the onset
|
||||
// end, even when it reappears with a longer duration.
|
||||
*ends = (*ends).max(*b);
|
||||
if new_pitch {
|
||||
pitches.push(*p);
|
||||
}
|
||||
events.entry(a.max(0)).or_default().starts.push((id, pitch));
|
||||
events.entry(b.min(limit)).or_default().ends.push((id, pitch));
|
||||
}
|
||||
let starts: Vec<i64> = onsets.keys().copied().collect();
|
||||
let mut spans: Vec<(i64, i64, Vec<u8>)> = Vec::new();
|
||||
for (i, (a, (b, mut ps))) in onsets.into_iter().enumerate() {
|
||||
let end = starts.get(i + 1).map_or(b, |n| b.min(*n));
|
||||
ps.sort_unstable();
|
||||
spans.push((a, end, ps));
|
||||
let events: Vec<_> = events.into_iter().collect();
|
||||
// Only admitted notes may end activity; rejected starts must not silence later notes.
|
||||
let mut admitted = std::collections::BTreeSet::new();
|
||||
let mut active = [0usize; 128];
|
||||
let mut spans = Vec::new();
|
||||
for pair in events.windows(2) {
|
||||
let [(from, ev), (to, next)] = pair else { continue };
|
||||
for (id, pitch) in &ev.ends {
|
||||
if !admitted.remove(id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(count) = active.get_mut(usize::from(*pitch)) {
|
||||
*count = count.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
let tied_in: Vec<u8> = active
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(p, n)| **n > 0 && !ev.starts.iter().any(|(_, pitch)| *pitch == *p as u8))
|
||||
.map(|(p, _)| p as u8)
|
||||
.collect();
|
||||
for (id, pitch) in &ev.starts {
|
||||
let idx = usize::from(*pitch);
|
||||
if active[idx] == 0 && active.iter().filter(|n| **n > 0).count() >= MAX_PITCHES_PER_CHORD {
|
||||
continue;
|
||||
}
|
||||
admitted.insert(*id);
|
||||
active[idx] = active[idx].saturating_add(1);
|
||||
}
|
||||
let pitches: Vec<u8> = active.iter().enumerate().filter(|(_, n)| **n > 0).map(|(p, _)| p as u8).collect();
|
||||
let mut ending = [0usize; 128];
|
||||
for (id, pitch) in &next.ends {
|
||||
if !admitted.contains(id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(count) = ending.get_mut(usize::from(*pitch)) {
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
let tied_out: Vec<u8> = pitches
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|p| {
|
||||
active.get(usize::from(*p)).zip(ending.get(usize::from(*p))).is_some_and(|(a, b)| a > b)
|
||||
&& !next.starts.iter().any(|(_, pitch)| pitch == p)
|
||||
})
|
||||
.collect();
|
||||
if !pitches.is_empty() {
|
||||
spans.push((*from, *to, pitches, tied_in, tied_out));
|
||||
}
|
||||
}
|
||||
let mut measures = Vec::new();
|
||||
for (ms, ml, num, den) in bars {
|
||||
let me = ms + ml;
|
||||
let mut items = Vec::new();
|
||||
let mut cursor = *ms;
|
||||
let emit = |from: i64, to: i64, pitches: &[u8], tied_in: bool, tied_out: bool, items: &mut Vec<Item>| {
|
||||
let emit = |from: i64, to: i64, pitches: &[u8], tied_in: &[u8], tied_out: &[u8], items: &mut Vec<Item>| {
|
||||
let parts = split_units(to - from);
|
||||
let n = parts.len();
|
||||
for (k, u) in parts.into_iter().enumerate() {
|
||||
let rest = pitches.is_empty();
|
||||
items.push(Item {
|
||||
pitches: pitches.to_vec(),
|
||||
units: u,
|
||||
tie_stop: !rest && (tied_in || k > 0),
|
||||
tie_start: !rest && (tied_out || k + 1 < n),
|
||||
tie_stop: pitches.iter().copied().filter(|p| k > 0 || tied_in.contains(p)).collect(),
|
||||
tie_start: pitches.iter().copied().filter(|p| k + 1 < n || tied_out.contains(p)).collect(),
|
||||
});
|
||||
}
|
||||
};
|
||||
for (a, b, ps) in spans.iter().filter(|(a, b, _)| *b > *ms && *a < me) {
|
||||
for (a, b, ps, tied_in, tied_out) in spans.iter().filter(|(a, b, ..)| *b > *ms && *a < me) {
|
||||
let from = (*a).max(*ms).max(cursor);
|
||||
let to = (*b).min(me);
|
||||
if to <= from {
|
||||
continue;
|
||||
}
|
||||
if from > cursor {
|
||||
emit(cursor, from, &[], false, false, &mut items);
|
||||
emit(cursor, from, &[], &[], &[], &mut items);
|
||||
}
|
||||
emit(from, to, ps, *a < *ms, *b > me, &mut items);
|
||||
emit(from, to, ps, if from > *a { ps } else { tied_in }, if to < *b { ps } else { tied_out }, &mut items);
|
||||
cursor = to;
|
||||
// Cap items per measure to avoid pathological memory use.
|
||||
if items.len() > MAX_ITEMS_PER_MEASURE {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if cursor < me {
|
||||
emit(cursor, me, &[], false, false, &mut items);
|
||||
if cursor < me && items.len() <= MAX_ITEMS_PER_MEASURE {
|
||||
emit(cursor, me, &[], &[], &[], &mut items);
|
||||
}
|
||||
// Cap the item count without shortening the measure: whatever suffix the cap discards is
|
||||
// replaced with representable rests, so the bar's duration (and the SVG layout denominator)
|
||||
// stays right. Shrinking the item list further makes room for those rests.
|
||||
if items.len() > MAX_ITEMS_PER_MEASURE {
|
||||
let bar_len = me.saturating_sub(*ms);
|
||||
let mut keep = MAX_ITEMS_PER_MEASURE;
|
||||
@@ -251,12 +254,11 @@ fn fill(bars: &[(i64, i64, u32, u32)], notes: &[(i64, i64, u8)]) -> Vec<Measure>
|
||||
let rests = split_units(bar_len.saturating_sub(kept));
|
||||
if keep.saturating_add(rests.len()) <= MAX_ITEMS_PER_MEASURE || keep == 0 {
|
||||
items.truncate(keep);
|
||||
items.extend(rests.into_iter().map(|units| Item { pitches: Vec::new(), units, tie_start: false, tie_stop: false }));
|
||||
items.extend(rests.into_iter().map(|units| Item { pitches: Vec::new(), units, tie_start: Vec::new(), tie_stop: Vec::new() }));
|
||||
break;
|
||||
}
|
||||
keep -= 1;
|
||||
}
|
||||
// Safety net for a hostile meter so wide that even whole-bar rests exceed the cap.
|
||||
items.truncate(MAX_ITEMS_PER_MEASURE);
|
||||
}
|
||||
measures.push(Measure { numerator: *num, denominator: *den, items });
|
||||
@@ -265,351 +267,122 @@ fn fill(bars: &[(i64, i64, u32, u32)], notes: &[(i64, i64, u8)]) -> Vec<Measure>
|
||||
}
|
||||
|
||||
/// (step, alter, octave) spelled with sharps.
|
||||
fn spell(pitch: u8) -> (char, i32, i32) {
|
||||
const STEPS: [(char, i32); 12] =
|
||||
[('C', 0), ('C', 1), ('D', 0), ('D', 1), ('E', 0), ('F', 0), ('F', 1), ('G', 0), ('G', 1), ('A', 0), ('A', 1), ('B', 0)];
|
||||
let (step, alter) = STEPS[usize::from(pitch % 12)];
|
||||
(step, alter, i32::from(pitch / 12) - 1)
|
||||
}
|
||||
|
||||
fn xml_escape(s: &str) -> String {
|
||||
s.chars()
|
||||
.filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}'))
|
||||
.collect::<String>()
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
}
|
||||
|
||||
fn note_type(units: u32) -> (&'static str, bool) {
|
||||
match units {
|
||||
16 => ("whole", false),
|
||||
12 => ("half", true),
|
||||
8 => ("half", false),
|
||||
6 => ("quarter", true),
|
||||
4 => ("quarter", false),
|
||||
3 => ("eighth", true),
|
||||
2 => ("eighth", false),
|
||||
_ => ("16th", false),
|
||||
fn shared_setup(setup: &ScoreSetup) -> craft_score::ScoreSetup {
|
||||
craft_score::ScoreSetup {
|
||||
software: "SoundCraft".into(),
|
||||
title: setup.title.clone(),
|
||||
composer: setup.composer.clone(),
|
||||
bars_per_system: setup.bars_per_system,
|
||||
show_track_names: setup.show_track_names,
|
||||
}
|
||||
}
|
||||
|
||||
/// MusicXML 4.0 (partwise) for `parts`.
|
||||
/// MusicXML 4.0 (partwise), written by the shared score serializer.
|
||||
pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result<String, String> {
|
||||
musicxml_budgeted(parts, setup, MAX_OUTPUT_BYTES)
|
||||
craft_score::musicxml(parts, &shared_setup(setup))
|
||||
}
|
||||
|
||||
/// [`musicxml`] with an explicit byte budget (kept separate so tests can pass a tiny budget
|
||||
/// instead of building a 256 MiB score).
|
||||
fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result<String, String> {
|
||||
let mut x = String::new();
|
||||
x.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
|
||||
x.push_str("<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 4.0 Partwise//EN\" \"http://www.musicxml.org/dtds/partwise.dtd\">\n");
|
||||
x.push_str("<score-partwise version=\"4.0\">\n");
|
||||
// The header (and an oversized title/composer, escaped) can itself exceed the budget even with
|
||||
// no measures, so check before the per-measure loop too.
|
||||
over_budget(&x, budget)?;
|
||||
let _ = writeln!(x, " <work><work-title>{}</work-title></work>", xml_escape(&setup.title));
|
||||
x.push_str(" <identification>\n");
|
||||
if !setup.composer.is_empty() {
|
||||
let _ = writeln!(x, " <creator type=\"composer\">{}</creator>", xml_escape(&setup.composer));
|
||||
}
|
||||
x.push_str(" <encoding><software>SoundCraft</software></encoding>\n </identification>\n <part-list>\n");
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
let _ = writeln!(x, " <score-part id=\"P{}\"><part-name>{}</part-name></score-part>", i + 1, xml_escape(&p.name));
|
||||
}
|
||||
x.push_str(" </part-list>\n");
|
||||
over_budget(&x, budget)?;
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
let _ = writeln!(x, " <part id=\"P{}\">", i + 1);
|
||||
let mut meter = (0, 0);
|
||||
for (mi, m) in p.measures.iter().enumerate() {
|
||||
let _ = writeln!(x, " <measure number=\"{}\">", mi + 1);
|
||||
if mi == 0 || meter != (m.numerator, m.denominator) {
|
||||
x.push_str(" <attributes>");
|
||||
if mi == 0 {
|
||||
x.push_str("<divisions>4</divisions><key><fifths>0</fifths></key>");
|
||||
}
|
||||
let _ = write!(x, "<time><beats>{}</beats><beat-type>{}</beat-type></time>", m.numerator, m.denominator);
|
||||
if mi == 0 {
|
||||
x.push_str(if p.bass { "<clef><sign>F</sign><line>4</line></clef>" } else { "<clef><sign>G</sign><line>2</line></clef>" });
|
||||
}
|
||||
x.push_str("</attributes>\n");
|
||||
meter = (m.numerator, m.denominator);
|
||||
}
|
||||
for it in &m.items {
|
||||
let (ty, dot) = note_type(it.units);
|
||||
if it.pitches.is_empty() {
|
||||
let _ = writeln!(
|
||||
x,
|
||||
" <note><rest/><duration>{}</duration><voice>1</voice><type>{ty}</type>{}</note>",
|
||||
it.units,
|
||||
if dot { "<dot/>" } else { "" }
|
||||
);
|
||||
continue;
|
||||
}
|
||||
for (k, pitch) in it.pitches.iter().enumerate() {
|
||||
let (step, alter, octave) = spell(*pitch);
|
||||
x.push_str(" <note>");
|
||||
if k > 0 {
|
||||
x.push_str("<chord/>");
|
||||
}
|
||||
let _ = write!(x, "<pitch><step>{step}</step>");
|
||||
if alter != 0 {
|
||||
let _ = write!(x, "<alter>{alter}</alter>");
|
||||
}
|
||||
let _ = write!(x, "<octave>{octave}</octave></pitch><duration>{}</duration>", it.units);
|
||||
if it.tie_stop {
|
||||
x.push_str("<tie type=\"stop\"/>");
|
||||
}
|
||||
if it.tie_start {
|
||||
x.push_str("<tie type=\"start\"/>");
|
||||
}
|
||||
let _ = write!(x, "<voice>1</voice><type>{ty}</type>");
|
||||
if dot {
|
||||
x.push_str("<dot/>");
|
||||
}
|
||||
if alter != 0 {
|
||||
x.push_str("<accidental>sharp</accidental>");
|
||||
}
|
||||
if it.tie_stop || it.tie_start {
|
||||
x.push_str("<notations>");
|
||||
if it.tie_stop {
|
||||
x.push_str("<tied type=\"stop\"/>");
|
||||
}
|
||||
if it.tie_start {
|
||||
x.push_str("<tied type=\"start\"/>");
|
||||
}
|
||||
x.push_str("</notations>");
|
||||
}
|
||||
x.push_str("</note>\n");
|
||||
}
|
||||
}
|
||||
x.push_str(" </measure>\n");
|
||||
over_budget(&x, budget)?;
|
||||
}
|
||||
x.push_str(" </part>\n");
|
||||
}
|
||||
x.push_str("</score-partwise>\n");
|
||||
over_budget(&x, budget)?;
|
||||
Ok(x)
|
||||
}
|
||||
|
||||
/// Staff position of `pitch` in half-spaces above the bottom line (treble E4 / bass G2).
|
||||
fn staff_step(pitch: u8, bass: bool) -> i32 {
|
||||
let (step, _, octave) = spell(pitch);
|
||||
let idx = "CDEFGAB".find(step).map_or(0, |i| i as i32);
|
||||
let diatonic = octave * 7 + idx;
|
||||
diatonic - if bass { 2 * 7 + 4 } else { 4 * 7 + 2 }
|
||||
}
|
||||
|
||||
/// An engraved score as a printable SVG page (A4 portrait width, as tall as needed).
|
||||
/// A printable SVG page, written by the shared score serializer.
|
||||
pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result<String, String> {
|
||||
svg_budgeted(parts, setup, MAX_OUTPUT_BYTES)
|
||||
craft_score::svg(parts, &shared_setup(setup))
|
||||
}
|
||||
|
||||
/// [`svg`] with an explicit byte budget (kept separate so tests can pass a tiny budget instead of
|
||||
/// building a 256 MiB score).
|
||||
#[cfg(test)]
|
||||
fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result<String, String> {
|
||||
craft_score::musicxml_budgeted(parts, &shared_setup(setup), budget)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result<String, String> {
|
||||
const W: f64 = 794.0;
|
||||
const MARGIN: f64 = 48.0;
|
||||
const SP: f64 = 7.0; // staff space
|
||||
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);
|
||||
// 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;
|
||||
let staff_x1 = W - MARGIN;
|
||||
let sys_h = parts.len().max(1) as f64 * STAFF_GAP + SYSTEM_GAP;
|
||||
let top = 110.0;
|
||||
let h = top + systems as f64 * sys_h + MARGIN;
|
||||
let mut o = String::new();
|
||||
let _ =
|
||||
writeln!(o, "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{W}\" height=\"{h:.0}\" viewBox=\"0 0 {W} {h:.0}\" font-family=\"serif\">");
|
||||
let _ = writeln!(o, "<rect width=\"100%\" height=\"100%\" fill=\"white\"/>");
|
||||
let _ = writeln!(o, "<text x=\"{}\" y=\"56\" font-size=\"24\" text-anchor=\"middle\">{}</text>", W / 2.0, xml_escape(&setup.title));
|
||||
if !setup.composer.is_empty() {
|
||||
let _ = writeln!(o, "<text x=\"{}\" y=\"84\" font-size=\"13\" text-anchor=\"end\">{}</text>", W - MARGIN, xml_escape(&setup.composer));
|
||||
over_budget(&o, budget)?;
|
||||
}
|
||||
over_budget(&o, budget)?;
|
||||
let bar_w = (staff_x1 - staff_x0) / per as f64;
|
||||
for sys in 0..systems {
|
||||
let y_sys = top + sys as f64 * sys_h;
|
||||
for (pi, p) in parts.iter().enumerate() {
|
||||
let y0 = y_sys + pi as f64 * STAFF_GAP; // top line
|
||||
let bottom = y0 + 4.0 * SP;
|
||||
if setup.show_track_names && sys == 0 {
|
||||
let _ = writeln!(o, "<text x=\"{MARGIN}\" y=\"{:.1}\" font-size=\"11\">{}</text>", y0 + 2.0 * SP + 4.0, xml_escape(&p.name));
|
||||
}
|
||||
for l in 0..5 {
|
||||
let y = y0 + f64::from(l) * SP;
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<line x1=\"{:.1}\" y1=\"{y:.1}\" x2=\"{staff_x1:.1}\" y2=\"{y:.1}\" stroke=\"black\" stroke-width=\"0.8\"/>",
|
||||
staff_x0 - 30.0
|
||||
);
|
||||
}
|
||||
let clef = if p.bass { "𝄢" } else { "𝄞" };
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{}\">{clef}</text>",
|
||||
staff_x0 - 29.0,
|
||||
bottom + if p.bass { -SP } else { SP * 0.6 },
|
||||
if p.bass { 26 } else { 36 }
|
||||
);
|
||||
for k in 0..per {
|
||||
let mi = sys * per + k;
|
||||
let x0 = staff_x0 + k as f64 * bar_w;
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<line x1=\"{:.1}\" y1=\"{y0:.1}\" x2=\"{:.1}\" y2=\"{bottom:.1}\" stroke=\"black\" stroke-width=\"1\"/>",
|
||||
x0 + bar_w,
|
||||
x0 + bar_w
|
||||
);
|
||||
let Some(m) = p.measures.get(mi) else { continue };
|
||||
if pi == 0 {
|
||||
let _ = writeln!(o, "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"9\">{}</text>", x0 + 2.0, y0 - 8.0, mi + 1);
|
||||
}
|
||||
let total: u32 = m.items.iter().map(|i| i.units).sum::<u32>().max(1);
|
||||
let mut acc = 0u32;
|
||||
for it in &m.items {
|
||||
let x = x0 + 10.0 + (bar_w - 16.0) * f64::from(acc) / f64::from(total);
|
||||
acc += it.units;
|
||||
let (_, dot) = note_type(it.units);
|
||||
if it.pitches.is_empty() {
|
||||
rest(&mut o, x, y0, SP, it.units);
|
||||
if dot {
|
||||
let _ = writeln!(o, "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"1.3\"/>", x + 7.0, y0 + 1.5 * SP);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let steps: Vec<i32> = it.pitches.iter().map(|p2| staff_step(*p2, p.bass)).collect();
|
||||
let filled = it.units < 8;
|
||||
for (pitch, st) in it.pitches.iter().zip(&steps) {
|
||||
let y = bottom - f64::from(*st) * SP / 2.0;
|
||||
// Ledger lines.
|
||||
let mut l = if *st < 0 { -2 } else { 10 };
|
||||
while (*st < 0 && l >= *st) || (*st > 8 && l <= *st) {
|
||||
let ly = bottom - f64::from(l) * SP / 2.0;
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<line x1=\"{:.1}\" y1=\"{ly:.1}\" x2=\"{:.1}\" y2=\"{ly:.1}\" stroke=\"black\" stroke-width=\"0.8\"/>",
|
||||
x - 7.0,
|
||||
x + 7.0
|
||||
);
|
||||
l += if *st < 0 { -2 } else { 2 };
|
||||
}
|
||||
let fill = if filled { "black" } else { "white" };
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<ellipse cx=\"{x:.1}\" cy=\"{y:.1}\" rx=\"4.6\" ry=\"3.3\" transform=\"rotate(-20 {x:.1} {y:.1})\" fill=\"{fill}\" stroke=\"black\" stroke-width=\"1.1\"/>"
|
||||
);
|
||||
if spell(*pitch).1 != 0 {
|
||||
let _ = writeln!(o, "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"12\">♯</text>", x - 14.0, y + 4.0);
|
||||
}
|
||||
if dot {
|
||||
let _ = writeln!(o, "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"1.3\"/>", x + 8.0, y - 1.5);
|
||||
}
|
||||
}
|
||||
if it.units < 16 {
|
||||
let (lo, hi) = (steps.iter().copied().min().unwrap_or(4), steps.iter().copied().max().unwrap_or(4));
|
||||
let up = (lo + hi) < 8;
|
||||
let (sx, y_from, y_to) = if up {
|
||||
(x + 4.3, bottom - f64::from(lo) * SP / 2.0, bottom - f64::from(hi) * SP / 2.0 - 3.5 * SP)
|
||||
} else {
|
||||
(x - 4.3, bottom - f64::from(hi) * SP / 2.0, bottom - f64::from(lo) * SP / 2.0 + 3.5 * SP)
|
||||
};
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<line x1=\"{sx:.1}\" y1=\"{y_from:.1}\" x2=\"{sx:.1}\" y2=\"{y_to:.1}\" stroke=\"black\" stroke-width=\"1\"/>"
|
||||
);
|
||||
let flags = match it.units {
|
||||
1 => 2,
|
||||
2 | 3 => 1,
|
||||
_ => 0,
|
||||
};
|
||||
for f in 0..flags {
|
||||
let fy = y_to + f64::from(f) * if up { 5.0 } else { -5.0 };
|
||||
let dy = if up { 9.0 } else { -9.0 };
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<path d=\"M{sx:.1} {fy:.1} q 7 {:.1} 5 {dy:.1}\" fill=\"none\" stroke=\"black\" stroke-width=\"1.4\"/>",
|
||||
dy * 0.5
|
||||
);
|
||||
}
|
||||
}
|
||||
if it.tie_start {
|
||||
let y = bottom - f64::from(steps[0]) * SP / 2.0 + 6.0;
|
||||
let _ = writeln!(o, "<path d=\"M{:.1} {y:.1} q 8 5 16 0\" fill=\"none\" stroke=\"black\" stroke-width=\"0.9\"/>", x + 3.0);
|
||||
}
|
||||
}
|
||||
// Check each measure, so a run of rest-only or missing measures that only draws
|
||||
// bar lines cannot grow the output past the budget untouched.
|
||||
over_budget(&o, budget)?;
|
||||
}
|
||||
// The staff markup (lines, clef, track names) itself grows with the part count even
|
||||
// without any items, so check once per staff too.
|
||||
over_budget(&o, budget)?;
|
||||
}
|
||||
// System bracket.
|
||||
let y_last = y_sys + (parts.len().max(1) - 1) as f64 * STAFF_GAP + 4.0 * SP;
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<line x1=\"{:.1}\" y1=\"{y_sys:.1}\" x2=\"{:.1}\" y2=\"{y_last:.1}\" stroke=\"black\" stroke-width=\"1.5\"/>",
|
||||
staff_x0 - 30.0,
|
||||
staff_x0 - 30.0
|
||||
);
|
||||
over_budget(&o, budget)?;
|
||||
}
|
||||
o.push_str("</svg>\n");
|
||||
over_budget(&o, budget)?;
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) {
|
||||
let mid = y0 + 2.0 * sp;
|
||||
match units {
|
||||
16 => {
|
||||
let _ = writeln!(o, "<rect x=\"{:.1}\" y=\"{:.1}\" width=\"9\" height=\"{:.1}\"/>", x - 4.5, y0 + sp, sp / 2.0);
|
||||
}
|
||||
8 | 12 => {
|
||||
let _ = writeln!(o, "<rect x=\"{:.1}\" y=\"{:.1}\" width=\"9\" height=\"{:.1}\"/>", x - 4.5, mid - sp / 2.0, sp / 2.0);
|
||||
}
|
||||
4 | 6 => {
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<path d=\"M{:.1} {:.1} l 4 5 l -4 4 l 4 5 q -6 -2 -2 5\" fill=\"none\" stroke=\"black\" stroke-width=\"1.8\"/>",
|
||||
x - 2.0,
|
||||
mid - 9.0
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
let _ = writeln!(o, "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"2\"/>", x - 2.0, mid - 3.0);
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"<line x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" stroke=\"black\" stroke-width=\"1.2\"/>",
|
||||
x + 2.5,
|
||||
mid - 4.0,
|
||||
x - 1.0,
|
||||
mid + 7.0
|
||||
);
|
||||
if units == 1 {
|
||||
let _ = writeln!(o, "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"2\"/>", x - 3.5, mid + 2.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
craft_score::svg_budgeted(parts, &shared_setup(setup), budget)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn score_preserves_pitch_activity(notes in proptest::collection::vec((0i64..32, 1i64..32, 48u8..64), 0..20)) {
|
||||
let notes: Vec<_> = notes.into_iter().map(|(a, length, pitch)| (a, a + length, pitch)).collect();
|
||||
let measures = fill(&[(0, 16, 4, 4), (16, 16, 4, 4), (32, 16, 4, 4), (48, 16, 4, 4)], ¬es);
|
||||
let mut at = 0i64;
|
||||
for m in measures {
|
||||
proptest::prop_assert_eq!(m.items.iter().map(|i| i.units).sum::<u32>(), 16);
|
||||
for item in m.items {
|
||||
for tick in at..at + i64::from(item.units) {
|
||||
let expected: Vec<u8> = (48..64).filter(|pitch| notes.iter().any(|(a, b, p)| p == pitch && *a <= tick && tick < *b)).collect();
|
||||
proptest::prop_assert_eq!(&item.pitches, &expected);
|
||||
}
|
||||
let end = at + i64::from(item.units);
|
||||
let tied_in: Vec<_> = item.pitches.iter().copied().filter(|p| {
|
||||
notes.iter().any(|(a, b, pitch)| pitch == p && *a < at && at < *b)
|
||||
&& !notes.iter().any(|(a, _, pitch)| pitch == p && *a == at)
|
||||
}).collect();
|
||||
let tied_out: Vec<_> = item.pitches.iter().copied().filter(|p| {
|
||||
end < 64 && notes.iter().any(|(a, b, pitch)| pitch == p && *a < end && end < *b)
|
||||
&& !notes.iter().any(|(a, _, pitch)| pitch == p && *a == end)
|
||||
}).collect();
|
||||
proptest::prop_assert_eq!(item.tie_stop, tied_in);
|
||||
proptest::prop_assert_eq!(item.tie_start, tied_out);
|
||||
at = end;
|
||||
}
|
||||
}
|
||||
proptest::prop_assert_eq!(at, 64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_note_end_does_not_silence_later_admitted_pitch() {
|
||||
let mut notes: Vec<_> = (48..64).map(|pitch| (0, 30, pitch)).collect();
|
||||
notes.extend([(10, 50, 64), (30, 80, 64)]);
|
||||
let measures = fill(&[(0, 80, 20, 4)], ¬es);
|
||||
let mut at = 0;
|
||||
for item in &measures[0].items {
|
||||
let end = at + i64::from(item.units);
|
||||
for tick in at..end {
|
||||
assert_eq!(item.pitches.contains(&64), (30..80).contains(&tick));
|
||||
}
|
||||
if item.pitches.contains(&64) {
|
||||
assert_eq!(item.tie_stop.contains(&64), at > 30);
|
||||
assert_eq!(item.tie_start.contains(&64), end < 80);
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
assert_eq!(at, 80);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_chord_durations_are_preserved_in_layout_and_exports() {
|
||||
let measures = fill(&[(0, 16, 4, 4)], &[(0, 4, 60), (0, 16, 64)]);
|
||||
let items = &measures[0].items;
|
||||
assert_eq!(items.iter().map(|i| i.units).sum::<u32>(), 16);
|
||||
assert_eq!(items.iter().filter(|i| i.pitches.contains(&60)).map(|i| i.units).sum::<u32>(), 4);
|
||||
assert_eq!(items.iter().filter(|i| i.pitches.contains(&64)).map(|i| i.units).sum::<u32>(), 16);
|
||||
assert_eq!(items[0].tie_start, vec![64]);
|
||||
assert_eq!(items[1].tie_stop, vec![64]);
|
||||
let parts = vec![Part { name: "Keys".into(), bass: false, measures }];
|
||||
let setup = ScoreSetup::from_session(&Session::default());
|
||||
let xml = musicxml(&parts, &setup).unwrap();
|
||||
let notes: Vec<_> = xml.split("<note>").skip(1).map(|n| n.split("</note>").next().unwrap()).collect();
|
||||
assert!(notes[0].contains("<step>C</step>") && notes[0].contains("<duration>4</duration>"));
|
||||
assert!(!notes[0].contains("<tie "));
|
||||
assert!(notes[1].contains("<tie type=\"start\"/>") && notes[1].contains("<chord/>"));
|
||||
assert!(notes[2].contains("<duration>12</duration>") && notes[2].contains("<tie type=\"stop\"/>"));
|
||||
assert_eq!(svg(&parts, &setup).unwrap().matches("stroke-width=\"0.9\"").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_notes_continue_and_repeated_notes_are_not_tied() {
|
||||
let m = fill(&[(0, 16, 4, 4), (16, 16, 4, 4)], &[(0, 20, 60), (4, 8, 64), (20, 24, 60)]);
|
||||
let items: Vec<_> = m.iter().flat_map(|m| &m.items).collect();
|
||||
assert_eq!(items.iter().filter(|i| i.pitches.contains(&60)).map(|i| i.units).sum::<u32>(), 24);
|
||||
assert_eq!(items.iter().filter(|i| i.pitches.contains(&64)).map(|i| i.units).sum::<u32>(), 4);
|
||||
assert_eq!(m[1].items[0].tie_stop, vec![60]);
|
||||
assert!(m[1].items[0].tie_start.is_empty());
|
||||
assert!(m[1].items[1].tie_stop.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_units_uses_representable_values() {
|
||||
assert_eq!(split_units(16), vec![16]);
|
||||
@@ -618,15 +391,6 @@ mod tests {
|
||||
assert!(split_units(0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spelling_and_staff_steps() {
|
||||
assert_eq!(spell(60), ('C', 0, 4));
|
||||
assert_eq!(spell(61), ('C', 1, 4));
|
||||
assert_eq!(staff_step(64, false), 0); // E4: bottom treble line
|
||||
assert_eq!(staff_step(77, false), 8); // F5: top treble line
|
||||
assert_eq!(staff_step(43, true), 0); // G2: bottom bass line
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_fill_exactly_and_tie_across_bars() {
|
||||
// 4/4: one bar = 16 units. A note from unit 12 to 20 crosses the bar line.
|
||||
@@ -637,8 +401,8 @@ mod tests {
|
||||
assert_eq!(meas.items.iter().map(|i| i.units).sum::<u32>(), 16);
|
||||
}
|
||||
assert_eq!(m[0].items[0].pitches, vec![60, 64]);
|
||||
assert!(m[0].items.last().is_some_and(|i| i.tie_start));
|
||||
assert!(m[1].items[0].tie_stop);
|
||||
assert!(m[0].items.last().is_some_and(|i| !i.tie_start.is_empty()));
|
||||
assert_eq!(m[1].items[0].tie_stop, vec![67]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -656,7 +420,7 @@ mod tests {
|
||||
|
||||
/// Note onsets (pitch count of every chord that is not a tie continuation).
|
||||
fn note_starts(parts: &[Part]) -> usize {
|
||||
parts.iter().flat_map(|p| &p.measures).flat_map(|m| &m.items).filter(|i| !i.tie_stop).map(|i| i.pitches.len()).sum()
|
||||
parts.iter().flat_map(|p| &p.measures).flat_map(|m| &m.items).filter(|i| i.tie_stop.is_empty()).map(|i| i.pitches.len()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -14,6 +14,7 @@ mod midi_offset;
|
||||
mod min_secs_with_timecode_counter;
|
||||
mod mix_required_params;
|
||||
mod new_track_rows;
|
||||
mod processing_keeps_crossfades;
|
||||
mod random_edits;
|
||||
mod recording;
|
||||
mod session_transport;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Processing a clip in place (AudioSuite, TCE, Elastic) keeps the crossfade it shares with its
|
||||
//! neighbour: the neighbour keeps its overlap and its fade, so the edit does not dip to silence.
|
||||
//! Where the processed clip reaches past its old edges, it still overwrites what is there.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_engine::Engine;
|
||||
use soundcraft_model::{Clip, ClipId, Fade, FadeShape, Source, SourceAudio, SourceId, TrackId};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn source(id: u64, name: &str) -> Source {
|
||||
Source {
|
||||
id: SourceId(id),
|
||||
name: name.into(),
|
||||
path: format!("{name}.wav"),
|
||||
channels: 1,
|
||||
frames: 20_000,
|
||||
sample_rate: 48_000,
|
||||
format: soundcraft_model::FileFormat::Wav,
|
||||
time_reference: 0,
|
||||
unsaved: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A on 0..1200 fading out over 1000..1200, B on 1000..3000 fading in over the same 200 samples.
|
||||
fn crossfade() -> (Engine, TrackId, ClipId, ClipId) {
|
||||
let mut e = Engine::default();
|
||||
let t = TrackId(e.execute("track.new", &json!({"count": 1})).unwrap()["tracks"][0].as_u64().unwrap());
|
||||
let s = e.session_mut();
|
||||
for (id, name) in [(1, "a"), (2, "b")] {
|
||||
s.sources.push(source(id, name));
|
||||
let buf = craft_audio::AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 20_000]] };
|
||||
s.pool.insert(SourceId(id), Arc::new(SourceAudio::new(buf)));
|
||||
}
|
||||
let (a, b) = (s.new_clip_id(), s.new_clip_id());
|
||||
let fade = Fade { len: 200, shape: FadeShape::EqualPower, curvature: 0.0 };
|
||||
let mut ca = Clip::audio(a, "a", SourceId(1), 5000, 0, 1200);
|
||||
ca.fade_out = fade;
|
||||
let mut cb = Clip::audio(b, "b", SourceId(2), 5000, 1000, 2000);
|
||||
cb.fade_in = fade;
|
||||
s.track_mut(t).and_then(|t| t.playlist_mut()).unwrap().clips = vec![ca, cb];
|
||||
(e, t, a, b)
|
||||
}
|
||||
|
||||
/// (start, end, fade in, fade out) of each clip on the track, in order.
|
||||
fn layout(e: &Engine, t: TrackId) -> Vec<(i64, i64, i64, i64)> {
|
||||
e.session().track(t).unwrap().clips().iter().map(|c| (c.start, c.end(), c.fade_in.len, c.fade_out.len)).collect()
|
||||
}
|
||||
|
||||
fn run(e: &mut Engine, cmd: &str, clip: ClipId, mut params: Value) {
|
||||
params["clips"] = json!([clip.0]);
|
||||
e.execute(cmd, ¶ms).unwrap_or_else(|err| panic!("{cmd} {params}: {err}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processing_either_clip_of_a_crossfade_keeps_the_crossfade() {
|
||||
let unchanged = vec![(0, 1200, 0, 200), (1000, 3000, 200, 0)];
|
||||
for (cmd, params) in [("audiosuite.process", json!({"plugin": "reverse"})), ("audiosuite.process", json!({"plugin": "invert"}))] {
|
||||
for later in [false, true] {
|
||||
let (mut e, t, a, b) = crossfade();
|
||||
run(&mut e, cmd, if later { b } else { a }, params.clone());
|
||||
assert_eq!(layout(&e, t), unchanged, "{cmd} {params} on {}", if later { "B" } else { "A" });
|
||||
}
|
||||
}
|
||||
// TCE over the clip's own range renders it again in place.
|
||||
let (mut e, t, _, b) = crossfade();
|
||||
run(&mut e, "edit.tce_to_timeline", b, json!({"start": 1000, "end": 3000}));
|
||||
assert_eq!(layout(&e, t), unchanged, "TCE of B in place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_processed_clip_that_grows_away_from_the_crossfade_keeps_it() {
|
||||
// Elastic and TCE that lengthen B keep its start: A keeps its overlap and its fade-out.
|
||||
let (mut e, t, _, b) = crossfade();
|
||||
e.session_mut().track_mut(t).unwrap().elastic = Some("polyphonic".into());
|
||||
run(&mut e, "clip.elastic_properties", b, json!({"ratio": 2.0}));
|
||||
assert_eq!(layout(&e, t), vec![(0, 1200, 0, 200), (1000, 5000, 200, 0)], "Elastic x2 on B");
|
||||
let (mut e, t, _, b) = crossfade();
|
||||
run(&mut e, "edit.tce_to_timeline", b, json!({"start": 1000, "end": 5000}));
|
||||
assert_eq!(layout(&e, t), vec![(0, 1200, 0, 200), (1000, 5000, 400, 0)], "TCE of B to 1000..5000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_processed_clip_still_overwrites_past_its_old_edges() {
|
||||
// TCE of B to 900..2900 starts it inside A: A is cut back to 900, as before.
|
||||
let (mut e, t, _, b) = crossfade();
|
||||
run(&mut e, "edit.tce_to_timeline", b, json!({"start": 900, "end": 2900}));
|
||||
assert_eq!(layout(&e, t), vec![(0, 900, 0, 0), (900, 2900, 200, 0)], "A ends where B now starts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_inside_or_around_the_processed_clip_is_still_overwritten() {
|
||||
// Neither shares a crossfade with B: one lies inside it (1500..2000), the other spans past both its
|
||||
// edges (900..3200). What replaces B still overwrites them where it lands.
|
||||
let cases = [
|
||||
((1500, 500), "edit.tce_to_timeline", json!({"start": 900, "end": 3100})),
|
||||
((900, 2300), "audiosuite.process", json!({"plugin": "reverse"})),
|
||||
];
|
||||
for ((start, len), cmd, params) in cases {
|
||||
let (mut e, t, _, b) = crossfade();
|
||||
let s = e.session_mut();
|
||||
let other = s.new_clip_id();
|
||||
s.track_mut(t).and_then(|t| t.playlist_mut()).unwrap().clips.push(Clip::audio(other, "other", SourceId(1), 5000, start, len));
|
||||
run(&mut e, cmd, b, params.clone());
|
||||
let over_b: Vec<ClipId> = e.session().track(t).unwrap().clips().iter().filter(|c| c.start <= 1750 && 1750 < c.end()).map(|c| c.id).collect();
|
||||
assert_eq!(over_b.len(), 1, "{cmd} {params} with a clip at {start}+{len}: {over_b:?} cover the middle of B");
|
||||
assert_ne!(over_b[0], other, "{cmd} {params}: the clip at {start}+{len} survived over B");
|
||||
}
|
||||
}
|
||||
|
||||
/// Both replacement orders preserve the audible overlap when one call processes both clips.
|
||||
#[test]
|
||||
fn processing_both_crossfade_clips_preserves_rendered_overlap() {
|
||||
for reverse_order in [false, true] {
|
||||
for (process, sign) in [("reverse", 1.0f32), ("invert", -1.0f32)] {
|
||||
let (mut e, t, a, b) = crossfade();
|
||||
let range = soundcraft_time::Range::new(1000, 1200);
|
||||
let before = soundcraft_mix::render_clips(e.session(), t, range);
|
||||
assert!(before.iter().flatten().all(|sample| sample.abs() > 0.1));
|
||||
let ids = if reverse_order { vec![b.0, a.0] } else { vec![a.0, b.0] };
|
||||
let result = e.execute("audiosuite.process", &json!({"process": process, "clips": ids})).unwrap();
|
||||
assert_eq!(result["processed"], 2);
|
||||
assert_eq!(layout(&e, t), vec![(0, 1200, 0, 200), (1000, 3000, 200, 0)]);
|
||||
let after = soundcraft_mix::render_clips(e.session(), t, range);
|
||||
assert_eq!(after.len(), before.len());
|
||||
for (actual, expected) in after.iter().zip(&before) {
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
for (frame, (actual, expected)) in actual.iter().zip(expected).enumerate() {
|
||||
assert!((actual - sign * expected).abs() < 1e-5, "{process} reversed={reverse_order} frame={frame}: {actual} vs {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,8 @@ pub use offline::{
|
||||
};
|
||||
pub use pan::itu_stereo_fold;
|
||||
use pan::{PanSpec, apply_matrix, apply_matrix_span, build_matrix};
|
||||
use routing::{processing_order, structure_fingerprint};
|
||||
pub use routing::solo_mutes;
|
||||
use routing::{any_solo, processing_order, structure_fingerprint};
|
||||
use strip::{
|
||||
Block, BusBuf, LiveInput, SlotCtx, Strip, apply_params, contain_failure, note_insert_latency, process_strip, strip_channels, strip_format,
|
||||
};
|
||||
@@ -365,7 +366,7 @@ impl MixEngine {
|
||||
pub fn render(&mut self, s: &Session, pos: Samples, frames: usize, out: &mut [Vec<f32>]) {
|
||||
let frames = frames.min(self.max_block);
|
||||
self.begin_block(s, pos, frames);
|
||||
let blk = Block { pos, frames, any_solo: s.tracks.iter().any(|t| t.mixer.solo && !t.inactive) };
|
||||
let blk = Block { pos, frames, any_solo: any_solo(s) };
|
||||
let order = std::mem::take(&mut self.order);
|
||||
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
|
||||
let mut work = std::mem::take(&mut self.work);
|
||||
|
||||
@@ -155,7 +155,33 @@ pub(crate) fn receives_solo(s: &Session, t: &Track) -> bool {
|
||||
let Route::Bus(b) = &t.mixer.input else { return false };
|
||||
s.tracks
|
||||
.iter()
|
||||
.any(|o| o.mixer.solo && (o.mixer.output == Route::Bus(*b) || o.mixer.sends.iter().flatten().any(|sn| sn.target == Route::Bus(*b))))
|
||||
.any(|o| (o.mixer.output == Route::Bus(*b) || o.mixer.sends.iter().flatten().any(|sn| sn.target == Route::Bus(*b))) && solo_source(s, o))
|
||||
}
|
||||
|
||||
/// A track's own solo, or the solo of the active VCA master it belongs to: soloing a VCA solos its members.
|
||||
fn soloed(s: &Session, t: &Track) -> bool {
|
||||
t.mixer.solo || t.mixer.vca.is_some_and(|vid| s.tracks.iter().any(|v| v.id.0 == vid && v.kind == TrackKind::Vca && !v.inactive && v.mixer.solo))
|
||||
}
|
||||
|
||||
/// `t` makes the solo: it plays and is soloed, by itself or through its VCA. A VCA passes no audio, so it is no source.
|
||||
fn solo_source(s: &Session, t: &Track) -> bool {
|
||||
!t.inactive && t.kind != TrackKind::Vca && soloed(s, t)
|
||||
}
|
||||
|
||||
/// The solo is on: a track makes it ([`solo_source`]). A soloed VCA with no members solos nothing.
|
||||
pub(crate) fn any_solo(s: &Session) -> bool {
|
||||
s.tracks.iter().any(|t| solo_source(s, t))
|
||||
}
|
||||
|
||||
/// The solo mutes `t`: it is on (`any_solo`, see [`any_solo`]) and `t` is neither soloed, Solo Safe nor fed by a
|
||||
/// soloed track. A VCA passes no audio, so the solo never mutes it: its fader still drives the members that sound.
|
||||
pub(crate) fn solo_muted(s: &Session, t: &Track, any_solo: bool) -> bool {
|
||||
any_solo && t.kind != TrackKind::Vca && !t.mixer.solo_safe && !soloed(s, t) && !receives_solo(s, t)
|
||||
}
|
||||
|
||||
/// [`solo_muted`] for displays, such as the implied-mute shade of a track's Mute key.
|
||||
pub fn solo_mutes(s: &Session, t: &Track) -> bool {
|
||||
solo_muted(s, t, any_solo(s))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::clips::{ClipFx, clip_fx_params, render_clip};
|
||||
use super::instances::{INSTRUMENT_SLOT, PluginFailures, PreparedInstance, create_instance_for, is_third_party};
|
||||
use super::midi::{chase_controllers, schedule_notes};
|
||||
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
|
||||
use super::routing::receives_solo;
|
||||
use super::routing::solo_muted;
|
||||
use super::{
|
||||
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
|
||||
db_to_gain,
|
||||
@@ -423,7 +423,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
|
||||
}
|
||||
}
|
||||
run_inserts(t, strip, blk, &transport);
|
||||
let soloed_out = any_solo && !t.mixer.solo && !t.mixer.solo_safe && !receives_solo(s, t);
|
||||
let soloed_out = solo_muted(s, t, any_solo);
|
||||
strip.muted = t.mixer.mute || soloed_out;
|
||||
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
|
||||
strip.pre.resize_with(strip.buf.len(), Vec::new);
|
||||
|
||||
@@ -89,6 +89,102 @@ fn add_dc_track(s: &mut Session, level: f32, frames: usize) -> TrackId {
|
||||
t
|
||||
}
|
||||
|
||||
/// Per track: the solo mutes it ([`solo_mutes`]).
|
||||
fn shaded(s: &Session) -> Vec<bool> {
|
||||
s.tracks.iter().map(|t| solo_mutes(s, t)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soloing_a_vca_solos_its_members() {
|
||||
let (mut s, member) = session_with_dc(0.5, 4800);
|
||||
// Quieter than the member, so the render tells which of the two sounds.
|
||||
let other = add_dc_track(&mut s, 0.5, 4800);
|
||||
s.track_mut(other).unwrap().mixer.volume_db = -6.0;
|
||||
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, Some("VCA"));
|
||||
s.track_mut(member).unwrap().mixer.vca = Some(vca.0);
|
||||
s.track_mut(other).unwrap().mixer.mute = true;
|
||||
let only_member = render_range(&s, Range::new(0, 4800), 512);
|
||||
assert!(only_member[0][2000].abs() > 0.1, "the member should sound");
|
||||
s.track_mut(other).unwrap().mixer.mute = false;
|
||||
s.track_mut(vca).unwrap().mixer.solo = true;
|
||||
assert_eq!(render_range(&s, Range::new(0, 4800), 512), only_member);
|
||||
assert_eq!(shaded(&s), [false, true, false], "member, other, VCA");
|
||||
// A soloed member leaves its VCA unshaded.
|
||||
s.track_mut(vca).unwrap().mixer.solo = false;
|
||||
s.track_mut(member).unwrap().mixer.solo = true;
|
||||
assert_eq!(shaded(&s), [false, true, false], "member soloed: member, other, VCA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soloing_an_empty_vca_mutes_nothing() {
|
||||
let (mut s, _) = session_with_dc(0.5, 4800);
|
||||
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, Some("VCA"));
|
||||
let all = render_range(&s, Range::new(0, 4800), 512);
|
||||
s.track_mut(vca).unwrap().mixer.solo = true;
|
||||
assert_eq!(render_range(&s, Range::new(0, 4800), 512), all);
|
||||
assert_eq!(shaded(&s), [false, false], "track, VCA");
|
||||
}
|
||||
|
||||
/// A member of a VCA that is not soloed itself, reaching an aux through its output or through a send, next to a
|
||||
/// track the solo mutes. Tracks: member, other, aux, VCA. The solo goes on the member, or on its VCA.
|
||||
fn member_through_aux(by_send: bool, solo_vca: bool) -> Session {
|
||||
let (mut s, member) = session_with_dc(0.5, 4800);
|
||||
add_dc_track(&mut s, 0.5, 4800);
|
||||
let bus = s.add_bus("Verb", ChannelFormat::Stereo);
|
||||
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, Some("Verb"));
|
||||
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
|
||||
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, Some("VCA"));
|
||||
let tr = s.track_mut(member).unwrap();
|
||||
tr.mixer.vca = Some(vca.0);
|
||||
if by_send {
|
||||
tr.mixer.output = Route::None;
|
||||
let mut send = soundcraft_model::SendSlot::new(Route::Bus(bus));
|
||||
send.level_db = 0.0; // a new send sits at -144 dB
|
||||
tr.mixer.sends[0] = Some(send);
|
||||
} else {
|
||||
tr.mixer.output = Route::Bus(bus);
|
||||
}
|
||||
if solo_vca {
|
||||
s.track_mut(vca).unwrap().mixer.solo = true;
|
||||
} else {
|
||||
s.track_mut(member).unwrap().mixer.solo = true;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soloed_vcas_member_feeds_its_aux_through_the_output() {
|
||||
let (vca, own) = (member_through_aux(false, true), member_through_aux(false, false));
|
||||
let out = render_range(&vca, Range::new(0, 4800), 512);
|
||||
assert!(out[0][2000].abs() > 0.1, "the aux carries the member: {}", out[0][2000]);
|
||||
// Soloing the VCA sounds as soloing the member itself.
|
||||
assert_eq!(out, render_range(&own, Range::new(0, 4800), 512));
|
||||
assert_eq!(shaded(&vca), [false, true, false, false], "member, other, aux, VCA");
|
||||
assert_eq!(shaded(&own), shaded(&vca));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soloed_vcas_member_feeds_its_send_return() {
|
||||
let (vca, own) = (member_through_aux(true, true), member_through_aux(true, false));
|
||||
let out = render_range(&vca, Range::new(0, 4800), 512);
|
||||
assert!(out[0][2000].abs() > 0.1, "the send return carries the member: {}", out[0][2000]);
|
||||
assert_eq!(out, render_range(&own, Range::new(0, 4800), 512));
|
||||
assert_eq!(shaded(&vca), [false, true, false, false], "member, other, aux, VCA");
|
||||
assert_eq!(shaded(&own), shaded(&vca));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inactive_track_does_not_solo_its_aux() {
|
||||
// An inactive track plays nothing, so it is no solo source for an aux, whether soloed itself or through its VCA.
|
||||
// `other` keeps the solo on.
|
||||
for solo_vca in [false, true] {
|
||||
let mut s = member_through_aux(false, solo_vca);
|
||||
s.tracks[1].mixer.solo = true;
|
||||
s.tracks[0].inactive = true;
|
||||
assert_eq!(shaded(&s), [false, false, true, false], "solo_vca {solo_vca}: member, other, aux, VCA");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_center_pan_is_minus_3db() {
|
||||
let (s, _) = session_with_dc(0.5, 4800);
|
||||
|
||||
@@ -8,6 +8,7 @@ rust-version = "1.95"
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
craft-ui.workspace = true
|
||||
soundcraft-time.workspace = true
|
||||
craft-audio.workspace = true
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -139,6 +139,7 @@ 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) {
|
||||
let _language = crate::localization::enter(self.ui.language);
|
||||
self.ui.undo_levels = self.ui.undo_levels.clamp(1, 64);
|
||||
self.engine.set_history_limit(self.ui.undo_levels);
|
||||
// Fonts set now take effect next frame, so draw only from the frame after.
|
||||
@@ -244,6 +245,7 @@ impl SoundApp {
|
||||
|
||||
/// Lay out the whole window.
|
||||
pub fn ui(&mut self, ui: &mut egui::Ui) {
|
||||
let _language = crate::localization::enter(self.ui.language);
|
||||
let ctx = ui.ctx().clone();
|
||||
// egui just processed the scripted key events. A scripted release while the host still
|
||||
// physically holds the key would report it up; put the host-only state back before any
|
||||
|
||||
@@ -13,7 +13,7 @@ impl SoundApp {
|
||||
/// then stays the configuration of the open device.
|
||||
pub fn apply_audio_config(&mut self, cfg: soundcraft_playback::AudioConfig) -> Result<(), String> {
|
||||
if self.engine.transport.recording {
|
||||
return Err("stop recording before changing the audio device".into());
|
||||
return Err(crate::localization::text("stop recording before changing the audio device").into());
|
||||
}
|
||||
self.ui.audio = cfg;
|
||||
let at = self.position();
|
||||
@@ -46,7 +46,7 @@ impl SoundApp {
|
||||
}
|
||||
Err(e) => {
|
||||
self.recorder_failed = true;
|
||||
self.ui.status = format!("No audio input: {e}");
|
||||
self.ui.status = crate::localized_format!("No audio input: {e}", e = e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,24 +58,28 @@ impl SoundApp {
|
||||
let name = p.device_name.clone();
|
||||
let (cause, then) = match trouble {
|
||||
OutputTrouble::Bug => (
|
||||
"the audio engine hit an internal error (see the log)".to_string(),
|
||||
"Use Reconnect audio device in Setup › Playback Engine, or restart SoundCraft.",
|
||||
crate::localization::text("the audio engine hit an internal error (see the log)").to_string(),
|
||||
crate::localization::text("Use Reconnect audio device in Setup › Playback Engine, or restart SoundCraft."),
|
||||
),
|
||||
OutputTrouble::Gone => (
|
||||
format!("“{}” {}", name, crate::localization::text("is unavailable")),
|
||||
crate::localization::text("Check the audio device, then use Reconnect audio device in Setup › Playback Engine."),
|
||||
),
|
||||
OutputTrouble::Stalled => (
|
||||
format!("“{}” {}", name, crate::localization::text("stopped asking for audio")),
|
||||
crate::localization::text("Use Reconnect audio device in Setup › Playback Engine."),
|
||||
),
|
||||
OutputTrouble::Gone => {
|
||||
(format!("“{name}” is unavailable"), "Check the audio device, then use Reconnect audio device in Setup › Playback Engine.")
|
||||
}
|
||||
OutputTrouble::Stalled => (format!("“{name}” stopped asking for audio"), "Use Reconnect audio device in Setup › Playback Engine."),
|
||||
};
|
||||
let (recording, playing) = (self.engine.transport.recording, self.engine.transport.playing);
|
||||
if recording || playing {
|
||||
self.stop_play();
|
||||
}
|
||||
self.ui.status = if recording {
|
||||
format!("Recording stopped: {cause}. The take is kept up to there. {then}")
|
||||
crate::localized_format!("Recording stopped: {cause} The take is kept up to there. {then}", cause = cause, then = then)
|
||||
} else if playing {
|
||||
format!("Playback stopped: {cause}. {then}")
|
||||
crate::localized_format!("Playback stopped: {cause} {then}", cause = cause, then = then)
|
||||
} else {
|
||||
format!("Audio output: {cause}. {then}")
|
||||
crate::localized_format!("Audio output: {cause} {then}", cause = cause, then = then)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -88,7 +92,7 @@ impl SoundApp {
|
||||
let lost = r.lost_ms();
|
||||
if recording && lost > self.lost_shown {
|
||||
self.lost_shown = lost;
|
||||
self.ui.status = format!("The disk is too slow: this take has lost {lost} ms of input so far.");
|
||||
self.ui.status = crate::localized_format!("The disk is too slow: this take has lost {lost} ms of input so far.", lost = lost);
|
||||
}
|
||||
return;
|
||||
};
|
||||
@@ -99,14 +103,14 @@ impl SoundApp {
|
||||
Trouble::Device(what) => {
|
||||
self.recorder = None;
|
||||
self.recorder_failed = true;
|
||||
(what, "Reconnect it, then use Reconnect audio device in Setup › Playback Engine.")
|
||||
(what, crate::localization::text("Reconnect it, then use Reconnect audio device in Setup › Playback Engine."))
|
||||
}
|
||||
Trouble::Disk(what) => (what, "Check the disk, then record again."),
|
||||
Trouble::Disk(what) => (what, crate::localization::text("Check the disk, then record again.")),
|
||||
};
|
||||
self.ui.status = if recording {
|
||||
format!("Recording stopped: {what}. The take is kept up to there. {then}")
|
||||
crate::localized_format!("Recording stopped: {what} The take is kept up to there. {then}", what = what, then = then)
|
||||
} else {
|
||||
format!("Audio input: {what}. {then}")
|
||||
crate::localized_format!("Audio input: {what} {then}", what = what, then = then)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{SoundApp, Value, bounce, menus};
|
||||
impl SoundApp {
|
||||
/// Run a command; errors go to the status line. Returns the result.
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
let _language = crate::localization::enter(self.ui.language);
|
||||
if matches!(id, "session.new" | "session.open" | "session.close" | "session.revert") && bounce::refuses_session_switch(self) {
|
||||
return Err(self.ui.status.clone());
|
||||
}
|
||||
@@ -39,7 +40,7 @@ impl SoundApp {
|
||||
Ok(v)
|
||||
}
|
||||
Err(e) => {
|
||||
self.ui.status = e.to_string();
|
||||
self.ui.status = crate::localization::error_text(&e.to_string());
|
||||
log::warn!("{id}: {e}");
|
||||
Err(e.to_string())
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ impl SoundApp {
|
||||
// Note indices and gestures belong to the old session's clips (#443); every document
|
||||
// replacement (run, Recover, a session the browser read) goes through here.
|
||||
self.midi = midi_editor::MidiEditorState::default();
|
||||
// The Output window shows a track of the old session: a track of the new one can have
|
||||
// the same id.
|
||||
self.ui.output_window = None;
|
||||
}
|
||||
|
||||
/// The session is modified, or a plugin editor gesture still holds a state the session hasn't
|
||||
@@ -34,7 +37,7 @@ impl SoundApp {
|
||||
/// plugins' own state reaches the session every two minutes (`autosave`).
|
||||
pub(super) fn autosave_changes(&mut self) {
|
||||
if let Some(e) = self.autosaver.as_ref().and_then(soundcraft_engine::autosave::Autosaver::failure) {
|
||||
self.ui.status = format!("Autosave failed: {e}");
|
||||
self.ui.status = crate::localized_format!("Autosave failed: {e}", e = e);
|
||||
}
|
||||
if self.autosave_dir.is_none() || self.engine.revision == self.autosaved_rev {
|
||||
return;
|
||||
@@ -60,7 +63,7 @@ impl SoundApp {
|
||||
let Some(w) = &self.autosaver else { return false };
|
||||
let written = w.flush();
|
||||
if let Err(e) = &written {
|
||||
self.ui.status = format!("Autosave failed: {e}");
|
||||
self.ui.status = crate::localized_format!("Autosave failed: {e}", e = e);
|
||||
}
|
||||
written.is_ok()
|
||||
}
|
||||
@@ -105,16 +108,19 @@ impl SoundApp {
|
||||
self.panic_rev = self.engine.revision;
|
||||
let saved = self.engine.is_dirty() && self.write_autosave();
|
||||
self.ui.status = if saved {
|
||||
"SoundCraft hit an internal error (see the log). Your changes were autosaved: save them, then restart SoundCraft.".into()
|
||||
crate::localization::text(
|
||||
"SoundCraft hit an internal error (see the log). Your changes were autosaved: save them, then restart SoundCraft.",
|
||||
)
|
||||
.into()
|
||||
} else {
|
||||
"SoundCraft hit an internal error (see the log). Restart SoundCraft to be safe.".into()
|
||||
crate::localization::text("SoundCraft hit an internal error (see the log). Restart SoundCraft to be safe.").into()
|
||||
};
|
||||
}
|
||||
|
||||
/// Replace the open session with unsaved work an earlier run left behind.
|
||||
pub fn recover(&mut self, left: &soundcraft_engine::autosave::Leftover) {
|
||||
if self.engine.transport.recording {
|
||||
self.ui.status = "Stop recording before recovering other work.".into();
|
||||
self.ui.status = crate::localization::text("Stop recording before recovering other work.").into();
|
||||
return;
|
||||
}
|
||||
self.close_autosave();
|
||||
@@ -125,11 +131,15 @@ impl SoundApp {
|
||||
soundcraft_engine::autosave::discard(left);
|
||||
}
|
||||
self.ui.status = match missing.len() {
|
||||
0 => format!("Recovered “{}”. Save it to keep the changes.", left.name),
|
||||
n => format!("Recovered “{}”, but {n} audio file(s) are missing. Save it to keep the changes.", left.name),
|
||||
0 => crate::localized_format!("Recovered “{name}”. Save it to keep the changes.", name = left.name),
|
||||
n => crate::localized_format!(
|
||||
"Recovered “{name}”, but {n} audio file(s) are missing. Save it to keep the changes.",
|
||||
name = left.name,
|
||||
n = n
|
||||
),
|
||||
};
|
||||
}
|
||||
Err(e) => self.ui.status = format!("Couldn't recover “{}”: {e}", left.name),
|
||||
Err(e) => self.ui.status = crate::localized_format!("Couldn't recover “{name}”: {e}", name = left.name, e = e),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ impl SoundApp {
|
||||
let r = self.run("mix.sampler_load", json!({"track": track.0, "path": path}));
|
||||
self.sample_loaded(track, path, r);
|
||||
}
|
||||
Err(e) => self.ui.status = e.to_string(),
|
||||
Err(e) => self.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
}
|
||||
} else {
|
||||
self.sample_reads.push(sampler_window::SampleRead { track, file });
|
||||
|
||||
@@ -92,9 +92,9 @@ impl SoundApp {
|
||||
let armed = self.engine.session().tracks.iter().any(|t| t.mixer.record_arm);
|
||||
if !armed {
|
||||
let why = if self.engine.session().tracks.is_empty() {
|
||||
"Nothing to record on yet: add a track with Track › New…, then click its R button."
|
||||
crate::localization::text("Nothing to record on yet: add a track with Track › New…, then click its R button.")
|
||||
} else {
|
||||
"No track is record-enabled: click the R button on the track to record."
|
||||
crate::localization::text("No track is record-enabled: click the R button on the track to record.")
|
||||
};
|
||||
self.ui.status = why.into();
|
||||
self.record_hint = Some((self.last_frame.unwrap_or_default(), why));
|
||||
@@ -104,7 +104,7 @@ impl SoundApp {
|
||||
let takes = match self.arm_recorder() {
|
||||
Ok(takes) => takes,
|
||||
Err(err) => {
|
||||
self.ui.status = format!("Cannot record: {err}");
|
||||
self.ui.status = crate::localized_format!("Cannot record: {err}", err = err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -163,10 +163,10 @@ impl SoundApp {
|
||||
None if self.engine.path.is_some() => std::path::PathBuf::new(),
|
||||
None => self.fallback_take_dir()?,
|
||||
};
|
||||
let Some(r) = &mut self.recorder else { return Err("no audio input device".into()) };
|
||||
let Some(r) = &mut self.recorder else { return Err(crate::localization::text("no audio input device").into()) };
|
||||
let plan = soundcraft_engine::io::plan_takes(&self.engine, &unsaved_dir, r.channels);
|
||||
if plan.is_empty() {
|
||||
return Err("no audio track is record-enabled".into());
|
||||
return Err(crate::localization::text("no audio track is record-enabled").into());
|
||||
}
|
||||
// The takes are unsaved work: on Unix the folder they go into is owner-only, like the
|
||||
// autosaves, before the recorder makes anything in it (other systems get the folder's
|
||||
@@ -216,8 +216,11 @@ impl SoundApp {
|
||||
self.punch = None;
|
||||
self.autosaved_rev = 0;
|
||||
let ids = soundcraft_engine::io::place_recording(&mut self.engine, &plan, takes);
|
||||
self.ui.status =
|
||||
if plan.pass.is_some() { format!("Loop-recorded {} take(s)", ids.len() / tracks) } else { format!("Recorded {} clip(s)", ids.len()) };
|
||||
self.ui.status = if plan.pass.is_some() {
|
||||
crate::localized_format!("Loop-recorded {} take(s)", ids.len() / tracks)
|
||||
} else {
|
||||
crate::localized_format!("Recorded {} clip(s)", ids.len())
|
||||
};
|
||||
if let Some(p) = problem {
|
||||
log::warn!("recording: {p}");
|
||||
self.ui.status = format!("{} ({p})", self.ui.status);
|
||||
|
||||
@@ -75,7 +75,11 @@ impl SoundApp {
|
||||
{
|
||||
match p.open_editor(track, slot) {
|
||||
Ok(()) => return,
|
||||
Err(e) => self.ui.status = format!("{}: {e}", mix_window::plugin_info(&plugin).map_or(plugin.as_str(), |i| i.name)),
|
||||
Err(e) => {
|
||||
let name = mix_window::plugin_info(&plugin).map_or(plugin.as_str(), |i| i.name);
|
||||
let reason = crate::localization::error_text(&e.to_string());
|
||||
self.ui.status = format!("{name}: {reason}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.ui.plugin_windows.contains(&(track, slot)) {
|
||||
@@ -130,5 +134,9 @@ pub(crate) fn failed_plugin_status(s: &soundcraft_model::Session, track: TrackId
|
||||
let t = s.track(track)?;
|
||||
let ins = if slot == soundcraft_mix::INSTRUMENT_SLOT { t.instrument.as_ref() } else { t.mixer.inserts.get(slot)?.as_ref() }?;
|
||||
let name = crate::mix_window::plugin_info(&ins.plugin).map_or(ins.plugin.as_str(), |p| p.name);
|
||||
Some(format!("{name} on {} put out invalid audio, so it is bypassed until playback stops or starts again.", t.name))
|
||||
Some(crate::localized_format!(
|
||||
"{name} on {track} put out invalid audio, so it is bypassed until playback stops or starts again.",
|
||||
name = name,
|
||||
track = t.name
|
||||
))
|
||||
}
|
||||
|
||||
@@ -8,14 +8,14 @@ use serde_json::Value;
|
||||
/// Starts the bounce `file.bounce_mix` runs for `params`; [`step`] renders it.
|
||||
pub fn start(app: &mut SoundApp, params: &Value) {
|
||||
if app.bounce.is_some() {
|
||||
app.ui.status = "A bounce is already running".into();
|
||||
app.ui.status = crate::localization::text("A bounce is already running").into();
|
||||
return;
|
||||
}
|
||||
// Third-party plugins keep state the session can't see: store it first.
|
||||
app.capture_plugin_states();
|
||||
match soundcraft_engine::cmd::bounce_job(&app.engine, params) {
|
||||
Ok(job) => app.bounce = Some(job),
|
||||
Err(e) => app.ui.status = e.to_string(),
|
||||
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,14 @@ pub fn step(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
return;
|
||||
}
|
||||
Ok(Some(done)) => {
|
||||
format!("Bounced {} (peak {:.1} dBFS, {:.1} LUFS)", job.path().file_name().unwrap_or_default().to_string_lossy(), done.peak_db, done.lufs)
|
||||
crate::localized_format!(
|
||||
"Bounced {} (peak {:.1} dBFS, {:.1} LUFS)",
|
||||
job.path().file_name().unwrap_or_default().to_string_lossy(),
|
||||
done.peak_db,
|
||||
done.lufs
|
||||
)
|
||||
}
|
||||
Err(e) => e.to_string(),
|
||||
Err(e) => crate::localization::error_text(&e.to_string()),
|
||||
};
|
||||
app.bounce = None;
|
||||
}
|
||||
@@ -40,7 +45,7 @@ pub fn step(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
/// out of memory. True when refused; the status line says why.
|
||||
pub fn refuses_session_switch(app: &mut SoundApp) -> bool {
|
||||
if app.bounce.is_some() {
|
||||
app.ui.status = "Finish or cancel the bounce first".into();
|
||||
app.ui.status = crate::localization::text("Finish or cancel the bounce first").into();
|
||||
}
|
||||
app.bounce.is_some()
|
||||
}
|
||||
@@ -70,15 +75,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);
|
||||
ui.set_width(320.0);
|
||||
let name = job.path().file_name().unwrap_or_default().to_string_lossy();
|
||||
ui.label(egui::RichText::new(format!("Bouncing {name}")).font(bold(13.0)));
|
||||
ui.label(egui::RichText::new(crate::localized_format!("Bouncing {name}", name = name)).font(bold(13.0)));
|
||||
ui.add(egui::ProgressBar::new(job.progress()));
|
||||
ui.horizontal(|ui| {
|
||||
cancel |= ui.button("Cancel").clicked();
|
||||
cancel |= ui.button(crate::localization::text("Cancel")).clicked();
|
||||
ui.label(egui::RichText::new(format!("{:.0}%", job.progress() * 100.0)).color(Tokens::current().text_dim));
|
||||
});
|
||||
});
|
||||
if cancel {
|
||||
app.bounce = None;
|
||||
app.ui.status = "Bounce cancelled".into();
|
||||
app.ui.status = crate::localization::text("Bounce cancelled").into();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -824,24 +824,8 @@ fn encode(img: &egui::ColorImage, path: Option<&str>, token: u64) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal base64 (standard alphabet) to avoid another dependency.
|
||||
pub fn base64(data: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
||||
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
||||
for i in 0..4 {
|
||||
if i <= chunk.len() {
|
||||
let idx = ((n >> (18 - 6 * i)) & 63) as usize;
|
||||
out.push(char::from(T.get(idx).copied().unwrap_or(b'A')));
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Standard padded Base64 without line wrapping, shared across Craft apps.
|
||||
pub use craft_mime::transfer::base64;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -899,3 +899,19 @@ fn scroll_reports_the_wheel_and_trackpad_sources_after_delivery() {
|
||||
let v = reply.try_recv().expect("trackpad scroll replies after its events were applied");
|
||||
assert_eq!(v["result"]["source"], "trackpad");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_retains_control_wire_bytes() {
|
||||
assert_eq!(super::base64(b""), "");
|
||||
assert_eq!(super::base64(b"f"), "Zg==");
|
||||
assert_eq!(super::base64(b"fo"), "Zm8=");
|
||||
assert_eq!(super::base64(b"foo"), "Zm9v");
|
||||
assert_eq!(super::base64(&[251, 255, 255]), "+///");
|
||||
let bytes: Vec<u8> = (0..=255).cycle().take(513).collect();
|
||||
for len in 0..=bytes.len() {
|
||||
let encoded = super::base64(&bytes[..len]);
|
||||
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
|
||||
assert!(!encoded.contains(['\r', '\n']));
|
||||
assert_eq!(craft_mime::base64::STANDARD.decode(&encoded).unwrap(), bytes[..len]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ impl Contributor {
|
||||
|
||||
/// One line with everything we know, for tooltips.
|
||||
pub fn summary(&self) -> String {
|
||||
format!(
|
||||
crate::localized_format!(
|
||||
"@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}",
|
||||
self.login,
|
||||
self.prs,
|
||||
@@ -213,31 +213,31 @@ impl Default for View {
|
||||
/// Controls for name style, sort key and sort direction above the contributor table.
|
||||
fn contributors_toolbar(ui: &mut egui::Ui, v: &mut View) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("Show");
|
||||
ui.label(crate::localization::text("Show"));
|
||||
for m in NameMode::ALL {
|
||||
if ui.selectable_label(v.names == m, m.label()).clicked() {
|
||||
if ui.selectable_label(v.names == m, crate::localization::text(m.label())).clicked() {
|
||||
v.names = m;
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
let sort = ui.label("Sort");
|
||||
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
|
||||
let sort = ui.label(crate::localization::text("Sort"));
|
||||
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
|
||||
for k in SortKey::ALL {
|
||||
if ui.selectable_label(v.key == k, k.label().0).clicked() {
|
||||
if ui.selectable_label(v.key == k, crate::localization::text(k.label().0)).clicked() {
|
||||
v.key = k;
|
||||
v.ascending = k.default_ascending();
|
||||
}
|
||||
}
|
||||
});
|
||||
combo.response.labelled_by(sort.id);
|
||||
if ui.button(if v.ascending { "⏶" } else { "⏷" }).on_hover_text("Reverse the order").clicked() {
|
||||
if ui.button(if v.ascending { "⏶" } else { "⏷" }).on_hover_text(crate::localization::text("Reverse the order")).clicked() {
|
||||
v.ascending = !v.ascending;
|
||||
}
|
||||
ui.separator();
|
||||
if ui.selectable_label(!v.table, "Grab bag").clicked() {
|
||||
if ui.selectable_label(!v.table, crate::localization::text("Grab bag")).clicked() {
|
||||
v.table = false;
|
||||
}
|
||||
if ui.selectable_label(v.table, "Table").clicked() {
|
||||
if ui.selectable_label(v.table, crate::localization::text("Table")).clicked() {
|
||||
v.table = true;
|
||||
}
|
||||
});
|
||||
@@ -247,7 +247,7 @@ fn contributors_grab_bag(ui: &mut egui::Ui, list: &[&Contributor], names: NameMo
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (i, c) in list.iter().enumerate() {
|
||||
if i > 0 {
|
||||
ui.label(RichText::new("·").weak());
|
||||
ui.label(RichText::new(crate::localization::text("·")).weak());
|
||||
}
|
||||
ui.hyperlink_to(c.name(names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary());
|
||||
}
|
||||
@@ -260,10 +260,10 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
|
||||
let mut v = ui.data_mut(|d| d.get_temp::<View>(id)).unwrap_or_default();
|
||||
contributors_toolbar(ui, &mut v);
|
||||
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.label(RichText::new(crate::localized_format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().weak());
|
||||
ui.separator();
|
||||
if list.is_empty() {
|
||||
ui.label("No contributor data was built into this copy.");
|
||||
ui.label(crate::localization::text("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.
|
||||
@@ -372,7 +372,7 @@ fn cells(c: &Contributor) -> [String; 9] {
|
||||
/// 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()
|
||||
RichText::new(crate::localization::text(k.label().1)).strong()
|
||||
}
|
||||
|
||||
fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
|
||||
@@ -390,7 +390,8 @@ fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
|
||||
.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);
|
||||
let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k)))
|
||||
.on_hover_text(crate::localization::text(k.label().0));
|
||||
|
||||
if r.clicked() {
|
||||
if v.key == k {
|
||||
@@ -423,7 +424,7 @@ fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
|
||||
/// 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.");
|
||||
ui.label(crate::localization::text("No model credits were built into this copy."));
|
||||
return;
|
||||
}
|
||||
let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1);
|
||||
@@ -447,14 +448,14 @@ pub fn models_ui(ui: &mut egui::Ui) {
|
||||
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())))
|
||||
.map(|(i, title)| natural(ui, RichText::new(crate::localization::text(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()));
|
||||
aligned(ui, r, |ui| ui.label(RichText::new(crate::localization::text(title)).strong()));
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
+114
-81
@@ -268,33 +268,43 @@ fn clear_message(s: &Session, clips: &[ClipId], sources: &[SourceId]) -> Option<
|
||||
let listed: std::collections::BTreeSet<ClipId> = clips.iter().copied().collect();
|
||||
let names: Vec<&str> = s.tracks.iter().flat_map(|t| t.clips()).filter(|c| listed.contains(&c.id)).map(|c| c.name.as_str()).collect();
|
||||
let files: Vec<_> = sources.iter().filter_map(|id| s.source(*id)).collect();
|
||||
let count = |n: usize, what: &str| if n == 1 { format!("1 {what}") } else { format!("{n} {what}s") };
|
||||
let count = |n: usize, what: &str| {
|
||||
if n == 1 { crate::localized_format!("1 {what}", what = what) } else { crate::localized_format!("{n} {what}s", n = n, what = what) }
|
||||
};
|
||||
let what = match (names.as_slice(), files.as_slice()) {
|
||||
([], []) => return None,
|
||||
([name], []) => format!("the clip \"{name}\""),
|
||||
([], [f]) => format!("the file \"{}\"", f.name),
|
||||
(c, []) => count(c.len(), "clip"),
|
||||
([], f) => count(f.len(), "file"),
|
||||
(c, f) => format!("{} and {}", count(c.len(), "clip"), count(f.len(), "file")),
|
||||
([name], []) => crate::localized_format!("the clip \"{name}\"", name = name),
|
||||
([], [f]) => crate::localized_format!("the file \"{name}\"", name = f.name),
|
||||
(c, []) => count(c.len(), crate::localization::text("clip")),
|
||||
([], f) => count(f.len(), crate::localization::text("file")),
|
||||
(c, f) => crate::localized_format!(
|
||||
"{clips} and {files}",
|
||||
clips = count(c.len(), crate::localization::text("clip")),
|
||||
files = count(f.len(), crate::localization::text("file"))
|
||||
),
|
||||
};
|
||||
let mut text = format!("Remove {what} from the session?");
|
||||
let mut text = crate::localized_format!("Remove {what} from the session?", what = what);
|
||||
let used: Vec<(&str, usize)> =
|
||||
files.iter().map(|f| (f.name.as_str(), s.clips_using(f.id).filter(|c| !listed.contains(&c.id)).count())).filter(|(_, n)| *n > 0).collect();
|
||||
let n: usize = used.iter().map(|u| u.1).sum();
|
||||
let users = if n == 1 {
|
||||
"a clip on the timeline, which is removed too.".to_string()
|
||||
crate::localization::text("a clip on the timeline, which is removed too.").to_owned()
|
||||
} else {
|
||||
format!("{n} clips on the timeline, which are removed too.")
|
||||
crate::localized_format!("{n} clips on the timeline, which are removed too.", n = n)
|
||||
};
|
||||
match used.as_slice() {
|
||||
[] => {}
|
||||
[_] if files.len() == 1 => text += &format!(" It is used by {users}"),
|
||||
u if u.len() == files.len() => text += &format!(" They are used by {users}"),
|
||||
[(name, _)] => text += &format!(" \"{name}\" is used by {users}"),
|
||||
many => text += &format!(" {} of the files are used by {users}", many.len()),
|
||||
[_] if files.len() == 1 => text += &crate::localized_format!(" It is used by {users}", users = users),
|
||||
u if u.len() == files.len() => text += &crate::localized_format!(" They are used by {users}", users = users),
|
||||
[(name, _)] => text += &crate::localized_format!(" \"{name}\" is used by {users}", name = name, users = users),
|
||||
many => text += &crate::localized_format!(" {n} of the files are used by {users}", n = many.len(), users = users),
|
||||
}
|
||||
if !files.is_empty() && files.iter().all(|f| !f.unsaved) {
|
||||
text += if files.len() == 1 { " The file stays on disk." } else { " The files stay on disk." };
|
||||
text += if files.len() == 1 {
|
||||
crate::localization::text(" The file stays on disk.")
|
||||
} else {
|
||||
crate::localization::text(" The files stay on disk.")
|
||||
};
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
@@ -311,10 +321,10 @@ pub fn bounce_path(path: &str, format: EncodeFormat) -> std::path::PathBuf {
|
||||
/// The Bounce form's file row: a path field and a Browse button that also picks the format.
|
||||
fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, format: &mut EncodeFormat) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("File");
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "File");
|
||||
ui.label(crate::localization::text("File"));
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("File"));
|
||||
if let Some(pick) = &app.services.pick_save
|
||||
&& ui.button("Browse…").clicked()
|
||||
&& ui.button(crate::localization::text("Browse…")).clicked()
|
||||
&& let Some(p) = pick("file.bounce_mix", std::path::Path::new(path.as_str()))
|
||||
{
|
||||
match unicode(&p) {
|
||||
@@ -324,7 +334,7 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
|
||||
*format = picked;
|
||||
}
|
||||
}
|
||||
Err(e) => app.ui.status = e.to_string(),
|
||||
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -332,20 +342,20 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
|
||||
|
||||
/// The path prompt's form; the command to run once it is confirmed.
|
||||
fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut String, key: &str, enter: bool) -> Option<(String, Value)> {
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "Path");
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("Path"));
|
||||
let mut picked = None;
|
||||
// Import Audio picks several files at once; every other open dialog takes one.
|
||||
let multi = cmd == "file.import_audio" && app.services.pick_open_many.is_some();
|
||||
if multi
|
||||
&& let Some(pick) = &app.services.pick_open_many
|
||||
&& ui.button("Browse…").clicked()
|
||||
&& ui.button(crate::localization::text("Browse…")).clicked()
|
||||
{
|
||||
let mut files = pick(cmd);
|
||||
if files.len() > 1 {
|
||||
let texts: Result<Vec<&str>, _> = files.iter().map(|f| unicode(f)).collect();
|
||||
match texts {
|
||||
Ok(texts) => return Some((cmd.to_string(), json!({"paths": texts}))),
|
||||
Err(e) => app.ui.status = e.to_string(),
|
||||
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
}
|
||||
} else {
|
||||
picked = files.pop();
|
||||
@@ -356,36 +366,36 @@ fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut
|
||||
&& cmd != "session.save_as"
|
||||
&& cmd != "session.save_copy"
|
||||
&& key != "dir"
|
||||
&& ui.button("Browse…").clicked()
|
||||
&& ui.button(crate::localization::text("Browse…")).clicked()
|
||||
&& let Some(p) = pick(cmd, &[])
|
||||
{
|
||||
picked = Some(p);
|
||||
}
|
||||
if let Some(pick) = &app.services.pick_folder
|
||||
&& key == "dir"
|
||||
&& ui.button("Browse…").clicked()
|
||||
&& ui.button(crate::localization::text("Browse…")).clicked()
|
||||
&& let Some(p) = pick(std::path::Path::new(path.as_str()))
|
||||
{
|
||||
picked = Some(p);
|
||||
}
|
||||
if let Some(pick) = &app.services.pick_save
|
||||
&& (cmd == "session.save_as" || cmd == "session.save_copy")
|
||||
&& ui.button("Browse…").clicked()
|
||||
&& ui.button(crate::localization::text("Browse…")).clicked()
|
||||
&& let Some(p) = pick(cmd, std::path::Path::new(path.as_str()))
|
||||
{
|
||||
picked = Some(p);
|
||||
}
|
||||
match picked.as_deref().map(unicode) {
|
||||
Some(Ok(text)) => *path = text.to_owned(),
|
||||
Some(Err(e)) => app.ui.status = e.to_string(),
|
||||
Some(Err(e)) => app.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
None => {}
|
||||
}
|
||||
let file = soundcraft_engine::io::session_file(path);
|
||||
let replaces = soundcraft_engine::io::replaces(&app.engine, cmd, &file);
|
||||
if replaces {
|
||||
ui.label(format!("“{}” already exists. Do you want to replace it?", file.file_name().unwrap_or_default().to_string_lossy()));
|
||||
ui.label(crate::localized_format!("“{}” already exists. Do you want to replace it?", file.file_name().unwrap_or_default().to_string_lossy()));
|
||||
}
|
||||
if buttons(ui, if replaces { "Replace" } else { "OK" }, enter && !replaces) {
|
||||
if buttons(ui, crate::localization::text(if replaces { "Replace" } else { "OK" }), enter && !replaces) {
|
||||
let mut v = json!({});
|
||||
v[key] = json!(path);
|
||||
if replaces {
|
||||
@@ -407,10 +417,10 @@ fn strip_silence_form(
|
||||
let mut rename_from = None;
|
||||
let [threshold, min_ms, pre_ms, post_ms] = values;
|
||||
let before = [*threshold, *min_ms, *pre_ms, *post_ms];
|
||||
crate::widgets::fine_slider(ui, threshold, -96.0..=0.0, "Threshold dB");
|
||||
crate::widgets::fine_slider(ui, min_ms, 0.0..=4000.0, "Min strip duration ms");
|
||||
crate::widgets::fine_slider(ui, pre_ms, 0.0..=500.0, "Clip start pad ms");
|
||||
crate::widgets::fine_slider(ui, post_ms, 0.0..=2000.0, "Clip end pad ms");
|
||||
crate::widgets::fine_slider(ui, threshold, -96.0..=0.0, crate::localization::text("Threshold dB"));
|
||||
crate::widgets::fine_slider(ui, min_ms, 0.0..=4000.0, crate::localization::text("Min strip duration ms"));
|
||||
crate::widgets::fine_slider(ui, pre_ms, 0.0..=500.0, crate::localization::text("Clip start pad ms"));
|
||||
crate::widgets::fine_slider(ui, post_ms, 0.0..=2000.0, crate::localization::text("Clip end pad ms"));
|
||||
let values = [*threshold, *min_ms, *pre_ms, *post_ms];
|
||||
// The Edit window is drawn before this window, so it draws the rectangles for new values in the next frame.
|
||||
if values != before {
|
||||
@@ -424,13 +434,13 @@ fn strip_silence_form(
|
||||
ui.horizontal(|ui| {
|
||||
let mut mode = None;
|
||||
let mut rename = false;
|
||||
if ui.button("Extract").clicked() {
|
||||
if ui.button(crate::localization::text("Extract")).clicked() {
|
||||
mode = Some("extract");
|
||||
}
|
||||
if ui.button("Rename…").clicked() {
|
||||
if ui.button(crate::localization::text("Rename…")).clicked() {
|
||||
rename = true;
|
||||
}
|
||||
if ui.button("Separate").clicked() {
|
||||
if ui.button(crate::localization::text("Separate")).clicked() {
|
||||
mode = Some("separate");
|
||||
}
|
||||
// Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked.
|
||||
@@ -504,7 +514,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
|i: &egui::InputState| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }));
|
||||
let enter = !first_frame && ctx.input(fresh_enter) && (ctx.memory(|m| m.focused().is_none()) || ctx.text_edit_focused());
|
||||
let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape));
|
||||
egui::Window::new(egui::RichText::new(&title).font(bold(13.0)))
|
||||
egui::Window::new(egui::RichText::new(crate::localization::text(&title)).font(bold(13.0)))
|
||||
.id(egui::Id::unique(&title))
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.anchor(Align2::CENTER_CENTER, vec2(0.0, -80.0))
|
||||
@@ -522,15 +533,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
Dialog::NewSession { name, sample_rate, demo } => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name");
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(name), "Name");
|
||||
ui.label(crate::localization::text("Name"));
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
|
||||
});
|
||||
craft_ui::ComboBox::from_label("Sample Rate").selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
|
||||
for r in soundcraft_time::SampleRate::COMMON {
|
||||
ui.selectable_value(sample_rate, r, format!("{r} Hz"));
|
||||
}
|
||||
});
|
||||
crate::widgets::checkbox(ui, demo, "Start from the demo session");
|
||||
crate::widgets::checkbox(ui, demo, crate::localization::text("Start from the demo session"));
|
||||
if buttons(ui, "Create", enter) {
|
||||
action = Some((
|
||||
"session.new".into(),
|
||||
@@ -541,25 +552,25 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
Dialog::Bounce { path, format, bit_depth, normalize, dither } => {
|
||||
bounce_file_row(app, ui, path, format);
|
||||
ui.horizontal(|ui| {
|
||||
craft_ui::ComboBox::from_label("Format").selected_text(format.container().name()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
|
||||
for &f in EncodeFormat::ALL {
|
||||
ui.selectable_value(format, f, f.container().name());
|
||||
}
|
||||
});
|
||||
craft_ui::ComboBox::from_label("Bit Depth").selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
|
||||
for b in ["16", "24", "32f"] {
|
||||
ui.selectable_value(bit_depth, b.to_string(), format!("{b}-bit"));
|
||||
ui.selectable_value(bit_depth, b.to_string(), crate::localized_format!("{b}-bit", b = b));
|
||||
}
|
||||
});
|
||||
});
|
||||
crate::widgets::checkbox(ui, normalize, "Normalize to -0.1 dBFS");
|
||||
crate::widgets::checkbox(ui, normalize, crate::localization::text("Normalize to -0.1 dBFS"));
|
||||
// 32-bit float keeps every sample as it is: there is nothing to dither.
|
||||
ui.add_enabled_ui(bit_depth.as_str() != "32f", |ui| {
|
||||
crate::widgets::checkbox(ui, dither, "Dither (TPDF)")
|
||||
.on_hover_text("Adds ±1 LSB triangular dither when writing 16- or 24-bit files. Leave it off when the master chain already dithers.");
|
||||
crate::widgets::checkbox(ui, dither, crate::localization::text("Dither (TPDF)"))
|
||||
.on_hover_text(crate::localization::text("Adds ±1 LSB triangular dither when writing 16- or 24-bit files. Leave it off when the master chain already dithers."));
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new("Bounces the edit selection, or the whole session when nothing is selected.")
|
||||
egui::RichText::new(crate::localization::text("Bounces the edit selection, or the whole session when nothing is selected."))
|
||||
.small()
|
||||
.color(Tokens::current().text_dim),
|
||||
);
|
||||
@@ -602,7 +613,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
Dialog::Number { cmd, key, value, suffix, .. } => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(value).speed(0.1)).accessible_name(format!("Value in {suffix}"));
|
||||
ui.add(egui::DragValue::new(value).speed(0.1)).accessible_name(crate::localized_format!("Value in {suffix}", suffix = suffix));
|
||||
ui.label(suffix.as_str());
|
||||
});
|
||||
if buttons(ui, "OK", enter) {
|
||||
@@ -613,8 +624,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
Dialog::TempoChange { at, bpm } => {
|
||||
ui.horizontal(|ui| {
|
||||
// Same limits the engine enforces (time crate `valid_bpm`).
|
||||
ui.add(egui::DragValue::new(bpm).speed(0.1).range(5.0..=1000.0)).accessible_name("Tempo (BPM)");
|
||||
ui.label("bpm");
|
||||
ui.add(egui::DragValue::new(bpm).speed(0.1).range(5.0..=1000.0)).accessible_name(crate::localization::text("Tempo (BPM)"));
|
||||
ui.label(crate::localization::text("bpm"));
|
||||
});
|
||||
if buttons(ui, "OK", enter) {
|
||||
action = Some(tempo_change_action(*at, *bpm));
|
||||
@@ -629,7 +640,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
Dialog::Fades { shape } => {
|
||||
for s in soundcraft_model::FadeShape::ALL {
|
||||
ui.radio_value(shape, s.label().to_lowercase(), s.label());
|
||||
ui.radio_value(shape, s.label().to_lowercase(), crate::localization::text(s.label()));
|
||||
}
|
||||
if buttons(ui, "OK", enter) {
|
||||
action = Some(("edit.fades_create".into(), json!({"shape": shape})));
|
||||
@@ -644,7 +655,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
Dialog::StripSilenceRename { names, .. } => {
|
||||
strip_name_fields(ui, names, STRIP_NAME_LABELS);
|
||||
let cleared = ui.button("Clear").clicked();
|
||||
let cleared = ui.button(crate::localization::text("Clear")).clicked();
|
||||
if cleared {
|
||||
*names = StripNames::default();
|
||||
}
|
||||
@@ -654,7 +665,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
Dialog::AutoRename { clips, names } => {
|
||||
ui.label("Text for naming the clips that editing makes from the selected clips:");
|
||||
ui.label(crate::localization::text("Text for naming the clips that editing makes from the selected clips:"));
|
||||
strip_name_fields(ui, names, AUTO_NAME_LABELS);
|
||||
if buttons(ui, "OK", enter) {
|
||||
action = Some(auto_rename_action(clips, names));
|
||||
@@ -662,14 +673,14 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
Dialog::Group { id, name, edit, mix, members } => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name");
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(name), "Name");
|
||||
ui.label(crate::localization::text("Name"));
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
crate::widgets::checkbox(ui, edit, "Edit group");
|
||||
crate::widgets::checkbox(ui, mix, "Mix group");
|
||||
crate::widgets::checkbox(ui, edit, crate::localization::text("Edit group"));
|
||||
crate::widgets::checkbox(ui, mix, crate::localization::text("Mix group"));
|
||||
});
|
||||
ui.label("Tracks");
|
||||
ui.label(crate::localization::text("Tracks"));
|
||||
egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {
|
||||
for (_, n, on) in members.iter_mut() {
|
||||
crate::widgets::checkbox(ui, on, n.as_str());
|
||||
@@ -690,14 +701,14 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
Dialog::Session { frame_rate, bit_depth } => {
|
||||
craft_ui::ComboBox::from_label("Timecode Rate").selected_text(frame_rate.as_str()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
|
||||
for r in soundcraft_time::FrameRate::ALL {
|
||||
ui.selectable_value(frame_rate, r.label().to_string(), r.label());
|
||||
ui.selectable_value(frame_rate, r.label().to_string(), crate::localization::text(r.label()));
|
||||
}
|
||||
});
|
||||
craft_ui::ComboBox::from_label("Bit Depth").selected_text(bit_depth.as_str()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
|
||||
for b in ["16", "24", "32f"] {
|
||||
ui.selectable_value(bit_depth, b.to_string(), b);
|
||||
ui.selectable_value(bit_depth, b.to_string(), crate::localization::text(b));
|
||||
}
|
||||
});
|
||||
if buttons(ui, "OK", enter) {
|
||||
@@ -707,15 +718,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
Dialog::Loop { by, count, length, format, start, filled } => {
|
||||
let s = app.engine.session();
|
||||
ui.horizontal(|ui| {
|
||||
let count_label = ui.radio_value(by, LoopBy::Count, "Number of Loops");
|
||||
let count_label = ui.radio_value(by, LoopBy::Count, crate::localization::text("Number of Loops"));
|
||||
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=512)).labelled_by(count_label.id);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let length_label = ui.radio_value(by, LoopBy::Length, "Loop Length");
|
||||
let length_label = ui.radio_value(by, LoopBy::Length, crate::localization::text("Loop Length"));
|
||||
ui.add_enabled(*by == LoopBy::Length, egui::TextEdit::singleline(length).desired_width(140.0)).labelled_by(length_label.id);
|
||||
ui.label(format.label());
|
||||
ui.label(crate::localization::text(format.label()));
|
||||
});
|
||||
ui.radio_value(by, LoopBy::Fill, "Loop Until End of Session or Next Clip");
|
||||
ui.radio_value(by, LoopBy::Fill, crate::localization::text("Loop Until End of Session or Next Clip"));
|
||||
let params = loop_params(s, *by, *count, length, *format, *start, filled);
|
||||
if buttons_enabled(ui, "OK", enter, params.is_some()) {
|
||||
action = params.map(|p| ("clip.loop".into(), p));
|
||||
@@ -723,18 +734,18 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
Dialog::ScoreSetup { title, composer, bars_per_system, show_track_names } => {
|
||||
egui::Grid::new("score_setup").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
|
||||
ui.label("Title");
|
||||
ui.label(crate::localization::text("Title"));
|
||||
// The painted label is not an accesskit name; name the field itself.
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(title), "Score title");
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(title), crate::localization::text("Score title"));
|
||||
ui.end_row();
|
||||
ui.label("Composer");
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(composer), "Score composer");
|
||||
ui.label(crate::localization::text("Composer"));
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(composer), crate::localization::text("Score composer"));
|
||||
ui.end_row();
|
||||
ui.label("Bars per system");
|
||||
ui.add(egui::DragValue::new(bars_per_system).range(1..=16)).accessible_name("Bars per system");
|
||||
ui.label(crate::localization::text("Bars per system"));
|
||||
ui.add(egui::DragValue::new(bars_per_system).range(1..=16)).accessible_name(crate::localization::text("Bars per system"));
|
||||
ui.end_row();
|
||||
});
|
||||
crate::widgets::checkbox(ui, show_track_names, "Show track names");
|
||||
crate::widgets::checkbox(ui, show_track_names, crate::localization::text("Show track names"));
|
||||
if buttons(ui, "OK", enter) {
|
||||
action = Some((
|
||||
"file.score_setup".into(),
|
||||
@@ -747,19 +758,19 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let revert = then.0 == "session.revert";
|
||||
if revert || cfg!(target_arch = "wasm32") {
|
||||
let (question, ok) = if revert {
|
||||
(format!("Revert “{name}” to its last saved version?"), "Revert")
|
||||
(crate::localized_format!("Revert “{name}” to its last saved version?", name = name), "Revert")
|
||||
} else {
|
||||
(format!("Close “{name}” without saving?"), "Don't Save")
|
||||
(crate::localized_format!("Close “{name}” without saving?", name = name), "Don't Save")
|
||||
};
|
||||
ui.label(format!("{question} Your changes will be lost."));
|
||||
ui.label(crate::localized_format!("{question} Your changes will be lost.", question = question));
|
||||
if buttons(ui, ok, false) {
|
||||
action = Some(then.clone());
|
||||
}
|
||||
} else {
|
||||
ui.label(format!("Save changes to “{name}” before closing?"));
|
||||
ui.label(crate::localized_format!("Save changes to “{name}” before closing?", name = name));
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Don't Save").clicked() {
|
||||
if ui.button(crate::localization::text("Don't Save")).clicked() {
|
||||
action = Some(then.clone());
|
||||
}
|
||||
if buttons(ui, "Save", enter) {
|
||||
@@ -834,7 +845,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
} else {
|
||||
match run_then(app, &cmd, params) {
|
||||
Ok(v) if cmd == "file.export_clips" => {
|
||||
app.ui.status = format!("Exported {} clip(s) to {}", v["written"], v["dir"].as_str().unwrap_or_default());
|
||||
app.ui.status = crate::localized_format!("Exported {} clip(s) to {}", v["written"], v["dir"].as_str().unwrap_or_default());
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => app.ui.status = e,
|
||||
@@ -873,11 +884,11 @@ pub(crate) fn buttons_enabled(ui: &mut egui::Ui, ok: &str, enter: bool, ready: b
|
||||
let mut canceled = false;
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Cancel").clicked() {
|
||||
if ui.button(crate::localization::text("Cancel")).clicked() {
|
||||
canceled = true;
|
||||
ui.ctx().memory_mut(|m| m.data.insert_temp(egui::Id::unique("dlg_cancel"), true));
|
||||
}
|
||||
let b = egui::Button::new(egui::RichText::new(ok).strong()).fill(Tokens::current().accent);
|
||||
let b = egui::Button::new(egui::RichText::new(crate::localization::text(ok)).strong()).fill(Tokens::current().accent);
|
||||
if ui.add_enabled(ready, b).clicked() {
|
||||
pressed = true;
|
||||
}
|
||||
@@ -888,7 +899,7 @@ pub(crate) fn buttons_enabled(ui: &mut egui::Ui, ok: &str, enter: bool, ready: b
|
||||
/// A name field that takes the focus with its text selected, so typing replaces the old name.
|
||||
fn name_field(ui: &mut egui::Ui, name: &mut String) {
|
||||
let mut out = egui::TextEdit::singleline(name).show(ui);
|
||||
let _ = crate::widgets::named_text_field(out.response.response.clone(), "Name");
|
||||
let _ = crate::widgets::named_text_field(out.response.response.clone(), crate::localization::text("Name"));
|
||||
if !out.response.has_focus() {
|
||||
out.response.request_focus();
|
||||
let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(name.chars().count()));
|
||||
@@ -1305,6 +1316,28 @@ mod tests {
|
||||
assert_eq!(named[..2], ["SFX023.Reel1", "SFX024.Reel1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_question_is_assembled_in_portuguese() {
|
||||
let _scope = crate::localization::enter(crate::localization::Language::PortugueseBrazil);
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
let kick = e.session().sources.iter().find(|f| f.name == "Kick").map(|f| f.id).unwrap();
|
||||
let kick_clips: Vec<ClipId> = e.session().clips_using(kick).map(|c| c.id).collect();
|
||||
let message = |d: &Dialogs| match &d.open {
|
||||
Some(Dialog::ClearClips { message, .. }) => message.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let mut d = Dialogs::default();
|
||||
assert!(d.open_clear(&e, kick_clips, vec![kick]));
|
||||
let combined = message(&d);
|
||||
assert_eq!(combined, "Remover 3 clipes e 1 arquivo da sessão?");
|
||||
e.session_mut().sources.iter_mut().for_each(|f| f.unsaved = false);
|
||||
assert!(d.open_clear(&e, vec![], vec![kick]));
|
||||
assert_eq!(
|
||||
message(&d),
|
||||
"Remover o arquivo \"Kick\" da sessão? Ele é usado por 3 clipes na linha do tempo, que também serão removidos. O arquivo permanece no disco."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_always_asks_and_names_the_timeline_clips_that_go_too() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(super) fn audiosuite_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let v = params.entry(p.id.to_string()).or_insert(p.default);
|
||||
let mut wide = f64::from(*v);
|
||||
crate::widgets::FineSlider::new(&mut wide, f64::from(p.min)..=f64::from(p.max))
|
||||
.text(p.name)
|
||||
.text(crate::localization::text(p.name))
|
||||
.default_value(f64::from(p.default))
|
||||
.show(ui);
|
||||
*v = wide as f32;
|
||||
@@ -30,45 +30,48 @@ pub(super) fn audiosuite_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
"normalize" => {
|
||||
let v = params.entry("target_db".into()).or_insert(-0.1);
|
||||
let mut wide = f64::from(*v);
|
||||
crate::widgets::FineSlider::new(&mut wide, -24.0..=0.0).text("Peak dB").default_value(-0.1).show(ui);
|
||||
crate::widgets::FineSlider::new(&mut wide, -24.0..=0.0).text(crate::localization::text("Peak dB")).default_value(-0.1).show(ui);
|
||||
*v = wide as f32;
|
||||
}
|
||||
"time_stretch" => {
|
||||
let v = params.entry("ratio".into()).or_insert(1.0);
|
||||
let mut wide = f64::from(*v);
|
||||
crate::widgets::FineSlider::new(&mut wide, 0.25..=4.0).text("Length ratio").default_value(1.0).show(ui);
|
||||
crate::widgets::FineSlider::new(&mut wide, 0.25..=4.0)
|
||||
.text(crate::localization::text("Length ratio"))
|
||||
.default_value(1.0)
|
||||
.show(ui);
|
||||
*v = wide as f32;
|
||||
}
|
||||
"pitch_shift" => {
|
||||
let v = params.entry("semitones".into()).or_insert(0.0);
|
||||
let mut wide = f64::from(*v);
|
||||
crate::widgets::FineSlider::new(&mut wide, -24.0..=24.0).text("Semitones").default_value(0.0).show(ui);
|
||||
crate::widgets::FineSlider::new(&mut wide, -24.0..=24.0).text(crate::localization::text("Semitones")).default_value(0.0).show(ui);
|
||||
*v = wide as f32;
|
||||
}
|
||||
"speed_ramp" => {
|
||||
for (id, label, default, choices) in SPEED_RAMP_CHOICES {
|
||||
let v = params.entry(id.to_string()).or_insert(default);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(label);
|
||||
ui.label(crate::localization::text(label));
|
||||
for &(value, name) in choices {
|
||||
ui.radio_value(v, value, name);
|
||||
ui.radio_value(v, value, crate::localization::text(name));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
ui.label("No parameters.");
|
||||
ui.label(crate::localization::text("No parameters."));
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.ctx().memory_mut(|m| m.data.insert_temp(key, params.clone()));
|
||||
let hint = if soundcraft_dsp::is_generator(&process) {
|
||||
"Fills the selection on the selected tracks with a new clip."
|
||||
crate::localization::text("Fills the selection on the selected tracks with a new clip.")
|
||||
} else {
|
||||
"Processes the selected clips and replaces them with rendered audio."
|
||||
crate::localization::text("Processes the selected clips and replaces them with rendered audio.")
|
||||
};
|
||||
ui.label(egui::RichText::new(hint).small());
|
||||
if ui.button(egui::RichText::new("Render").strong()).clicked() {
|
||||
if ui.button(egui::RichText::new(crate::localization::text("Render")).strong()).clicked() {
|
||||
let p: serde_json::Map<String, Value> = params.iter().map(|(k, v)| (k.clone(), json!(v))).collect();
|
||||
let _ = app.run("audiosuite.process", json!({"process": process, "params": p}));
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn open_path(app: &mut SoundApp, path: &std::path::Path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
log::warn!("{e}");
|
||||
app.ui.status = e.to_string();
|
||||
app.ui.status = crate::localization::error_text(&e.to_string());
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -98,9 +98,13 @@ pub(super) fn open_pending_session(app: &mut SoundApp) {
|
||||
Ok(missing) => {
|
||||
// This path replaces the document without going through `SoundApp::run`.
|
||||
app.document_replaced();
|
||||
if missing.is_empty() { format!("Opened {name}") } else { format!("Opened {name} ({} missing media)", missing.len()) }
|
||||
if missing.is_empty() {
|
||||
crate::localized_format!("Opened {name}", name = name)
|
||||
} else {
|
||||
crate::localized_format!("Opened {name} ({missing} missing media)", name = name, missing = missing.len())
|
||||
}
|
||||
}
|
||||
Err(e) => e.to_string(),
|
||||
Err(e) => crate::localization::error_text(&e.to_string()),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ impl NewTracks {
|
||||
let id = egui::Id::unique(("new_tracks_row", row.key));
|
||||
let rect = egui::Rect::from_min_size(ui.available_rect_before_wrap().min, vec2(ui.available_width(), ui.spacing().interact_size.y));
|
||||
ui.scope_builder(egui::UiBuilder::new().scope_id(id).max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
|
||||
let label = ui.label("Create");
|
||||
let label = ui.label(crate::localization::text("Create"));
|
||||
let counter = ui
|
||||
.scope_builder(egui::UiBuilder::new().scope_id(id.with("count")), |ui| {
|
||||
ui.spacing_mut().interact_size.x = widths.count;
|
||||
@@ -180,19 +180,19 @@ impl NewTracks {
|
||||
if counter.gained_focus() {
|
||||
counter.scroll_to_me(Some(egui::Align::Center));
|
||||
}
|
||||
ui.label("new");
|
||||
ui.label(crate::localization::text("new"));
|
||||
let format = if has_format(&row.kind) {
|
||||
Some(
|
||||
craft_ui::ComboBox::from_id_salt("nt_fmt")
|
||||
.width(widths.format)
|
||||
.selected_text(&row.format)
|
||||
.selected_text(crate::localization::text(&row.format))
|
||||
.show_ui(ui, |ui| {
|
||||
for f in ChannelFormat::ALL {
|
||||
ui.selectable_value(&mut row.format, f.label().to_string(), f.label());
|
||||
ui.selectable_value(&mut row.format, f.label().to_string(), crate::localization::text(f.label()));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.accessible_name("Channel format"),
|
||||
.accessible_name(crate::localization::text("Channel format")),
|
||||
)
|
||||
} else {
|
||||
ui.allocate_space(vec2(widths.format, ui.spacing().interact_size.y));
|
||||
@@ -200,47 +200,55 @@ impl NewTracks {
|
||||
};
|
||||
let kind = craft_ui::ComboBox::from_id_salt("nt_kind")
|
||||
.width(widths.kind)
|
||||
.selected_text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label()))
|
||||
.selected_text(crate::localization::text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label())))
|
||||
.show_ui(ui, |ui| {
|
||||
for k in TrackKind::ALL {
|
||||
if ui.selectable_label(row.kind == k.id(), k.label()).clicked() {
|
||||
if ui.selectable_label(row.kind == k.id(), crate::localization::text(k.label())).clicked() {
|
||||
set_new_track_kind(&mut row.kind, &mut row.name, k);
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.accessible_name("Track kind");
|
||||
.accessible_name(crate::localization::text("Track kind"));
|
||||
let timebase = if has_timebase(&row.kind) {
|
||||
ui.label("in");
|
||||
ui.label(crate::localization::text("in"));
|
||||
Some(
|
||||
craft_ui::ComboBox::from_id_salt("nt_tb")
|
||||
.width(widths.timebase)
|
||||
.selected_text(if row.timebase == "ticks" { "Ticks" } else { "Samples" })
|
||||
.selected_text(crate::localization::text(if row.timebase == "ticks" { "Ticks" } else { "Samples" }))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut row.timebase, "samples".to_string(), "Samples");
|
||||
ui.selectable_value(&mut row.timebase, "ticks".to_string(), "Ticks");
|
||||
ui.selectable_value(&mut row.timebase, "samples".to_string(), crate::localization::text("Samples"));
|
||||
ui.selectable_value(&mut row.timebase, "ticks".to_string(), crate::localization::text("Ticks"));
|
||||
})
|
||||
.response
|
||||
.accessible_name("Timebase"),
|
||||
.accessible_name(crate::localization::text("Timebase")),
|
||||
)
|
||||
} else {
|
||||
ui.allocate_space(vec2(text_width(ui, "in"), ui.spacing().interact_size.y));
|
||||
ui.allocate_space(vec2(text_width(ui, crate::localization::text("in")), ui.spacing().interact_size.y));
|
||||
ui.allocate_space(vec2(widths.timebase, ui.spacing().interact_size.y));
|
||||
None
|
||||
};
|
||||
let label = ui.label("Name:");
|
||||
let label = ui.label(crate::localization::text("Name:"));
|
||||
let name = crate::widgets::named_text_field(
|
||||
ui.add(egui::TextEdit::singleline(&mut row.name).id(id.with("name")).desired_width(NAME_WIDTH)).labelled_by(label.id),
|
||||
"Name:",
|
||||
crate::localization::text("Name:"),
|
||||
);
|
||||
if format.iter().chain(timebase.iter()).chain([&kind, &name]).any(|r| r.clicked() || r.has_focus()) {
|
||||
self.active = index;
|
||||
}
|
||||
let size = vec2(ROW_BUTTON_WIDTH, ui.spacing().interact_size.y);
|
||||
if ui.add_enabled(len > 1, egui::Button::new("−").min_size(size)).on_hover_text("Remove this row").clicked() {
|
||||
if ui
|
||||
.add_enabled(len > 1, egui::Button::new(crate::localization::text("−")).min_size(size))
|
||||
.on_hover_text(crate::localization::text("Remove this row"))
|
||||
.clicked()
|
||||
{
|
||||
remove = Some(index);
|
||||
}
|
||||
if ui.add_enabled(len < MAX_TRACKS, egui::Button::new("+").min_size(size)).on_hover_text("Add a row below").clicked() {
|
||||
if ui
|
||||
.add_enabled(len < MAX_TRACKS, egui::Button::new(crate::localization::text("+")).min_size(size))
|
||||
.on_hover_text(crate::localization::text("Add a row below"))
|
||||
.clicked()
|
||||
{
|
||||
insert = Some(index);
|
||||
}
|
||||
});
|
||||
@@ -258,7 +266,7 @@ impl NewTracks {
|
||||
let total = self.rows.iter().fold(0_u32, |total, row| total.saturating_add(row.count));
|
||||
let can_create = !self.rows.is_empty() && total <= MAX_TRACKS as u32;
|
||||
if !can_create {
|
||||
ui.colored_label(ui.visuals().error_fg_color, "Create up to 128 tracks at a time.");
|
||||
ui.colored_label(ui.visuals().error_fg_color, crate::localization::text("Create up to 128 tracks at a time."));
|
||||
}
|
||||
// Enter on a focused row button changes that row only; it must not also submit the dialog.
|
||||
if crate::dialogs::buttons_enabled(ui, "Create", enter && !row_action, can_create) && !row_action {
|
||||
|
||||
@@ -94,39 +94,44 @@ fn beat_detective(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Beat Analysis").open(&mut open).default_size(vec2(360.0, 220.0)).show(ctx, |ui| {
|
||||
ui.label("Analyses the edit selection on the selected tracks.");
|
||||
ui.add(egui::Slider::new(&mut app.ops.beat_sensitivity, 0.0..=1.0).text("Sensitivity"));
|
||||
crate::widgets::checkbox(ui, &mut app.ops.beat_separate, "Separate clips at detected beats");
|
||||
crate::widgets::checkbox(ui, &mut app.ops.beat_set_tempo, "Set the session tempo from the beats");
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Analyze").clicked() {
|
||||
let r = app.run("event.beat_detective", json!({"sensitivity": app.ops.beat_sensitivity, "separate": false, "set_tempo": false}));
|
||||
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
|
||||
}
|
||||
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
|
||||
let r = app.run(
|
||||
"event.beat_detective",
|
||||
json!({"sensitivity": app.ops.beat_sensitivity, "separate": app.ops.beat_separate, "set_tempo": app.ops.beat_set_tempo}),
|
||||
);
|
||||
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
|
||||
egui::Window::new(crate::localization::text("Beat Analysis"))
|
||||
.id(egui::Id::unique("Beat Analysis"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 220.0))
|
||||
.show(ctx, |ui| {
|
||||
ui.label(crate::localization::text("Analyses the edit selection on the selected tracks."));
|
||||
ui.add(egui::Slider::new(&mut app.ops.beat_sensitivity, 0.0..=1.0).text(crate::localization::text("Sensitivity")));
|
||||
crate::widgets::checkbox(ui, &mut app.ops.beat_separate, crate::localization::text("Separate clips at detected beats"));
|
||||
crate::widgets::checkbox(ui, &mut app.ops.beat_set_tempo, crate::localization::text("Set the session tempo from the beats"));
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(crate::localization::text("Analyze")).clicked() {
|
||||
let r = app.run("event.beat_detective", json!({"sensitivity": app.ops.beat_sensitivity, "separate": false, "set_tempo": false}));
|
||||
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
|
||||
}
|
||||
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
|
||||
let r = app.run(
|
||||
"event.beat_detective",
|
||||
json!({"sensitivity": app.ops.beat_sensitivity, "separate": app.ops.beat_separate, "set_tempo": app.ops.beat_set_tempo}),
|
||||
);
|
||||
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(crate::localization::text("Identify Beat: selection is"));
|
||||
ui.add(egui::DragValue::new(&mut app.ops.identify_bars).range(1..=64))
|
||||
.accessible_name(crate::localization::text("Identify beat bars"));
|
||||
ui.label(crate::localization::text("bar(s)"));
|
||||
if ui.button(crate::localization::text("Set Tempo")).clicked() {
|
||||
let r = app.run("event.identify_beat", json!({"bars": app.ops.identify_bars}));
|
||||
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
|
||||
}
|
||||
});
|
||||
if !app.ops.beat_result.is_empty() {
|
||||
let s = app.ops.beat_result.clone();
|
||||
ui.label(egui::RichText::new(if s.len() > 300 { format!("{}…", &s[..300]) } else { s }).small());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Identify Beat: selection is");
|
||||
ui.add(egui::DragValue::new(&mut app.ops.identify_bars).range(1..=64)).accessible_name("Identify beat bars");
|
||||
ui.label("bar(s)");
|
||||
if ui.button("Set Tempo").clicked() {
|
||||
let r = app.run("event.identify_beat", json!({"bars": app.ops.identify_bars}));
|
||||
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
|
||||
}
|
||||
});
|
||||
if !app.ops.beat_result.is_empty() {
|
||||
let s = app.ops.beat_result.clone();
|
||||
ui.label(egui::RichText::new(if s.len() > 300 { format!("{}…", &s[..300]) } else { s }).small());
|
||||
}
|
||||
});
|
||||
app.ui.show_beat_detective = open;
|
||||
}
|
||||
|
||||
@@ -152,26 +157,34 @@ fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Tempo Operations").open(&mut open).default_size(vec2(360.0, 200.0)).show(ctx, |ui| {
|
||||
craft_ui::ComboBox::from_label("Curve").selected_text(app.ops.tempo_curve.clone()).show_ui(ui, |ui| {
|
||||
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
|
||||
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), c);
|
||||
}
|
||||
});
|
||||
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix("start bpm ")).accessible_name("Start tempo (BPM)");
|
||||
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix("end bpm ")).accessible_name("End tempo (BPM)");
|
||||
ui.label(
|
||||
egui::RichText::new(
|
||||
egui::Window::new(crate::localization::text("Tempo Operations"))
|
||||
.id(egui::Id::unique("Tempo Operations"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 200.0))
|
||||
.show(ctx, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Curve"))
|
||||
.selected_text(crate::localization::text(&app.ops.tempo_curve))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
|
||||
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), crate::localization::text(c));
|
||||
}
|
||||
});
|
||||
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix(crate::localization::text("start bpm ")))
|
||||
.accessible_name(crate::localization::text("Start tempo (BPM)"));
|
||||
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix(crate::localization::text("end bpm ")))
|
||||
.accessible_name(crate::localization::text("End tempo (BPM)"));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text(
|
||||
"Applies across the edit selection (constant: at the insertion point; scale: factor = end / start; stretch: factor = start / end).",
|
||||
)
|
||||
))
|
||||
.small(),
|
||||
);
|
||||
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
|
||||
let (id, p) = tempo_ops_apply(&app.ops.tempo_curve, app.ops.tempo_start, app.ops.tempo_end);
|
||||
let r = app.run(id, p);
|
||||
result_line(ui, &r);
|
||||
}
|
||||
});
|
||||
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
|
||||
let (id, p) = tempo_ops_apply(&app.ops.tempo_curve, app.ops.tempo_start, app.ops.tempo_end);
|
||||
let r = app.run(id, p);
|
||||
result_line(ui, &r);
|
||||
}
|
||||
});
|
||||
app.ui.show_tempo_ops = open;
|
||||
}
|
||||
|
||||
@@ -182,43 +195,51 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Time Operations").open(&mut open).default_size(vec2(360.0, 200.0)).show(ctx, |ui| {
|
||||
craft_ui::ComboBox::from_label("Operation").selected_text(app.ops.time_op.clone()).show_ui(ui, |ui| {
|
||||
for c in ["insert", "cut", "change meter", "move song start"] {
|
||||
ui.selectable_value(&mut app.ops.time_op, c.to_string(), c);
|
||||
egui::Window::new(crate::localization::text("Time Operations"))
|
||||
.id(egui::Id::unique("Time Operations"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 200.0))
|
||||
.show(ctx, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
|
||||
.selected_text(crate::localization::text(&app.ops.time_op))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in ["insert", "cut", "change meter", "move song start"] {
|
||||
ui.selectable_value(&mut app.ops.time_op, c.to_string(), crate::localization::text(c));
|
||||
}
|
||||
});
|
||||
match app.ops.time_op.as_str() {
|
||||
"change meter" => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64))
|
||||
.accessible_name(crate::localization::text("Meter numerator"));
|
||||
ui.label(crate::localization::text("/"));
|
||||
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
|
||||
for d in [2u32, 4, 8, 16] {
|
||||
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
|
||||
}
|
||||
});
|
||||
den.response.accessible_name(crate::localization::text("Meter denominator"));
|
||||
});
|
||||
}
|
||||
"insert" => {
|
||||
ui.add(egui::DragValue::new(&mut app.ops.time_seconds).range(0.0..=3600.0).suffix(" s"))
|
||||
.accessible_name(crate::localization::text("Time (seconds)"));
|
||||
}
|
||||
_ => {
|
||||
ui.label(egui::RichText::new(crate::localization::text("Uses the edit selection.")).small());
|
||||
}
|
||||
}
|
||||
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
|
||||
let at = app.engine.session().edit.selection.start;
|
||||
let r = match app.ops.time_op.as_str() {
|
||||
"insert" => app.run("event.insert_time", json!({"start": at, "length": {"seconds": app.ops.time_seconds}})),
|
||||
"cut" => app.run("event.cut_time", json!({})),
|
||||
"change meter" => app.run("event.meter", json!({"numerator": app.ops.meter_num, "denominator": app.ops.meter_den, "at": at})),
|
||||
_ => app.run("event.move_song_start", json!({"to": at})),
|
||||
};
|
||||
result_line(ui, &r);
|
||||
}
|
||||
});
|
||||
match app.ops.time_op.as_str() {
|
||||
"change meter" => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64)).accessible_name("Meter numerator");
|
||||
ui.label("/");
|
||||
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
|
||||
for d in [2u32, 4, 8, 16] {
|
||||
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
|
||||
}
|
||||
});
|
||||
den.response.accessible_name("Meter denominator");
|
||||
});
|
||||
}
|
||||
"insert" => {
|
||||
ui.add(egui::DragValue::new(&mut app.ops.time_seconds).range(0.0..=3600.0).suffix(" s")).accessible_name("Time (seconds)");
|
||||
}
|
||||
_ => {
|
||||
ui.label(egui::RichText::new("Uses the edit selection.").small());
|
||||
}
|
||||
}
|
||||
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
|
||||
let at = app.engine.session().edit.selection.start;
|
||||
let r = match app.ops.time_op.as_str() {
|
||||
"insert" => app.run("event.insert_time", json!({"start": at, "length": {"seconds": app.ops.time_seconds}})),
|
||||
"cut" => app.run("event.cut_time", json!({})),
|
||||
"change meter" => app.run("event.meter", json!({"numerator": app.ops.meter_num, "denominator": app.ops.meter_den, "at": at})),
|
||||
_ => app.run("event.move_song_start", json!({"to": at})),
|
||||
};
|
||||
result_line(ui, &r);
|
||||
}
|
||||
});
|
||||
app.ui.show_time_ops = open;
|
||||
}
|
||||
|
||||
@@ -227,44 +248,49 @@ fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("MIDI Operations").open(&mut open).default_size(vec2(360.0, 220.0)).show(ctx, |ui| {
|
||||
craft_ui::ComboBox::from_label("Operation").selected_text(app.ops.midi_op.clone()).show_ui(ui, |ui| {
|
||||
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
|
||||
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), c);
|
||||
}
|
||||
});
|
||||
match app.ops.midi_op.as_str() {
|
||||
"quantize" => {
|
||||
craft_ui::ComboBox::from_label("Grid").selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
|
||||
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
|
||||
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
|
||||
egui::Window::new(crate::localization::text("MIDI Operations"))
|
||||
.id(egui::Id::unique("MIDI Operations"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(360.0, 220.0))
|
||||
.show(ctx, |ui| {
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
|
||||
.selected_text(crate::localization::text(&app.ops.midi_op))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
|
||||
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), crate::localization::text(c));
|
||||
}
|
||||
});
|
||||
ui.add(egui::Slider::new(&mut app.ops.quant_strength, 0.0..=100.0).text("Strength %"));
|
||||
ui.add(egui::Slider::new(&mut app.ops.quant_swing, 0.0..=100.0).text("Swing %"));
|
||||
}
|
||||
"transpose" => {
|
||||
ui.add(egui::Slider::new(&mut app.ops.transpose, -48..=48).text("Semitones"));
|
||||
}
|
||||
"change velocity" => {
|
||||
ui.add(egui::Slider::new(&mut app.ops.velocity_add, -127..=127).text("Add"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ui.label(egui::RichText::new("Applies to the selected MIDI clips (or those under the selection).").small());
|
||||
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
|
||||
let r = match app.ops.midi_op.as_str() {
|
||||
match app.ops.midi_op.as_str() {
|
||||
"quantize" => {
|
||||
app.run("event.quantize", json!({"grid": app.ops.quant_grid, "strength": app.ops.quant_strength, "swing": app.ops.quant_swing}))
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
|
||||
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
|
||||
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
|
||||
}
|
||||
});
|
||||
ui.add(egui::Slider::new(&mut app.ops.quant_strength, 0.0..=100.0).text(crate::localization::text("Strength %")));
|
||||
ui.add(egui::Slider::new(&mut app.ops.quant_swing, 0.0..=100.0).text(crate::localization::text("Swing %")));
|
||||
}
|
||||
"transpose" => app.run("event.transpose", json!({"semitones": app.ops.transpose})),
|
||||
"change velocity" => app.run("event.change_velocity", json!({"add": app.ops.velocity_add})),
|
||||
"flatten performance" => app.run("event.flatten_performance", json!({})),
|
||||
_ => app.run("event.restore_performance", json!({})),
|
||||
};
|
||||
result_line(ui, &r);
|
||||
}
|
||||
});
|
||||
"transpose" => {
|
||||
ui.add(egui::Slider::new(&mut app.ops.transpose, -48..=48).text(crate::localization::text("Semitones")));
|
||||
}
|
||||
"change velocity" => {
|
||||
ui.add(egui::Slider::new(&mut app.ops.velocity_add, -127..=127).text(crate::localization::text("Add")));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ui.label(egui::RichText::new(crate::localization::text("Applies to the selected MIDI clips (or those under the selection).")).small());
|
||||
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
|
||||
let r = match app.ops.midi_op.as_str() {
|
||||
"quantize" => app
|
||||
.run("event.quantize", json!({"grid": app.ops.quant_grid, "strength": app.ops.quant_strength, "swing": app.ops.quant_swing})),
|
||||
"transpose" => app.run("event.transpose", json!({"semitones": app.ops.transpose})),
|
||||
"change velocity" => app.run("event.change_velocity", json!({"add": app.ops.velocity_add})),
|
||||
"flatten performance" => app.run("event.flatten_performance", json!({})),
|
||||
_ => app.run("event.restore_performance", json!({})),
|
||||
};
|
||||
result_line(ui, &r);
|
||||
}
|
||||
});
|
||||
app.ui.show_midi_ops = open;
|
||||
}
|
||||
|
||||
@@ -275,29 +301,36 @@ fn rtp(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
let targets = app.engine.target_tracks();
|
||||
sync_rtp_form(&mut app.ops, app.engine.session(), targets, ctx.dragged_id().is_some());
|
||||
egui::Window::new("MIDI Real-Time Properties").open(&mut open).default_size(vec2(340.0, 200.0)).show(ctx, |ui| {
|
||||
ui.label("Non-destructive, applied at playback to the selected MIDI tracks.");
|
||||
let mut changed = RtpChanged::default();
|
||||
changed.velocity = ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text("Velocity +")).changed();
|
||||
changed.transpose = ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text("Transpose")).changed();
|
||||
changed.duration = ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text("Duration %")).changed();
|
||||
changed.delay = ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text("Delay (ticks)")).changed();
|
||||
if let Some(p) = rtp_params(changed, &app.ops) {
|
||||
let _ = app.engine.execute_merged("event.midi_rtp", &p, "rtp");
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Write to Notes").clicked() {
|
||||
let _ = app.run("track.write_midi_rtp", json!({}));
|
||||
}
|
||||
if ui.button("Clear").clicked() {
|
||||
let _ = app.run("event.midi_rtp", json!({"clear": true}));
|
||||
app.ops.rtp_velocity = 0;
|
||||
app.ops.rtp_transpose = 0;
|
||||
app.ops.rtp_duration = 100.0;
|
||||
app.ops.rtp_delay = 0;
|
||||
egui::Window::new(crate::localization::text("MIDI Real-Time Properties"))
|
||||
.id(egui::Id::unique("MIDI Real-Time Properties"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(340.0, 200.0))
|
||||
.show(ctx, |ui| {
|
||||
ui.label(crate::localization::text("Non-destructive, applied at playback to the selected MIDI tracks."));
|
||||
let mut changed = RtpChanged::default();
|
||||
changed.velocity =
|
||||
ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text(crate::localization::text("Velocity +"))).changed();
|
||||
changed.transpose =
|
||||
ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text(crate::localization::text("Transpose"))).changed();
|
||||
changed.duration =
|
||||
ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text(crate::localization::text("Duration %"))).changed();
|
||||
changed.delay = ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text(crate::localization::text("Delay (ticks)"))).changed();
|
||||
if let Some(p) = rtp_params(changed, &app.ops) {
|
||||
let _ = app.engine.execute_merged("event.midi_rtp", &p, "rtp");
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(crate::localization::text("Write to Notes")).clicked() {
|
||||
let _ = app.run("track.write_midi_rtp", json!({}));
|
||||
}
|
||||
if ui.button(crate::localization::text("Clear")).clicked() {
|
||||
let _ = app.run("event.midi_rtp", json!({"clear": true}));
|
||||
app.ops.rtp_velocity = 0;
|
||||
app.ops.rtp_transpose = 0;
|
||||
app.ops.rtp_duration = 100.0;
|
||||
app.ops.rtp_delay = 0;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
app.ui.show_rtp = open;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,9 +85,9 @@ impl SoundApp {
|
||||
|
||||
/// The File › Open Recent submenu.
|
||||
pub fn menu(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
ui.menu_button("Open Recent", |ui| {
|
||||
ui.menu_button(crate::localization::text("Open Recent"), |ui| {
|
||||
if app.ui.recent_sessions.is_empty() {
|
||||
ui.add_enabled(false, egui::Button::new("No Recent Sessions"));
|
||||
ui.add_enabled(false, egui::Button::new(crate::localization::text("No Recent Sessions")));
|
||||
return;
|
||||
}
|
||||
let now = ui.ctx().input(|i| i.time);
|
||||
@@ -95,14 +95,17 @@ pub fn menu(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
let mut open = None;
|
||||
for (i, path) in app.ui.recent_sessions.iter().enumerate() {
|
||||
let here = exists.get(i).copied().unwrap_or(true);
|
||||
let text = if here { label(path) } else { format!("{} (missing)", label(path)) };
|
||||
let r = ui.add_enabled(here, egui::Button::new(text)).on_hover_text(path.as_str()).on_disabled_hover_text(format!("{path}\nnot found"));
|
||||
let text = if here { label(path) } else { crate::localized_format!("{} (missing)", label(path)) };
|
||||
let r = ui
|
||||
.add_enabled(here, egui::Button::new(text))
|
||||
.on_hover_text(path.as_str())
|
||||
.on_disabled_hover_text(crate::localized_format!("{path}\nnot found", path = path));
|
||||
if r.clicked() {
|
||||
open = Some(path.clone());
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Clear Recent").clicked() {
|
||||
if ui.button(crate::localization::text("Clear Recent")).clicked() {
|
||||
app.ui.recent_sessions.clear();
|
||||
app.recent_changed = true;
|
||||
ui.close();
|
||||
@@ -112,7 +115,7 @@ pub fn menu(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
// Through the dialog layer, so unsaved changes are asked about first.
|
||||
if let Err(e) = crate::dialogs::run_or_ask(app, "session.open", json!({"path": path})) {
|
||||
log::warn!("{path}: {e}");
|
||||
app.ui.status = format!("Could not open {path}: {e}");
|
||||
app.ui.status = crate::localized_format!("Could not open {path}: {e}", path = path, e = e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -9,22 +9,28 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let Some(left) = app.leftovers.first().cloned() else { return };
|
||||
let mut open = true;
|
||||
let mut recover = None;
|
||||
egui::Window::new(egui::RichText::new("Recover Unsaved Work").font(bold(13.0)))
|
||||
egui::Window::new(egui::RichText::new(crate::localization::text("Recover Unsaved Work")).font(bold(13.0)))
|
||||
.id(egui::Id::unique("Recover Unsaved Work"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.anchor(Align2::CENTER_CENTER, vec2(0.0, -80.0))
|
||||
.show(ctx, |ui| {
|
||||
let age = left.saved.elapsed().map_or_else(|_| "recently".into(), |d| ago(d.as_secs()));
|
||||
let what = if left.recording { "unsaved changes and an unfinished recording" } else { "unsaved changes" };
|
||||
ui.label(format!("“{}” has {what} from an earlier run, autosaved {age}.", left.name));
|
||||
let age = left.saved.elapsed().map_or_else(|_| crate::localization::text("recently").to_owned(), |d| ago(d.as_secs()));
|
||||
let what = crate::localization::text(if left.recording { "unsaved changes and an unfinished recording" } else { "unsaved changes" });
|
||||
ui.label(crate::localized_format!("“{name}” has {what} from an earlier run, autosaved {age}.", name = left.name, what = what, age = age));
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Discard").clicked() {
|
||||
if ui.button(crate::localization::text("Discard")).clicked() {
|
||||
recover = Some(false);
|
||||
}
|
||||
let recover_button = egui::Button::new(egui::RichText::new("Recover").strong()).fill(Tokens::current().accent);
|
||||
if ui.add_enabled(!app.engine.transport.recording, recover_button).on_disabled_hover_text("Stop recording first").clicked() {
|
||||
let recover_button =
|
||||
egui::Button::new(egui::RichText::new(crate::localization::text("Recover")).strong()).fill(Tokens::current().accent);
|
||||
if ui
|
||||
.add_enabled(!app.engine.transport.recording, recover_button)
|
||||
.on_disabled_hover_text(crate::localization::text("Stop recording first"))
|
||||
.clicked()
|
||||
{
|
||||
recover = Some(true);
|
||||
}
|
||||
});
|
||||
@@ -41,10 +47,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
|
||||
fn ago(secs: u64) -> String {
|
||||
let (n, unit) = match secs {
|
||||
0..60 => return "less than a minute ago".into(),
|
||||
0..60 => return crate::localization::text("less than a minute ago").to_owned(),
|
||||
60..3_600 => (secs / 60, "minute"),
|
||||
3_600..86_400 => (secs / 3_600, "hour"),
|
||||
_ => (secs / 86_400, "day"),
|
||||
};
|
||||
format!("{n} {unit}{} ago", if n == 1 { "" } else { "s" })
|
||||
let unit = crate::localization::text(unit);
|
||||
if n == 1 {
|
||||
crate::localized_format!("{n} {unit} ago", n = n, unit = unit)
|
||||
} else {
|
||||
crate::localized_format!("{n} {unit}s ago", n = n, unit = unit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,10 +141,10 @@ fn spot_field_row(ui: &mut Ui, s: &Session, d: &mut Spot, i: usize, label: &str)
|
||||
}
|
||||
|
||||
fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples) {
|
||||
ui.label("Original Time Stamp");
|
||||
ui.label(crate::localization::text("Original Time Stamp"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(s.format_position(at, TimeFormat::Timecode)).font(mono(13.0)));
|
||||
if ui.button("Use").on_hover_text("Spot to where it was recorded").clicked() {
|
||||
if ui.button(crate::localization::text("Use")).on_hover_text(crate::localization::text("Spot to where it was recorded")).clicked() {
|
||||
d.start = at;
|
||||
}
|
||||
});
|
||||
@@ -154,12 +154,13 @@ fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples)
|
||||
/// The dialog's fields; the caller adds OK and Cancel.
|
||||
pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
|
||||
egui::Grid::new("spot").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
|
||||
let scale = ui.label("Time Scale");
|
||||
let time_scale = craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(d.format.label()).show_ui(ui, |ui| {
|
||||
for f in TimeFormat::ALL {
|
||||
ui.selectable_value(&mut d.format, f, f.label());
|
||||
}
|
||||
});
|
||||
let scale = ui.label(crate::localization::text("Time Scale"));
|
||||
let time_scale =
|
||||
craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
|
||||
for f in TimeFormat::ALL {
|
||||
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
|
||||
}
|
||||
});
|
||||
time_scale.response.labelled_by(scale.id);
|
||||
ui.end_row();
|
||||
for (i, label) in FIELDS.into_iter().enumerate() {
|
||||
@@ -168,7 +169,7 @@ pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
|
||||
}
|
||||
spot_field_row(ui, s, d, i, label);
|
||||
}
|
||||
ui.label("Duration");
|
||||
ui.label(crate::localization::text("Duration"));
|
||||
ui.label(RichText::new(format_length(d.start, d.len, d.format, s.sample_rate, &s.tempo, s.frame_rate)).font(mono(13.0)));
|
||||
ui.end_row();
|
||||
if let Some(at) = d.stamp {
|
||||
|
||||
@@ -150,23 +150,23 @@ pub(super) const AUTO_NAME_LABELS: [&str; 2] = ["Starting Number", "Number of Pl
|
||||
pub(super) fn strip_name_fields(ui: &mut egui::Ui, names: &mut StripNames, labels: [&str; 2]) {
|
||||
let [number, zeros] = labels;
|
||||
egui::Grid::new("strip_names").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
|
||||
let name = ui.label("Name");
|
||||
let name = ui.label(crate::localization::text("Name"));
|
||||
ui.text_edit_singleline(&mut names.name).labelled_by(name.id);
|
||||
ui.end_row();
|
||||
let number = ui.label(number);
|
||||
let number = ui.label(crate::localization::text(number));
|
||||
ui.add(egui::DragValue::new(&mut names.number).range(0..=StripNames::MAX_NUMBER)).labelled_by(number.id);
|
||||
ui.end_row();
|
||||
let zeros = ui.label(zeros);
|
||||
let zeros = ui.label(crate::localization::text(zeros));
|
||||
ui.add(egui::DragValue::new(&mut names.zeros).range(0..=StripNames::MAX_ZEROS)).labelled_by(zeros.id);
|
||||
ui.end_row();
|
||||
let suffix = ui.label("Suffix");
|
||||
let suffix = ui.label(crate::localization::text("Suffix"));
|
||||
ui.text_edit_singleline(&mut names.suffix).labelled_by(suffix.id);
|
||||
ui.end_row();
|
||||
});
|
||||
let example = if names.name.trim().is_empty() {
|
||||
"Without a name, the clips keep their names.".to_string()
|
||||
crate::localization::text("Without a name, the clips keep their names.").to_string()
|
||||
} else {
|
||||
format!("First clip: {}", names.clip_name(0))
|
||||
crate::localized_format!("First clip: {}", names.clip_name(0))
|
||||
};
|
||||
ui.label(egui::RichText::new(example).small().color(Tokens::current().text_dim));
|
||||
}
|
||||
|
||||
@@ -452,7 +452,7 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
|
||||
if edit { std::mem::replace(&mut app.ui.docking, edit_default()) } else { std::mem::replace(&mut app.ui.mix_docking, mix_default()) };
|
||||
let before_sync = workspace.clone();
|
||||
if let Err(error) = (if edit { validate(&workspace) } else { validate_mix(&workspace) }).and_then(|()| sync(&mut workspace, app, edit)) {
|
||||
app.ui.status = format!("Panel layout could not be restored: {error}");
|
||||
app.ui.status = crate::localized_format!("Panel layout could not be restored: {error}", error = error);
|
||||
workspace = if edit { edit_default() } else { mix_default() };
|
||||
let _ = sync(&mut workspace, app, edit);
|
||||
}
|
||||
@@ -481,7 +481,7 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
|
||||
ui,
|
||||
&workspace.layout,
|
||||
&style,
|
||||
|panel| panel.label().into(),
|
||||
|panel| crate::localization::text(panel.label()).into(),
|
||||
permissions,
|
||||
panel_limits,
|
||||
|ui, panel| match panel {
|
||||
@@ -508,7 +508,7 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
|
||||
store(app, workspace, edit);
|
||||
for action in output.actions {
|
||||
if let Err(error) = command_for(app, &DockCommand::Layout { action }, edit) {
|
||||
app.ui.status = format!("Panel move was not applied: {error}");
|
||||
app.ui.status = crate::localized_format!("Panel move was not applied: {error}", error = error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,8 @@ use overlay::overlay;
|
||||
#[cfg(test)]
|
||||
use overlay::playhead_colour;
|
||||
pub use rulers::ruler_height;
|
||||
#[cfg(test)]
|
||||
use rulers::{arrow_half, selection_marker_colour, selection_markers};
|
||||
use rulers::{column_titles, draw_rulers, views_button};
|
||||
pub use scroll::zoom_toggle;
|
||||
#[cfg(test)]
|
||||
@@ -81,7 +83,7 @@ fn dock_tabs(app: &mut SoundApp, ui: &mut Ui) {
|
||||
("MEMORY LOCATIONS", app.ui.show_memory_locations, "window.memory_locations"),
|
||||
("UNDO HISTORY", app.ui.show_undo_history, "window.undo_history"),
|
||||
] {
|
||||
let g = ui.painter().layout_no_wrap(label.to_string(), bold(10.5), if on { Color32::WHITE } else { t.text_dim });
|
||||
let g = ui.painter().layout_no_wrap(crate::localization::text(label).to_string(), bold(10.5), if on { Color32::WHITE } else { t.text_dim });
|
||||
let tr = Rect::from_min_size(pos2(x, r.min.y + 2.0), vec2(g.size().x + 16.0, r.height() - 4.0));
|
||||
if on {
|
||||
ui.painter().rect_filled(tr, 3.0, t.accent_dark);
|
||||
@@ -98,25 +100,20 @@ fn status_bar(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let t = Tokens::current();
|
||||
let r = ui.max_rect();
|
||||
let s = app.engine.session();
|
||||
let mut left = format!(
|
||||
"{} · {} Hz · {} · {} tracks · {}",
|
||||
s.name,
|
||||
s.sample_rate.hz(),
|
||||
match s.bit_depth {
|
||||
soundcraft_model::BitDepthSetting::Int16 => "16-bit",
|
||||
soundcraft_model::BitDepthSetting::Int24 => "24-bit",
|
||||
soundcraft_model::BitDepthSetting::Float32 => "32-bit float",
|
||||
},
|
||||
s.tracks.len(),
|
||||
app.ui.status
|
||||
);
|
||||
let depth = match s.bit_depth {
|
||||
soundcraft_model::BitDepthSetting::Int16 => crate::localization::text("16-bit"),
|
||||
soundcraft_model::BitDepthSetting::Int24 => crate::localization::text("24-bit"),
|
||||
soundcraft_model::BitDepthSetting::Float32 => crate::localization::text("32-bit float"),
|
||||
};
|
||||
let tracks = if s.tracks.len() == 1 { crate::localized_format!("1 track") } else { crate::localized_format!("{n} tracks", n = s.tracks.len()) };
|
||||
let mut left = crate::localized_format!("{} · {} Hz · {} · {} · {}", s.name, s.sample_rate.hz(), depth, tracks, app.ui.status);
|
||||
soundcraft_model::truncate_chars(&mut left, 4 * soundcraft_model::MAX_NAME_CHARS);
|
||||
ui.painter().text(pos2(r.min.x + 10.0, r.center().y), Align2::LEFT_CENTER, left, regular(11.0), t.text_dim);
|
||||
let undo = app.engine.undo_label().map_or(String::new(), |l| format!("Undo {l}"));
|
||||
let undo = app.engine.undo_label().map_or(String::new(), |l| crate::localized_format!("Undo {l}", l = crate::localization::text(l)));
|
||||
ui.painter().text(
|
||||
pos2(r.max.x - 10.0, r.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
if app.frame_ms < 50.0 { format!("{undo} {:.1} ms/frame", app.frame_ms) } else { undo },
|
||||
if app.frame_ms < 50.0 { crate::localized_format!("{undo} {ms:.1} ms/frame", undo = undo, ms = app.frame_ms) } else { undo },
|
||||
regular(11.0),
|
||||
t.text_dim,
|
||||
);
|
||||
|
||||
@@ -263,7 +263,13 @@ fn draw_clip_content(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
painter.text(body_r.center(), Align2::CENTER_CENTER, "media offline", regular(10.0), Color32::from_rgb(220, 120, 120));
|
||||
painter.text(
|
||||
body_r.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
crate::localization::text("media offline"),
|
||||
regular(10.0),
|
||||
Color32::from_rgb(220, 120, 120),
|
||||
);
|
||||
}
|
||||
}
|
||||
ClipContent::Video { .. } => {} // thumbnails: video_track::draw_lane
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::layout::STRIP_W;
|
||||
use super::tracks::{click_track, folder_depth, height_targets, in_edit_window, track_context_menu, view_label, view_menu};
|
||||
use super::{
|
||||
Align2, AutoParam, Color32, Gesture, Pos2, Rect, Sense, Shape, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, bold,
|
||||
groove, json, level_pos, meter_pos, pos2, raised_key, regular, rgb, shade, vec2,
|
||||
Align2, AutoParam, Color32, Gesture, Pos2, Rect, Sense, Shape, SoundApp, Stroke, StrokeKind, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui,
|
||||
bold, groove, json, level_pos, meter_pos, pos2, raised_key, regular, rgb, shade, vec2,
|
||||
};
|
||||
|
||||
/// Draw one track header: resize edge, selection and context menu, folder/options control, automation-lane toggle,
|
||||
@@ -94,11 +94,11 @@ fn strip_buttons(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
ui.painter().circle_filled(round.center(), 5.0, shade(strip, if rresp.hovered() { 0.6 } else { 0.45 }));
|
||||
arrow(ui.painter(), round.center(), !track.is_folder() || track.folder_open, ink);
|
||||
if track.is_folder() {
|
||||
if rresp.on_hover_text(if track.folder_open { "Close folder" } else { "Open folder" }).clicked() {
|
||||
if rresp.on_hover_text(crate::localization::text(if track.folder_open { "Close folder" } else { "Open folder" })).clicked() {
|
||||
let _ = app.run("track.folder_toggle", json!({"track": id.0}));
|
||||
}
|
||||
} else {
|
||||
egui::Popup::menu(&rresp.on_hover_text("Track options")).show(|ui| track_context_menu(app, ui, id));
|
||||
egui::Popup::menu(&rresp.on_hover_text(crate::localization::text("Track options"))).show(|ui| track_context_menu(app, ui, id));
|
||||
}
|
||||
if h >= 40.0 && track.kind.has_playlist() {
|
||||
let ar = at(3.0, h - 12.0, 9.0, 9.0);
|
||||
@@ -109,7 +109,7 @@ fn strip_buttons(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
ui.painter().line_segment([a, b], Stroke::new(1.0, ink));
|
||||
ui.painter().circle_filled(a, 1.3, ink);
|
||||
ui.painter().circle_filled(b, 1.3, ink);
|
||||
if aresp.on_hover_text(if showing { "Hide automation" } else { "Show volume automation" }).clicked() {
|
||||
if aresp.on_hover_text(crate::localization::text(if showing { "Hide automation" } else { "Show volume automation" })).clicked() {
|
||||
let view = if !showing {
|
||||
"volume"
|
||||
} else if track.kind.is_midi() {
|
||||
@@ -199,14 +199,14 @@ fn playlist_menu(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, hea
|
||||
let presp = ui.interact(pl_r, ui.scope_id().with(("pl", id.0)), Sense::click());
|
||||
ui.painter().rect_filled(pl_r, 1.5, shade(head_bg, if presp.hovered() { -0.2 } else { -0.35 }));
|
||||
arrow(ui.painter(), pos2(pl_r.center().x, pl_r.min.y + 5.75), true, t.text);
|
||||
egui::Popup::menu(&presp.on_hover_text("Playlists")).show(|ui| {
|
||||
if ui.button("New...").clicked() {
|
||||
egui::Popup::menu(&presp.on_hover_text(crate::localization::text("Playlists"))).show(|ui| {
|
||||
if ui.button(crate::localization::text("New...")).clicked() {
|
||||
let _ = app.run("track.playlist_new", json!({"track": id.0}));
|
||||
}
|
||||
if ui.button("Duplicate...").clicked() {
|
||||
if ui.button(crate::localization::text("Duplicate...")).clicked() {
|
||||
let _ = app.run("track.playlist_duplicate", json!({"track": id.0}));
|
||||
}
|
||||
if ui.button("Delete Unused...").clicked() {
|
||||
if ui.button(crate::localization::text("Delete Unused...")).clicked() {
|
||||
let _ = app.run("track.playlist_delete_unused", json!({"track": id.0}));
|
||||
}
|
||||
ui.separator();
|
||||
@@ -227,7 +227,7 @@ fn toggle_keys(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
let is_master = track.kind == TrackKind::Master;
|
||||
if h >= 37.0 && !is_master {
|
||||
let (records, mixes) = (track.kind.has_playlist(), true);
|
||||
let implied = !m.solo && app.engine.session().tracks.iter().any(|t| t.mixer.solo);
|
||||
let implied = soundcraft_mix::solo_mutes(app.engine.session(), track);
|
||||
let keys = [
|
||||
(HeaderKey::Rec, m.record_arm, false, "mix.record_arm", records),
|
||||
(HeaderKey::Input, m.input_monitor, false, "mix.input_monitor", records),
|
||||
@@ -256,10 +256,10 @@ fn view_selector(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
ui,
|
||||
at(17.0, view_y, 105.0, 17.0),
|
||||
ui.scope_id().with(("view", id.0)),
|
||||
&view_label(&track.view),
|
||||
crate::localization::text(&view_label(&track.view)),
|
||||
t.text,
|
||||
true,
|
||||
&format!("Track view for {}", track.name),
|
||||
&crate::localized_format!("Track view for {}", track.name),
|
||||
);
|
||||
egui::Popup::menu(&vresp).show(|ui| view_menu(app, ui, track));
|
||||
}
|
||||
@@ -272,11 +272,19 @@ fn view_selector(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
soundcraft_model::AutomationMode::Latch => t.auto_latch,
|
||||
_ => t.text_dim,
|
||||
};
|
||||
let mode_name = format!("Automation mode for {}", track.name);
|
||||
let aresp = header_selector(ui, at(17.0, 39.0, 105.0, 17.0), ui.scope_id().with(("auto_mode", id.0)), mode.label(), col, true, &mode_name);
|
||||
let mode_name = crate::localized_format!("Automation mode for {}", track.name);
|
||||
let aresp = header_selector(
|
||||
ui,
|
||||
at(17.0, 39.0, 105.0, 17.0),
|
||||
ui.scope_id().with(("auto_mode", id.0)),
|
||||
crate::localization::text(mode.label()),
|
||||
col,
|
||||
true,
|
||||
&mode_name,
|
||||
);
|
||||
egui::Popup::menu(&aresp).show(|ui| {
|
||||
for m in soundcraft_model::AutomationMode::ALL {
|
||||
if ui.selectable_label(m == mode, m.label()).clicked() {
|
||||
if ui.selectable_label(m == mode, crate::localization::text(m.label())).clicked() {
|
||||
let _ = app.run("mix.automation_mode", json!({"track": id.0, "mode": m.label()}));
|
||||
}
|
||||
}
|
||||
@@ -303,17 +311,25 @@ fn voice_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
let d = vec2(a.to_radians().sin(), a.to_radians().cos()) * 3.5;
|
||||
ui.painter().line_segment([r.center() - d, r.center() + d], Stroke::new(1.5, t.text));
|
||||
}
|
||||
if resp.on_hover_text(if track.frozen { "Unfreeze" } else { "Freeze" }).clicked() {
|
||||
if resp.on_hover_text(crate::localization::text(if track.frozen { "Unfreeze" } else { "Freeze" })).clicked() {
|
||||
let _ = app.run("track.freeze", json!({"tracks": [id.0]}));
|
||||
}
|
||||
}
|
||||
if !matches!(track.kind, TrackKind::Master | TrackKind::Vca | TrackKind::Folder) {
|
||||
let (voice, color) = if track.inactive { ("off", t.text_dim) } else { ("dyn", t.text) };
|
||||
let voice_name = format!("Voice for {}", track.name);
|
||||
let resp = header_selector(ui, at(31.0, 57.0, 31.0, 17.0), ui.scope_id().with(("voice", id.0)), voice, color, false, &voice_name);
|
||||
egui::Popup::menu(&resp.on_hover_text("Voice: dyn plays the track, off makes it inactive")).show(|ui| {
|
||||
let voice_name = crate::localized_format!("Voice for {}", track.name);
|
||||
let resp = header_selector(
|
||||
ui,
|
||||
at(31.0, 57.0, 31.0, 17.0),
|
||||
ui.scope_id().with(("voice", id.0)),
|
||||
crate::localization::text(voice),
|
||||
color,
|
||||
false,
|
||||
&voice_name,
|
||||
);
|
||||
egui::Popup::menu(&resp.on_hover_text(crate::localization::text("Voice: dyn plays the track, off makes it inactive"))).show(|ui| {
|
||||
for (label, inactive) in [("dyn", false), ("off", true)] {
|
||||
if ui.selectable_label(track.inactive == inactive, label).clicked() {
|
||||
if ui.selectable_label(track.inactive == inactive, crate::localization::text(label)).clicked() {
|
||||
let _ = app.run("track.make_inactive", json!({"tracks": [id.0], "inactive": inactive}));
|
||||
}
|
||||
}
|
||||
@@ -327,11 +343,19 @@ fn voice_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
|
||||
soundcraft_model::AutomationMode::Latch => t.auto_latch,
|
||||
_ => t.text_dim,
|
||||
};
|
||||
let mode_name = format!("Automation mode for {}", track.name);
|
||||
let aresp = header_selector(ui, at(63.0, 57.0, 59.0, 17.0), ui.scope_id().with(("auto_mode", id.0)), mode.label(), col, true, &mode_name);
|
||||
let mode_name = crate::localized_format!("Automation mode for {}", track.name);
|
||||
let aresp = header_selector(
|
||||
ui,
|
||||
at(63.0, 57.0, 59.0, 17.0),
|
||||
ui.scope_id().with(("auto_mode", id.0)),
|
||||
crate::localization::text(mode.label()),
|
||||
col,
|
||||
true,
|
||||
&mode_name,
|
||||
);
|
||||
egui::Popup::menu(&aresp).show(|ui| {
|
||||
for m in soundcraft_model::AutomationMode::ALL {
|
||||
if ui.selectable_label(m == mode, m.label()).clicked() {
|
||||
if ui.selectable_label(m == mode, crate::localization::text(m.label())).clicked() {
|
||||
let _ = app.run("mix.automation_mode", json!({"track": id.0, "mode": m.label()}));
|
||||
}
|
||||
}
|
||||
@@ -378,10 +402,13 @@ fn field_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, head_bg
|
||||
let resp = ui.interact(field, ui.scope_id().with(("field", id.0)), Sense::click());
|
||||
ui.painter().rect_filled(field, 2.0, shade(head_bg, if resp.hovered() { -0.02 } else { -0.1 }));
|
||||
if track.kind == TrackKind::Instrument {
|
||||
let name =
|
||||
track.instrument.as_ref().and_then(|i| crate::mix_window::plugin_info(&i.plugin)).map_or("no instrument", |p| p.short_name);
|
||||
let name = track
|
||||
.instrument
|
||||
.as_ref()
|
||||
.and_then(|i| crate::mix_window::plugin_info(&i.plugin))
|
||||
.map_or_else(|| crate::localization::text("no instrument"), |p| p.short_name);
|
||||
ui.painter().with_clip_rect(field).text(pos2(field.min.x + 5.0, field.center().y), Align2::LEFT_CENTER, name, bold(10.0), t.text);
|
||||
egui::Popup::menu(&resp.on_hover_text("Instrument"))
|
||||
egui::Popup::menu(&resp.on_hover_text(crate::localization::text("Instrument")))
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.show(|ui| crate::mix_window::instrument_menu(app, ui, id));
|
||||
} else {
|
||||
@@ -397,7 +424,7 @@ fn field_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, head_bg
|
||||
t.text,
|
||||
);
|
||||
}
|
||||
egui::Popup::menu(&resp.on_hover_text("Elastic Audio")).show(|ui| {
|
||||
egui::Popup::menu(&resp.on_hover_text(crate::localization::text("Elastic Audio"))).show(|ui| {
|
||||
for alg in ["none", "polyphonic", "rhythmic", "monophonic", "varispeed", "x-form"] {
|
||||
let current = track.elastic.as_deref().unwrap_or("none") == alg;
|
||||
if ui.selectable_label(current, soundcraft_engine::feature_names::display_label(alg)).clicked() {
|
||||
@@ -427,6 +454,7 @@ pub(super) fn header_selector(ui: &Ui, r: Rect, id: egui::Id, text: &str, color:
|
||||
let resp = ui.interact(r, id, Sense::click());
|
||||
resp.widget_info(|| {
|
||||
let mut info = egui::WidgetInfo::labeled(egui::accesskit::Role::ComboBox, ui.is_enabled(), name);
|
||||
// `text` can be a user-defined route name (a bus called "File"), so show it unchanged.
|
||||
info.current_text_value = Some(text.to_string());
|
||||
info
|
||||
});
|
||||
@@ -451,14 +479,23 @@ enum HeaderKey {
|
||||
/// mute that another track's solo implies). Record keys stay dark red when off, as in Pro Tools.
|
||||
fn header_toggle(ui: &Ui, r: Rect, track: TrackId, track_name: &str, key: HeaderKey, lit: bool, implied: bool) -> egui::Response {
|
||||
let t = Tokens::current();
|
||||
let (label, color) = match key {
|
||||
let (source_label, color) = match key {
|
||||
HeaderKey::Rec => ("Record enable", t.rec),
|
||||
HeaderKey::Input => ("Input monitoring", t.input),
|
||||
HeaderKey::Solo => ("Solo", t.solo),
|
||||
HeaderKey::Mute => ("Mute", t.mute),
|
||||
};
|
||||
let name = format!("{label} for {track_name}");
|
||||
let resp = ui.interact(r, ui.scope_id().with((label, track.0)), Sense::click());
|
||||
let label = crate::localization::text(source_label);
|
||||
// Fixed badges, independent of the translated label: in some languages the translated
|
||||
// labels for two different buttons would otherwise start with the same letter.
|
||||
let badge = match key {
|
||||
HeaderKey::Rec => "",
|
||||
HeaderKey::Input => "I",
|
||||
HeaderKey::Solo => "S",
|
||||
HeaderKey::Mute => "M",
|
||||
};
|
||||
let name = crate::localized_format!("{} for {}", label, track_name);
|
||||
let resp = ui.interact(r, ui.scope_id().with((source_label, track.0)), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), lit, &name));
|
||||
let rec = key == HeaderKey::Rec;
|
||||
let (tint, k) = if lit {
|
||||
@@ -482,7 +519,7 @@ fn header_toggle(ui: &Ui, r: Rect, track: TrackId, track_name: &str, key: Header
|
||||
if rec {
|
||||
ui.painter().circle_filled(r.center(), 4.0, if lit { Color32::WHITE } else { t.text.lerp_to_gamma(color, 0.3) });
|
||||
} else {
|
||||
ui.painter().text(r.center(), Align2::CENTER_CENTER, label.get(..1).unwrap_or_default(), bold(11.0), ink);
|
||||
ui.painter().text(r.center(), Align2::CENTER_CENTER, badge, bold(11.0), ink);
|
||||
}
|
||||
resp.on_hover_text(label)
|
||||
}
|
||||
@@ -532,7 +569,7 @@ pub(super) fn header_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, col:
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r.shrink(3.0)));
|
||||
let field = crate::widgets::named_text_field(
|
||||
child.add(egui::TextEdit::multiline(&mut c).desired_width(r.width() - 6.0).font(regular(10.0))),
|
||||
&format!("Comments for {}", track.name),
|
||||
&crate::localized_format!("Comments for {}", track.name),
|
||||
);
|
||||
if field.changed() {
|
||||
let _ =
|
||||
@@ -552,8 +589,9 @@ fn io_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, r: Rect) {
|
||||
let row = |y: f32, h: f32| (r.height() >= y + h + 1.0).then_some(Rect::from_min_size(r.min + vec2(7.0, y), vec2(r.width() - 14.0, h)));
|
||||
if let Some(input) = row(4.0, 15.0).filter(|_| crate::mix_window::has_input_selector(track.kind)) {
|
||||
let input_name = crate::mix_window::input_name(app, track);
|
||||
let resp = header_selector(&ui, input, ui.scope_id().with(("in", id.0)), &input_name, t.text, true, &format!("Input for {}", track.name));
|
||||
crate::mix_window::route_popup(app, &resp.on_hover_text("Input"), id, true);
|
||||
let name = crate::localized_format!("Input for {}", track.name);
|
||||
let resp = header_selector(&ui, input, ui.scope_id().with(("in", id.0)), &input_name, t.text, true, &name);
|
||||
crate::mix_window::route_popup(app, &resp.on_hover_text(crate::localization::text("Input")), id, true);
|
||||
}
|
||||
if let Some(out) = row(21.0, 17.0) {
|
||||
let (sel, fader) = (out.with_max_x(out.max.x - 11.0), out.with_min_x(out.max.x - 11.0));
|
||||
@@ -565,16 +603,23 @@ fn io_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, r: Rect) {
|
||||
info
|
||||
});
|
||||
let fresp = ui.interact(fader, ui.scope_id().with(("out_fader", id.0)), Sense::click());
|
||||
let shown = app.ui.output_window == Some(id);
|
||||
fresp.widget_info(|| {
|
||||
egui::WidgetInfo::selected(egui::accesskit::Role::Button, ui.is_enabled(), shown, format!("Output window for {}", track.name))
|
||||
});
|
||||
raised_key(ui.painter(), out, t.slot_face, resp.hovered() || fresp.hovered());
|
||||
groove(ui.painter(), fader.min.x - 0.5, out.min.y + 1.0..=out.max.y - 1.0, t.slot_face[0]);
|
||||
ui.painter().with_clip_rect(sel.shrink(1.0)).text(sel.center(), Align2::CENTER_CENTER, &output_name, bold(10.0), t.text);
|
||||
let c = fader.center() + vec2(0.5, 0.0);
|
||||
ui.painter().vline(c.x, c.y - 5.0..=c.y + 5.0, Stroke::new(1.0, t.text));
|
||||
ui.painter().rect_filled(Rect::from_center_size(c + vec2(0.0, -1.5), vec2(5.0, 2.5)), 0.5, t.text);
|
||||
crate::mix_window::route_popup(app, &resp.on_hover_text("Output"), id, false);
|
||||
if fresp.on_hover_text("Show in the Mix window").clicked() {
|
||||
let _ = app.run("edit.select", json!({"tracks": [id.0]}));
|
||||
let _ = app.run("window.mix", json!({}));
|
||||
if shown {
|
||||
ui.painter().rect_stroke(fader.shrink(0.5), 1.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
|
||||
}
|
||||
crate::mix_window::route_popup(app, &resp.on_hover_text(crate::localization::text("Output")), id, false);
|
||||
// As in Pro Tools, the fader button opens the track's Output window, not the Mix window (#1392).
|
||||
if fresp.on_hover_text(crate::localization::text("Output window")).clicked() {
|
||||
crate::mix_window::toggle_output_window(app, id);
|
||||
}
|
||||
}
|
||||
if let Some(vr) = row(45.0, 30.0).map(|vr| vr.shrink2(vec2(1.0, 0.0))) {
|
||||
|
||||
@@ -120,6 +120,7 @@ struct LaneCtx<'a> {
|
||||
eff: Tool,
|
||||
fade_corner: Option<bool>,
|
||||
selector_press: bool,
|
||||
command_point: bool,
|
||||
}
|
||||
|
||||
/// The lane's response, with its clip context menu and the drops it accepts.
|
||||
@@ -160,10 +161,10 @@ fn lane_menu_and_drops(app: &mut SoundApp, ui: &mut Ui, track: &Track, lane: Rec
|
||||
}
|
||||
|
||||
/// Hit-test the press point against breakpoints, fade handles and clip bodies.
|
||||
fn hit_test<'a>(inp: &LaneInput<'a>) -> LaneHits<'a> {
|
||||
fn hit_test<'a>(inp: &LaneInput<'a>, command: bool) -> LaneHits<'a> {
|
||||
let (track, lane, tl, s, tool, origin, at_origin) = (inp.track, inp.lane, inp.tl, inp.s, inp.tool, inp.origin, inp.at_origin);
|
||||
let auto_view = &inp.auto_view;
|
||||
let point_hit = if matches!(tool, Tool::Smart | Tool::Grabber | Tool::Pencil) {
|
||||
let point_hit = if command || matches!(tool, Tool::Smart | Tool::Grabber | Tool::Pencil) {
|
||||
shown_automation(track).and_then(|param| breakpoint_at(s, tl, lane, track, ¶m, origin).map(|at| (param, at)))
|
||||
} else {
|
||||
None
|
||||
@@ -337,9 +338,13 @@ fn drag_clip_gain(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui:
|
||||
|
||||
/// Click handling for the lane: breakpoints, clip selection, spot dialogs, zoom and pencil points.
|
||||
fn lane_click(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::Response) {
|
||||
let (track, lane, s, auto_view) = (c.inp.track, c.inp.lane, c.inp.s, &c.inp.auto_view);
|
||||
let (track, lane, s) = (c.inp.track, c.inp.lane, c.inp.s);
|
||||
let (point_hit, curve_handle, hit) = (&c.hits.point_hit, c.hits.curve_handle, &c.hits.hit);
|
||||
let (mods, p, at, eff, selector_press) = (c.mods, c.p, c.at, c.eff, c.selector_press);
|
||||
let command_view = if c.command_point { shown_automation(track) } else { None };
|
||||
let auto_view = command_view.as_ref().or(c.inp.auto_view.as_ref());
|
||||
// Command-click inserts a point like the Pencil without changing the active tool or its drags.
|
||||
let eff = if c.command_point { Tool::Pencil } else { eff };
|
||||
if resp.clicked()
|
||||
&& let Some((param, at)) = &point_hit
|
||||
{
|
||||
@@ -376,7 +381,7 @@ fn lane_click(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::Res
|
||||
let _ = app.run(if mods.alt { "view.zoom_out" } else { "view.zoom_in" }, json!({}));
|
||||
}
|
||||
Tool::Pencil => {
|
||||
if let Some(param) = &auto_view {
|
||||
if let Some(param) = auto_view {
|
||||
let (lo, hi, _) = param.range();
|
||||
let (lo, hi) = if matches!(param, AutoParam::Volume | AutoParam::SendLevel(_)) {
|
||||
(-60.0, 12.0)
|
||||
@@ -429,7 +434,9 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l
|
||||
let at_origin = sample_at(&s, tl, origin.x).max(0);
|
||||
let auto_view = AutoParam::parse(&track.view);
|
||||
let inp = LaneInput { track, lane, tl, s: &s, tool, origin, at_origin, auto_view };
|
||||
let hits = hit_test(&inp);
|
||||
// Command changes a click's target, while a drag retains the active tool's normal hits.
|
||||
let command_click = mods.command && !resp.drag_started() && !resp.dragged();
|
||||
let hits = hit_test(&inp, command_click);
|
||||
let eff = effective_tool(&inp, &hits);
|
||||
if resp.hovered() {
|
||||
let icon = match eff {
|
||||
@@ -457,15 +464,31 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l
|
||||
if resp.hovered() && gain_icon_at(p).is_some() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
|
||||
}
|
||||
// Existing points and clip controls keep their normal hit priority over modifier insertion.
|
||||
let command_point = mods.command
|
||||
&& shown_automation(track).is_some()
|
||||
&& hits.point_hit.is_none()
|
||||
&& fade_corner.is_none()
|
||||
&& curve_handle.is_none()
|
||||
&& gain_icon_at(p).is_none();
|
||||
let selector_press = eff == Tool::Selector && fade_corner.is_none() && curve_handle.is_none() && gain_icon_at(origin).is_none();
|
||||
if selector_press && resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) {
|
||||
// A Command-click keeps the prior selection; real drags still start their normal selection gesture.
|
||||
if selector_press
|
||||
&& (!mods.command || shown_automation(track).is_none())
|
||||
&& resp.is_pointer_button_down_on()
|
||||
&& ui.input(|i| i.pointer.primary_pressed())
|
||||
{
|
||||
place_insertion(app, ui, &s, track.id, at, mods.shift);
|
||||
}
|
||||
let gain_drag = if resp.drag_started() { gain_icon_at(origin) } else { None };
|
||||
let cx = LaneCtx { inp, hits, mods, p, at, eff, fade_corner, selector_press };
|
||||
let cx = LaneCtx { inp, hits, mods, p, at, eff, fade_corner, selector_press, command_point };
|
||||
start_gesture(app, ui, &cx, &resp, gain_drag);
|
||||
drag_clip_gain(app, ui, &cx, &resp);
|
||||
lane_click(app, ui, &cx, &resp);
|
||||
if command_point && resp.hovered() && !resp.dragged() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
resp.on_hover_text("Click to add an automation point");
|
||||
}
|
||||
}
|
||||
|
||||
fn place_insertion(app: &mut SoundApp, ui: &Ui, s: &Session, track: TrackId, at: Samples, extend: bool) {
|
||||
@@ -513,7 +536,7 @@ pub(super) fn new_midi_clip(app: &mut SoundApp, s: &Session, track: TrackId, fro
|
||||
|
||||
fn clip_context_menu(app: &mut SoundApp, ui: &mut Ui, clip: Option<ClipId>) {
|
||||
let Some(c) = clip else {
|
||||
if ui.button("Paste").clicked() {
|
||||
if ui.button(crate::localization::text("Paste")).clicked() {
|
||||
let _ = app.run("edit.paste", json!({}));
|
||||
}
|
||||
return;
|
||||
@@ -535,11 +558,11 @@ fn clip_context_menu(app: &mut SoundApp, ui: &mut Ui, clip: Option<ClipId>) {
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Rename...").clicked() {
|
||||
if ui.button(crate::localization::text("Rename...")).clicked() {
|
||||
let name = app.engine.session().find_clip(c).map(|(_, x)| x.name.clone()).unwrap_or_default();
|
||||
app.dialogs.open_rename_clip(c, &name);
|
||||
}
|
||||
if ui.button("Delete").clicked() {
|
||||
if ui.button(crate::localization::text("Delete")).clicked() {
|
||||
let s = app.engine.session();
|
||||
let selected: Vec<u64> = s.edit.selected_clips.iter().map(|id| id.0).collect();
|
||||
let track: Vec<u64> = s.find_clip(c).map(|(t, _)| t.0).into_iter().collect();
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::drag::drag_plan;
|
||||
use super::input::midi_clip_span;
|
||||
use super::layout::x_of;
|
||||
use super::scroll::{FollowFrame, follow_update};
|
||||
use super::{Color32, Gesture, Rect, Samples, Shape, SoundApp, Stroke, StrokeKind, Tokens, TrackId, Ui, json, ops, pos2, rgb};
|
||||
use super::{Color32, Gesture, Rect, Samples, SoundApp, Stroke, StrokeKind, Tokens, TrackId, Ui, json, ops, pos2, rgb};
|
||||
|
||||
/// The playback cursor is red only while recording; plain playback draws it in its own neutral
|
||||
/// grey, apart from the insertion colour of the edit cursor that stands beside it.
|
||||
@@ -11,6 +11,7 @@ pub(super) fn playhead_colour(t: &Tokens, recording: bool) -> Color32 {
|
||||
}
|
||||
|
||||
/// Selection overlay, insertion point and playhead across rulers and tracks.
|
||||
/// The insertion point stays drawn while playing, beside the moving playhead.
|
||||
/// While playing, auto-scroll keeps the playhead in view for the follow
|
||||
/// modes (`page`/`continuous`/`center`) — but any outside view move (a manual
|
||||
/// pan, scrollbar, universe jump, or programmatic scroll) pauses it, so the
|
||||
@@ -34,16 +35,9 @@ pub(super) fn overlay(app: &mut SoundApp, ui: &mut Ui, tl: Rect, area: Rect) {
|
||||
}
|
||||
}
|
||||
let sel = s.edit.selection;
|
||||
// Timeline selection markers on the main ruler.
|
||||
if !sel.is_empty() {
|
||||
for x in [x_of(s, tl, sel.start), x_of(s, tl, sel.end)] {
|
||||
painter.add(Shape::convex_polygon(
|
||||
vec![pos2(x - 5.0, area.min.y + 2.0), pos2(x + 5.0, area.min.y + 2.0), pos2(x, area.min.y + 9.0)],
|
||||
t.accent,
|
||||
Stroke::NONE,
|
||||
));
|
||||
}
|
||||
} else if !app.is_playing() {
|
||||
// The insertion point blinks while playing too, standing still at its place
|
||||
// while the playhead (its own colour) moves on, like the incumbent.
|
||||
if sel.is_empty() {
|
||||
let x = x_of(s, tl, sel.start);
|
||||
let now = ui.input(|i| i.time);
|
||||
let (id, key) = (ui.scope_id().with("insertion_blink"), (sel.start, s.edit.selected_tracks.clone()));
|
||||
|
||||
@@ -85,6 +85,52 @@ fn nice_step(spp: f64, sr: f64, min_px: f64) -> i64 {
|
||||
(3600.0 * sr) as i64
|
||||
}
|
||||
|
||||
/// Selection markers are blue, or red while any track is record-armed.
|
||||
pub(super) fn selection_marker_colour(t: &Tokens, armed: bool) -> Color32 {
|
||||
if armed { t.rec } else { t.accent }
|
||||
}
|
||||
|
||||
/// How far a half of the selection arrow reaches out from its cut edge, in px.
|
||||
const ARROW_REACH: f32 = 10.0;
|
||||
|
||||
/// Corner points of one half of the selection arrow, tip first: the whole arrow points down at
|
||||
/// `x`, a shaft on top and a head below with its tip at the foot of the ruler row, and is cut in
|
||||
/// two along its vertical axis. `outward` picks the half: -1 for the left one (a start), +1 for the
|
||||
/// right one (an end). Each half is a bar 4 px wide next to the cut and a wing 6 px further out from
|
||||
/// mid-height, whose slope runs back to the tip. Mirroring `outward` is the only difference between
|
||||
/// the halves, so they always fit together.
|
||||
pub(super) fn arrow_half(x: f32, row: Rect, outward: f32) -> [egui::Pos2; 5] {
|
||||
let (top, bottom) = (row.min.y + 0.5, row.max.y - 0.5);
|
||||
let (mid, bar, wing) = ((top + bottom) / 2.0, x + outward * 4.0, x + outward * ARROW_REACH);
|
||||
[pos2(x, bottom), pos2(wing, mid), pos2(bar, mid), pos2(bar, top), pos2(x, top)]
|
||||
}
|
||||
|
||||
/// The markers for a selection from `x0` to `x1`: the left half of the arrow at the start, the right
|
||||
/// half at the end, each filled and outlined. An empty selection (`x0 == x1`) joins them into the
|
||||
/// whole arrow on the insertion point, filled and outlined as one so no seam shows.
|
||||
pub(super) fn selection_markers(x0: f32, x1: f32, row: Rect, fill: Color32, outline: Color32) -> Vec<Shape> {
|
||||
let (left, right) = (arrow_half(x0, row, -1.0), arrow_half(x1, row, 1.0));
|
||||
let stroke = Stroke::new(1.0, outline);
|
||||
// Each half is concave, so it is filled as the bar down to mid-height plus the wing's triangle.
|
||||
if x0 == x1 {
|
||||
vec![
|
||||
Shape::convex_polygon(vec![left[3], right[3], right[2], left[2]], fill, Stroke::NONE),
|
||||
Shape::convex_polygon(vec![left[1], right[1], left[0]], fill, Stroke::NONE),
|
||||
Shape::closed_line(vec![right[0], right[1], right[2], right[3], left[3], left[2], left[1]], stroke),
|
||||
]
|
||||
} else {
|
||||
let mut shapes = Vec::new();
|
||||
for half in [left, right] {
|
||||
let [tip, wing, mid, top, cut] = half;
|
||||
let seam = pos2(cut.x, mid.y);
|
||||
shapes.push(Shape::convex_polygon(vec![cut, top, mid, seam], fill, Stroke::NONE));
|
||||
shapes.push(Shape::convex_polygon(vec![wing, seam, tip], fill, Stroke::NONE));
|
||||
shapes.push(Shape::closed_line(half.to_vec(), stroke));
|
||||
}
|
||||
shapes
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw each enabled ruler and handle its clicks and double-clicks against the visible sample range.
|
||||
pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect, rulers: &[String]) {
|
||||
let t = Tokens::current();
|
||||
@@ -92,6 +138,9 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
|
||||
ui.painter().rect_filled(area, 0.0, t.ruler_bg);
|
||||
let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x));
|
||||
let sr = s.sample_rate;
|
||||
// The selection is marked in the main timebase ruler, or in the top one when that is hidden.
|
||||
let main = rulers.iter().position(|id| TimeFormat::from_id(id) == Some(s.edit.main_counter)).unwrap_or(0);
|
||||
let marker = selection_marker_colour(&t, s.tracks.iter().any(|track| track.mixer.record_arm));
|
||||
let mut y0 = area.min.y + 3.0;
|
||||
for (i, id) in rulers.iter().enumerate() {
|
||||
let h = ruler_height(id);
|
||||
@@ -99,7 +148,13 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
|
||||
let lab = Rect::from_min_max(pos2(area.min.x, y0), pos2(area.min.x + HEADER_W, y0 + h));
|
||||
y0 += h;
|
||||
let painter = ui.painter().with_clip_rect(row);
|
||||
ui.painter().text(pos2(lab.max.x - 12.0, lab.center().y), Align2::RIGHT_CENTER, ruler_label(id), bold(11.0), t.ruler_text);
|
||||
ui.painter().text(
|
||||
pos2(lab.max.x - 12.0, lab.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
crate::localization::text(ruler_label(id)),
|
||||
bold(11.0),
|
||||
t.ruler_text,
|
||||
);
|
||||
let fmt = TimeFormat::from_id(id);
|
||||
match id.as_str() {
|
||||
"tempo" => {
|
||||
@@ -151,7 +206,13 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
|
||||
"key" => {
|
||||
painter.rect_filled(row, 0.0, Color32::from_rgb(64, 52, 88));
|
||||
if s.key_signatures.is_empty() {
|
||||
painter.text(pos2(tl.min.x + 6.0, row.center().y), Align2::LEFT_CENTER, "C major", bold(11.0), Color32::from_rgb(220, 214, 236));
|
||||
painter.text(
|
||||
pos2(tl.min.x + 6.0, row.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
crate::localization::text("C major"),
|
||||
bold(11.0),
|
||||
Color32::from_rgb(220, 214, 236),
|
||||
);
|
||||
}
|
||||
for (at, k) in &s.key_signatures {
|
||||
let x = x_of(&s, tl, *at);
|
||||
@@ -241,6 +302,17 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
|
||||
}
|
||||
}
|
||||
}
|
||||
if i == main {
|
||||
let sel = s.edit.selection;
|
||||
let (x0, x1) = (x_of(&s, tl, sel.start), x_of(&s, tl, sel.end));
|
||||
// The start's left half reaches out to the left of the timeline when the start is at its
|
||||
// edge (a new session: insertion at 0, scroll 0), so the clip widens by that much, over
|
||||
// the empty strip next to the ruler row only (never into the track headers below). A start
|
||||
// scrolled out of view keeps the plain clip, so its half does not show in that strip.
|
||||
let reach = if x0 >= tl.min.x { ARROW_REACH } else { 0.0 };
|
||||
let markers = ui.painter().with_clip_rect(row.with_min_x(row.min.x - reach));
|
||||
markers.extend(selection_markers(x0, x1, row, marker, t.text_dark));
|
||||
}
|
||||
if id == "min_secs" || id == "bars_beats" || id == "timecode" || id == "samples" || id == "feet_frames" {
|
||||
// Main timebase marker (blue tick like a selected ruler).
|
||||
if Some(s.edit.main_counter) == fmt {
|
||||
@@ -374,7 +446,7 @@ pub(super) fn column_titles(ui: &Ui, rulers: Rect, cols: &[Column]) {
|
||||
ui.painter().vline(end - 0.5, row.y_range(), line);
|
||||
for &(_, _, title, w) in cols {
|
||||
ui.painter().vline(x + 0.5, row.y_range(), line);
|
||||
ui.painter().text(pos2(x + w / 2.0, row.center().y), Align2::CENTER_CENTER, title, bold(10.0), t.section_label);
|
||||
ui.painter().text(pos2(x + w / 2.0, row.center().y), Align2::CENTER_CENTER, crate::localization::text(title), bold(10.0), t.section_label);
|
||||
x += w;
|
||||
}
|
||||
}
|
||||
@@ -383,9 +455,9 @@ pub(super) fn column_titles(ui: &Ui, rulers: Rect, cols: &[Column]) {
|
||||
pub(super) fn views_button(app: &mut SoundApp, ui: &mut Ui, rulers: Rect) {
|
||||
let r = Rect::from_min_size(rulers.min + vec2(6.0, 5.0), vec2(50.0, 18.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r));
|
||||
let resp = crate::widgets::selector_box(&mut child, r.width(), r.height(), "Views", Tokens::current().text);
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, child.is_enabled(), "Views"));
|
||||
let resp = resp.on_hover_text("Columns beside the track headers: inserts, sends, I/O…");
|
||||
let resp = crate::widgets::selector_box(&mut child, r.width(), r.height(), crate::localization::text("Views"), Tokens::current().text);
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, child.is_enabled(), crate::localization::text("Views")));
|
||||
let resp = resp.on_hover_text(crate::localization::text("Columns beside the track headers: inserts, sends, I/O…"));
|
||||
egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
let shown = edit_columns(app.engine.session());
|
||||
for (id, label, _, _) in COLUMNS {
|
||||
@@ -394,10 +466,10 @@ pub(super) fn views_button(app: &mut SoundApp, ui: &mut Ui, rulers: Rect) {
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("All").clicked() {
|
||||
if ui.button(crate::localization::text("All")).clicked() {
|
||||
let _ = app.run("view.edit_all", json!({}));
|
||||
}
|
||||
if ui.button("Minimal").clicked() {
|
||||
if ui.button(crate::localization::text("Minimal")).clicked() {
|
||||
let _ = app.run("view.edit_minimal", json!({}));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1574,6 +1574,182 @@ fn alt_click_on_a_breakpoint_deletes_it() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifier clicks insert an undoable point with the existing tools; plain clicks leave the curve alone.
|
||||
#[test]
|
||||
fn command_click_adds_an_automation_point_without_changing_clips_and_undoes() {
|
||||
for tool in ["smart", "grabber", "selector"] {
|
||||
let (mut h, track, [a, b], clips) = breakpoints_over_a_clip(tool);
|
||||
let before = volume_points(&h, track);
|
||||
let s = h.state().engine.session_arc();
|
||||
let i = h.state().edit_layout.rows.iter().position(|(id, _)| *id == track.0).unwrap();
|
||||
let lane = lane_rect(s.track(track).unwrap(), row(&h, i), timeline(&h));
|
||||
let at = pos2((a.x + b.x) * 0.5, lane.center().y);
|
||||
let sample = sample_at(h.state().engine.session(), timeline(&h), at.x);
|
||||
|
||||
click(&mut h, at);
|
||||
assert_eq!(volume_points(&h, track), before, "{tool}: a plain click adds no point");
|
||||
h.run_steps(30);
|
||||
fade_shot(&mut h, &format!("automation-command-{tool}-before"));
|
||||
click_with(&mut h, at, egui::Modifiers::COMMAND);
|
||||
let points = volume_points(&h, track);
|
||||
assert_eq!(points.len(), before.len() + 1, "{tool}: {points:?}");
|
||||
let point = points.iter().find(|(at, _)| *at == sample).expect("a point at the clicked sample");
|
||||
assert!((point.1 + 24.0).abs() < 0.01, "{tool}: the lane midpoint is -24 dB, above the -40 dB curve: {}", point.1);
|
||||
assert_eq!(h.state().engine.session().track(track).unwrap().clips(), clips.as_slice(), "{tool}: clips stay");
|
||||
h.run_steps(2);
|
||||
fade_shot(&mut h, &format!("automation-command-{tool}-after"));
|
||||
|
||||
h.state_mut().engine.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(volume_points(&h, track), before, "{tool}: one undo removes only the new point");
|
||||
assert_eq!(h.state().engine.session().track(track).unwrap().clips(), clips.as_slice(), "{tool}: undo leaves clips alone");
|
||||
}
|
||||
}
|
||||
|
||||
/// A modifier click adds a point while retaining an existing clip and range selection, including after undo.
|
||||
#[test]
|
||||
fn command_click_preserves_an_existing_edit_selection() {
|
||||
for tool in ["smart", "selector"] {
|
||||
let (mut h, track, [a, b], clips) = breakpoints_over_a_clip(tool);
|
||||
let s = h.state().engine.session_arc();
|
||||
let i = h.state().edit_layout.rows.iter().position(|(id, _)| *id == track.0).unwrap();
|
||||
let lane = lane_rect(s.track(track).unwrap(), row(&h, i), timeline(&h));
|
||||
let at = pos2((a.x + b.x) * 0.5, lane.min.y + lane.height() * 0.35);
|
||||
h.state_mut().engine.execute("edit.select", &json!({"clips": [clips[0].id.0]})).unwrap();
|
||||
h.run_steps(2);
|
||||
let before = h.state().engine.session().edit.clone();
|
||||
let points_before = volume_points(&h, track);
|
||||
assert!(!before.selection.is_empty());
|
||||
assert!(!before.selected_clips.is_empty());
|
||||
fade_shot(&mut h, &format!("automation-command-selection-{tool}-before"));
|
||||
|
||||
click_with(&mut h, at, egui::Modifiers::COMMAND);
|
||||
assert_eq!(volume_points(&h, track).len(), points_before.len() + 1, "{tool}");
|
||||
let after = &h.state().engine.session().edit;
|
||||
assert_eq!(after.selection, before.selection, "{tool}: the range stays");
|
||||
assert_eq!(after.selected_clips, before.selected_clips, "{tool}: selected clips stay");
|
||||
assert_eq!(after.selected_tracks, before.selected_tracks, "{tool}: selected tracks stay");
|
||||
h.run_steps(2);
|
||||
fade_shot(&mut h, &format!("automation-command-selection-{tool}-after"));
|
||||
h.state_mut().engine.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(volume_points(&h, track), points_before, "{tool}: one undo removes the point");
|
||||
assert_eq!(h.state().engine.session().edit.selection, before.selection, "{tool}: undo retains the range");
|
||||
assert_eq!(h.state().engine.session().edit.selected_clips, before.selected_clips, "{tool}: undo retains selected clips");
|
||||
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
|
||||
drag(&mut h, at, at + vec2(50.0, 0.0));
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
let after_drag = &h.state().engine.session().edit;
|
||||
assert!(!after_drag.selection.is_empty(), "{tool}: a Command-drag still selects a range");
|
||||
assert_ne!(after_drag.selection, before.selection, "{tool}: drag selection changes once the gesture starts");
|
||||
assert_eq!(volume_points(&h, track), points_before, "{tool}: dragging adds no point");
|
||||
assert_eq!(h.state().engine.session().track(track).unwrap().clips(), clips.as_slice(), "{tool}: clips stay");
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks that always paint volume automation also accept modifier clicks when their stored view is not automation.
|
||||
#[test]
|
||||
fn command_click_adds_to_fallback_volume_views() {
|
||||
for kind in [TrackKind::Master, TrackKind::Aux, TrackKind::Vca] {
|
||||
let mut engine = soundcraft_engine::Engine::default();
|
||||
let track = engine.session_mut().add_track(kind, soundcraft_model::ChannelFormat::Stereo, None);
|
||||
engine.execute("track.view", &json!({"track": track.0, "view": "waveform"})).unwrap();
|
||||
engine.execute("edit.tool", &json!({"tool": "smart"})).unwrap();
|
||||
let mut h = harness_with(engine);
|
||||
let s = h.state().engine.session_arc();
|
||||
let lane = lane_rect(s.track(track).unwrap(), row(&h, 0), timeline(&h));
|
||||
let at = pos2(lane.min.x + 100.0, lane.center().y);
|
||||
let sample = sample_at(&s, timeline(&h), at.x);
|
||||
fade_shot(&mut h, &format!("automation-command-fallback-{kind:?}-before"));
|
||||
click_with(&mut h, at, egui::Modifiers::COMMAND);
|
||||
let points = volume_points(&h, track);
|
||||
assert_eq!(points.len(), 1, "{kind:?}: status {}", h.state().ui.status);
|
||||
assert_eq!(points[0].0, sample, "{kind:?}");
|
||||
assert!((points[0].1 + 24.0).abs() < 0.01, "{kind:?}: {}", points[0].1);
|
||||
h.run_steps(2);
|
||||
fade_shot(&mut h, &format!("automation-command-fallback-{kind:?}-after"));
|
||||
h.state_mut().engine.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(volume_points(&h, track).is_empty(), "{kind:?}: one undo removes the point");
|
||||
}
|
||||
}
|
||||
|
||||
/// Command-click keeps an existing visible breakpoint as the hit target with every active tool.
|
||||
#[test]
|
||||
fn command_click_near_an_existing_breakpoint_does_not_insert_another_point() {
|
||||
for tool in ["smart", "grabber", "pencil", "selector", "trim", "scrubber", "zoom"] {
|
||||
let (mut h, track, [_, point], clips) = breakpoints_over_a_clip(tool);
|
||||
h.state_mut().engine.execute("edit.select", &json!({"clips": [clips[0].id.0]})).unwrap();
|
||||
h.run_steps(2);
|
||||
let before = volume_points(&h, track);
|
||||
let edit = h.state().engine.session().edit.clone();
|
||||
assert!(!edit.selection.is_empty());
|
||||
assert!(!edit.selected_clips.is_empty());
|
||||
// Inside the six-point hit target, but a different sample from the stored point.
|
||||
let near = point + vec2(3.0, 0.0);
|
||||
let sample = sample_at(h.state().engine.session(), timeline(&h), near.x);
|
||||
assert_ne!(sample, before[1].0);
|
||||
click_with(&mut h, near, egui::Modifiers::COMMAND);
|
||||
assert_eq!(volume_points(&h, track), before, "{tool}: the existing point wins over insertion");
|
||||
let after = &h.state().engine.session().edit;
|
||||
assert_eq!(after.tool, edit.tool, "{tool}: active tool stays");
|
||||
assert_eq!(after.selection, edit.selection, "{tool}: range selection stays");
|
||||
assert_eq!(after.selected_clips, edit.selected_clips, "{tool}: clip selection stays");
|
||||
assert_eq!(after.selected_tracks, edit.selected_tracks, "{tool}: track selection stays");
|
||||
assert_eq!(h.state().engine.session().track(track).unwrap().clips(), clips.as_slice(), "{tool}: clips stay");
|
||||
|
||||
click_with(&mut h, near, egui::Modifiers::COMMAND | egui::Modifiers::ALT);
|
||||
assert_eq!(volume_points(&h, track), before[..1], "{tool}: Alt still deletes the existing point");
|
||||
h.state_mut().engine.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(volume_points(&h, track), before, "{tool}: deletion remains undoable");
|
||||
}
|
||||
}
|
||||
|
||||
/// Command advertises insertion over empty automation space, while a breakpoint keeps its grab cursor.
|
||||
#[test]
|
||||
fn command_hover_shows_insertion_only_away_from_existing_breakpoints() {
|
||||
let (mut h, track, [a, b], _) = breakpoints_over_a_clip("selector");
|
||||
let s = h.state().engine.session_arc();
|
||||
let i = h.state().edit_layout.rows.iter().position(|(id, _)| *id == track.0).unwrap();
|
||||
let lane = lane_rect(s.track(track).unwrap(), row(&h, i), timeline(&h));
|
||||
let at = pos2((a.x + b.x) * 0.5, lane.center().y);
|
||||
let points = volume_points(&h, track);
|
||||
|
||||
h.hover_at(at);
|
||||
h.step();
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "plain Selector hover stays unchanged");
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
|
||||
h.hover_at(at);
|
||||
h.step();
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Crosshair, "Command shows the insertion gesture");
|
||||
h.run_steps(40);
|
||||
fade_shot(&mut h, "automation-command-hover-insertion");
|
||||
h.hover_at(b + vec2(3.0, 0.0));
|
||||
h.step();
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the existing point stays the target");
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
h.hover_at(at);
|
||||
h.step();
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "releasing Command restores the active tool cursor");
|
||||
assert_eq!(volume_points(&h, track), points, "hover adds no points");
|
||||
}
|
||||
|
||||
/// The Command click shortcut does not turn a Selector drag beginning beside a point into a point move.
|
||||
#[test]
|
||||
fn command_drag_near_an_existing_breakpoint_retains_the_selector_gesture() {
|
||||
let (mut h, track, [_, point], clips) = breakpoints_over_a_clip("selector");
|
||||
let points = volume_points(&h, track);
|
||||
let before = h.state().engine.session().edit.clone();
|
||||
let near = point + vec2(3.0, 0.0);
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
|
||||
drag(&mut h, near, near + vec2(50.0, 0.0));
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
let after = &h.state().engine.session().edit;
|
||||
assert!(!after.selection.is_empty(), "a Command-drag still selects a range");
|
||||
assert_ne!(after.selection, before.selection, "the Selector gesture changes the range");
|
||||
assert_eq!(after.tool, before.tool, "the active tool stays selected");
|
||||
assert_eq!(volume_points(&h, track), points, "dragging the selection does not move or insert a point");
|
||||
assert_eq!(h.state().engine.session().track(track).unwrap().clips(), clips.as_slice(), "the clips stay");
|
||||
}
|
||||
|
||||
const ALONE: ClipCut = ClipCut { left: false, right: false };
|
||||
|
||||
#[test]
|
||||
@@ -1837,6 +2013,262 @@ fn an_overlapping_clip_covers_the_pill_of_the_clip_below() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_markers_are_blue_or_red_when_a_track_is_armed() {
|
||||
for t in [Tokens::DARK, Tokens::LIGHT] {
|
||||
let (blue, red) = (selection_marker_colour(&t, false), selection_marker_colour(&t, true));
|
||||
assert!(blue.b() > blue.r() && blue.b() > blue.g(), "{blue:?} is not blue");
|
||||
assert!(red.r() > red.g() && red.r() > red.b(), "{red:?} is not red");
|
||||
}
|
||||
}
|
||||
|
||||
type Piece = (Color32, Vec<egui::Pos2>);
|
||||
|
||||
/// The filled pieces of `shapes`, as (fill, points).
|
||||
fn fills(shapes: &[Shape]) -> Vec<Piece> {
|
||||
let filled = |s: &Shape| match s {
|
||||
Shape::Path(p) if p.fill != Color32::TRANSPARENT => Some((p.fill, p.points.clone())),
|
||||
_ => None,
|
||||
};
|
||||
shapes.iter().filter_map(filled).collect()
|
||||
}
|
||||
|
||||
/// The outlines of `shapes`: closed, unfilled paths, as (stroke colour, width, points).
|
||||
fn outlines(shapes: &[Shape]) -> Vec<(egui::epaint::ColorMode, f32, Vec<egui::Pos2>)> {
|
||||
let outline = |s: &Shape| match s {
|
||||
Shape::Path(p) if p.closed && p.fill == Color32::TRANSPARENT => Some((p.stroke.color.clone(), p.stroke.width, p.points.clone())),
|
||||
_ => None,
|
||||
};
|
||||
shapes.iter().filter_map(outline).collect()
|
||||
}
|
||||
|
||||
/// Leftmost and rightmost x, and topmost and bottommost y, of some pieces.
|
||||
fn extent(pieces: &[Piece]) -> (f32, f32, f32, f32) {
|
||||
let pts = || pieces.iter().flat_map(|(_, p)| p.iter());
|
||||
let fold = |f: fn(f32, f32) -> f32, init: f32, get: fn(&egui::Pos2) -> f32| pts().map(get).fold(init, f);
|
||||
(fold(f32::min, f32::MAX, |p| p.x), fold(f32::max, f32::MIN, |p| p.x), fold(f32::min, f32::MAX, |p| p.y), fold(f32::max, f32::MIN, |p| p.y))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_gets_the_left_half_of_the_arrow_at_its_start_and_the_right_half_at_its_end() {
|
||||
let row = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 17.0));
|
||||
let range = selection_markers(100.0, 200.0, row, Color32::BLUE, Color32::BLACK);
|
||||
let pieces = fills(&range);
|
||||
assert_eq!(pieces.len(), 4, "a bar and a wing for each end");
|
||||
// Left half: cut edge on the start, ten pixels of bar and wing out to its left, row-high.
|
||||
assert_eq!(extent(&pieces[..2]), (90.0, 100.0, 0.5, 16.5));
|
||||
// Right half: cut edge on the end, wing out to its right.
|
||||
assert_eq!(extent(&pieces[2..]), (200.0, 210.0, 0.5, 16.5));
|
||||
// The wing starts at mid-height and its slope ends at the foot of the cut edge: nothing below it.
|
||||
assert_eq!(pieces[1].1, vec![pos2(90.0, 8.5), pos2(100.0, 8.5), pos2(100.0, 16.5)]);
|
||||
// Each half is outlined on its own, thin and dark, cut edge included.
|
||||
let lines = outlines(&range);
|
||||
assert_eq!(lines.len(), 2);
|
||||
assert!(lines.iter().all(|(c, w, pts)| *c == egui::epaint::ColorMode::Solid(Color32::BLACK) && *w == 1.0 && pts.len() == 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_selection_joins_the_halves_into_the_whole_arrow() {
|
||||
let row = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 17.0));
|
||||
let point = selection_markers(150.0, 150.0, row, Color32::BLUE, Color32::BLACK);
|
||||
let pieces = fills(&point);
|
||||
assert_eq!(pieces.len(), 2, "a shaft and a head, with no seam");
|
||||
assert_eq!(extent(&pieces), (140.0, 160.0, 0.5, 16.5), "centred on 150");
|
||||
assert_eq!(pieces[0].1, vec![pos2(146.0, 0.5), pos2(154.0, 0.5), pos2(154.0, 8.5), pos2(146.0, 8.5)]);
|
||||
assert_eq!(pieces[1].1, vec![pos2(140.0, 8.5), pos2(160.0, 8.5), pos2(150.0, 16.5)], "tip on the position");
|
||||
// One outline, built only from the corners of the two halves, nothing along the cut axis.
|
||||
let lines = outlines(&point);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let (left, right) = (arrow_half(150.0, row, -1.0), arrow_half(150.0, row, 1.0));
|
||||
assert_eq!(lines[0].2.len(), 7);
|
||||
assert!(lines[0].2.iter().all(|p| left.contains(p) || right.contains(p)));
|
||||
assert!(lines[0].2.windows(2).all(|w| !(w[0].x == 150.0 && w[1].x == 150.0)));
|
||||
// The halves are mirror images across the cut axis, so they always fit together.
|
||||
for (l, r) in left.iter().zip(&right) {
|
||||
assert_eq!((300.0 - l.x, l.y), (r.x, r.y));
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything `draw_rulers` paints for a selection, with the clip rectangle of each shape. The
|
||||
/// timeline starts at x 100 and the view at sample `scroll`. Rulers are Bars|Beats (row y 3..20)
|
||||
/// over Min:Secs (row y 20..37); `main` picks which carries the markers.
|
||||
fn ruler_shapes(selection: Range, scroll: Samples, armed: bool, main: TimeFormat) -> Vec<egui::epaint::ClippedShape> {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let mut engine = soundcraft_engine::Engine::default();
|
||||
engine.execute("track.new", &json!({"count": 1})).unwrap();
|
||||
let session = engine.session_mut();
|
||||
session.edit.selection = selection;
|
||||
session.edit.zoom.scroll = scroll;
|
||||
session.edit.zoom.samples_per_px = 1_000.0;
|
||||
session.edit.main_counter = main;
|
||||
session.tracks[0].mixer.record_arm = armed;
|
||||
let mut app = SoundApp::new(engine, None, crate::Services::default());
|
||||
let tl = Rect::from_min_max(pos2(100.0, 100.0), pos2(900.0, 500.0));
|
||||
let rulers_rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(900.0, 100.0));
|
||||
let rulers = ["bars_beats".to_string(), "min_secs".to_string()];
|
||||
let ctx = egui::Context::default();
|
||||
crate::fonts::install(&ctx, true);
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| draw_rulers(&mut app, ui, rulers_rect, tl, &rulers));
|
||||
output.textures_delta.clear();
|
||||
output.shapes
|
||||
}
|
||||
|
||||
/// The marker pieces (accent or record fill) and the number of dark outlines `draw_rulers`
|
||||
/// paints for a selection, with the view at the start of the session.
|
||||
fn ruler_markers(selection: Range, armed: bool, main: TimeFormat) -> (Vec<Piece>, usize) {
|
||||
let t = Tokens::current();
|
||||
let shapes: Vec<Shape> = ruler_shapes(selection, 0, armed, main).into_iter().map(|s| s.shape).collect();
|
||||
let dark = outlines(&shapes).iter().filter(|(c, w, _)| *c == egui::epaint::ColorMode::Solid(t.text_dark) && *w == 1.0).count();
|
||||
(fills(&shapes).into_iter().filter(|(c, _)| *c == t.accent || *c == t.rec).collect(), dark)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rulers_mark_a_range_and_a_point_in_the_main_ruler_and_red_when_armed() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let t = Tokens::current();
|
||||
for armed in [false, true] {
|
||||
let colour = if armed { t.rec } else { t.accent };
|
||||
// 30_000..60_000 samples at 1_000 samples/px: x 130 and 160, in the Min:Secs row (y 20..37).
|
||||
let (range, dark) = ruler_markers(Range::new(30_000, 60_000), armed, TimeFormat::MinSecs);
|
||||
assert_eq!(range.len(), 4, "a bar and a wing for each end");
|
||||
assert!(range.iter().all(|(c, _)| *c == colour), "{range:?}");
|
||||
assert_eq!(extent(&range[..2]), (120.0, 130.0, 20.5, 36.5), "the start, cut edge on 130");
|
||||
assert_eq!(extent(&range[2..]), (160.0, 170.0, 20.5, 36.5), "the end, cut edge on 160");
|
||||
assert_eq!(dark, 2);
|
||||
// A point: the whole arrow centred on the insertion point, one outline.
|
||||
let (point, dark) = ruler_markers(Range::point(30_000), armed, TimeFormat::MinSecs);
|
||||
assert_eq!(extent(&point), (120.0, 140.0, 20.5, 36.5));
|
||||
assert!(point.iter().all(|(c, _)| *c == colour) && dark == 1);
|
||||
}
|
||||
// The markers follow the main counter: with Bars|Beats main they move to the first row (y 3..20).
|
||||
let (bars, _) = ruler_markers(Range::point(30_000), false, TimeFormat::BarsBeats);
|
||||
assert_eq!(extent(&bars), (120.0, 140.0, 3.5, 19.5));
|
||||
}
|
||||
|
||||
/// Clip rectangles of the marker pieces (accent fill) `draw_rulers` paints, with their extent.
|
||||
fn marker_clips(selection: Range, scroll: Samples) -> Vec<(Rect, Rect)> {
|
||||
let accent = Tokens::current().accent;
|
||||
ruler_shapes(selection, scroll, false, TimeFormat::MinSecs)
|
||||
.into_iter()
|
||||
.filter_map(|c| match c.shape {
|
||||
Shape::Path(p) if p.fill == accent => Some((c.clip_rect, Rect::from_points(&p.points))),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arrow_at_position_zero_is_not_cut_at_the_edge_of_the_timeline() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
// Insertion at 0 with scroll 0, as in a new session: x 100, the timeline's left edge, so the
|
||||
// left wing sits in the 10 px next to it (x 90..100). The Min:Secs row is y 20..37.
|
||||
for selection in [Range::point(0), Range::new(0, 30_000)] {
|
||||
let clips = marker_clips(selection, 0);
|
||||
assert!(clips.len() >= 2, "{clips:?}");
|
||||
let (clip, drawn) = clips.iter().fold((Rect::NOTHING, Rect::NOTHING), |(c, d), (clip, piece)| (c.union(*clip), d.union(*piece)));
|
||||
assert_eq!(drawn.min.x, 90.0, "the left wing starts 10 px before the edge");
|
||||
assert!(clip.contains_rect(drawn), "the clip {clip:?} cuts the arrow {drawn:?}");
|
||||
// ...and only the ruler row's strip is opened: the same band of rows, nothing wider.
|
||||
assert_eq!((clip.min.x, clip.min.y, clip.max.y), (90.0, 20.0, 37.0), "{clip:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_scrolled_out_of_view_does_not_bleed_into_the_strip_beside_the_timeline() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
// Scrolled 5 px: the insertion at 0 is at x 95, off the timeline (which starts at x 100).
|
||||
let clips = marker_clips(Range::point(0), 5_000);
|
||||
assert!(!clips.is_empty());
|
||||
assert!(clips.iter().all(|(clip, _)| clip.min.x == 100.0), "{clips:?}");
|
||||
}
|
||||
|
||||
/// x of every insertion-point stroke painted in the last frame.
|
||||
fn insertion_xs(h: &Harness<SoundApp>) -> Vec<f32> {
|
||||
lines(h, Tokens::current().insertion).iter().map(|l| l[0].x).collect()
|
||||
}
|
||||
|
||||
/// Every line segment of `colour` painted in the last frame.
|
||||
fn lines(h: &Harness<SoundApp>, colour: Color32) -> Vec<[Pos2; 2]> {
|
||||
let line = |shape: &Shape| match shape {
|
||||
Shape::LineSegment { points, stroke } if stroke.color == colour => Some(*points),
|
||||
_ => None,
|
||||
};
|
||||
h.output().shapes.iter().filter_map(|c| line(&c.shape)).collect()
|
||||
}
|
||||
|
||||
/// Centre x of the ruler arrow's head (a 20 px wide filled triangle in the marker colour) in the last frame.
|
||||
fn arrow_xs(h: &Harness<SoundApp>) -> Vec<f32> {
|
||||
let shapes: Vec<Shape> = h.output().shapes.iter().map(|c| c.shape.clone()).collect();
|
||||
let heads = fills(&shapes).into_iter().filter(|(c, pts)| *c == Tokens::current().accent && pts.len() == 3);
|
||||
heads.map(|piece| extent(&[piece])).filter(|(x0, x1, _, _)| (x1 - x0 - 20.0).abs() < 0.01).map(|(x0, x1, _, _)| (x0 + x1) / 2.0).collect()
|
||||
}
|
||||
|
||||
/// Steps until the blinking insertion point is on (at most one second and a half).
|
||||
fn step_to_insertion_on(h: &mut Harness<SoundApp>) {
|
||||
for _ in 0..90 {
|
||||
if !insertion_rows(h).is_empty() {
|
||||
return;
|
||||
}
|
||||
h.step();
|
||||
}
|
||||
}
|
||||
|
||||
/// An insertion point on row 2, then playback from it with the view held still.
|
||||
fn playing_from_an_insertion_point() -> (Harness<'static, SoundApp>, Samples) {
|
||||
let mut h = harness(4);
|
||||
h.state_mut().run("options.scrolling", json!({"mode": "none"})).unwrap();
|
||||
let a = lane_point(&h, 2);
|
||||
click(&mut h, a);
|
||||
let at = h.state().engine.session().edit.selection.start;
|
||||
h.state_mut().run("transport.play", json!({})).unwrap();
|
||||
h.run_steps(5);
|
||||
assert!(h.state().is_playing());
|
||||
(h, at)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_insertion_point_stays_drawn_while_playing_beside_the_playhead() {
|
||||
let (mut h, at) = playing_from_an_insertion_point();
|
||||
step_to_insertion_on(&mut h);
|
||||
assert!(h.state().is_playing());
|
||||
assert!(h.state().position() > at, "the playhead did not move on");
|
||||
let (s, tl) = (h.state().engine.session(), timeline(&h));
|
||||
assert_eq!(insertion_rows(&h), [2], "only on the selected track");
|
||||
let x = x_of(s, tl, at);
|
||||
assert!(matches!(insertion_xs(&h)[..], [i] if (i - x).abs() < 0.01), "{:?} is not on {x}", insertion_xs(&h));
|
||||
// The playback line has its own colour and is already further along.
|
||||
assert_ne!(Tokens::current().insertion, Tokens::current().playback);
|
||||
// (The overview paints a small playhead of its own: keep the line that crosses all four tracks.)
|
||||
let span = row(&h, 3).max.y - row(&h, 0).min.y;
|
||||
let playhead: Vec<f32> = lines(&h, Tokens::current().playback).iter().filter(|l| l[1].y - l[0].y >= span).map(|l| l[0].x).collect();
|
||||
assert!(matches!(playhead[..], [p] if p > x), "{playhead:?} is not past the insertion point {x}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_in_a_track_while_playing_moves_the_insertion_point_and_the_arrow_not_the_playback() {
|
||||
let (mut h, at) = playing_from_an_insertion_point();
|
||||
let (s, tl) = (h.state().engine.session(), timeline(&h));
|
||||
assert!(matches!(arrow_xs(&h)[..], [a] if (a - x_of(s, tl, at)).abs() < 0.01), "{:?} is not on the insertion point", arrow_xs(&h));
|
||||
let before = h.state().position();
|
||||
let b = lane_point(&h, 0) + vec2(300.0, 0.0);
|
||||
click(&mut h, b);
|
||||
let s = h.state().engine.session();
|
||||
let want = sample_at(s, timeline(&h), b.x);
|
||||
assert_eq!(s.edit.selection, Range::point(want));
|
||||
assert_eq!(s.edit.selected_tracks, row_ids(&h)[..1]);
|
||||
let x = x_of(s, timeline(&h), want);
|
||||
assert!(matches!(arrow_xs(&h)[..], [a] if (a - x).abs() < 0.01), "{:?} is not on {x}", arrow_xs(&h));
|
||||
// Playback went on from where it was: it neither stopped nor jumped to the click. The harness steps
|
||||
// 1/60 s per frame (800 samples at 48 kHz) and the click takes five of them (measured: 4 000 samples),
|
||||
// so allow seven. The old bound, one second, let a seek up to 60 frames ahead pass.
|
||||
let pos = h.state().position();
|
||||
assert!(h.state().is_playing());
|
||||
assert!(pos >= before && pos < before + 7 * 800 && pos < want, "playback went from {before} to {pos}, the click is at {want}");
|
||||
step_to_insertion_on(&mut h);
|
||||
assert!(matches!(insertion_xs(&h)[..], [i] if (i - x).abs() < 0.01), "{:?} is not on {x}", insertion_xs(&h));
|
||||
assert_eq!(insertion_rows(&h), [0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playhead_is_red_only_while_recording() {
|
||||
for t in [Tokens::DARK, Tokens::LIGHT] {
|
||||
|
||||
@@ -163,7 +163,7 @@ fn playlist_lanes(app: &mut SoundApp, ui: &mut Ui, track: &Track, row: Rect, mai
|
||||
let _ = app.run("track.playlist_promote", json!({"track": track.id.0, "playlist": i, "start": a, "end": b}));
|
||||
}
|
||||
}
|
||||
resp.on_hover_text("Click a take (or the selection) to promote it to the main playlist");
|
||||
resp.on_hover_text(crate::localization::text("Click a take (or the selection) to promote it to the main playlist"));
|
||||
y += LANE_H;
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,7 @@ pub(super) fn view_menu(app: &mut SoundApp, ui: &mut Ui, track: &Track) {
|
||||
}
|
||||
opts.extend(["volume", "pan", "mute"]);
|
||||
for o in opts {
|
||||
if ui.selectable_label(track.view == o, view_label(o)).clicked() {
|
||||
if ui.selectable_label(track.view == o, crate::localization::text(&view_label(o))).clicked() {
|
||||
let _ = app.run("track.view", json!({"track": id, "view": o}));
|
||||
}
|
||||
}
|
||||
@@ -240,7 +240,7 @@ pub(crate) fn track_context_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
.map(|track| (track.id.0, track.name.clone()))
|
||||
.collect();
|
||||
if !folders.is_empty() {
|
||||
ui.menu_button("Move to Folder", |ui| {
|
||||
ui.menu_button(crate::localization::text("Move to Folder"), |ui| {
|
||||
for (folder, name) in &folders {
|
||||
if ui.button(name).clicked() {
|
||||
let _ = app.run("track.move_to_folder", json!({"tracks": selection, "folder": folder}));
|
||||
@@ -248,24 +248,26 @@ pub(crate) fn track_context_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
}
|
||||
});
|
||||
}
|
||||
if app.engine.session().track(id).is_some_and(|track| track.folder.is_some()) && ui.button("Remove from Folder").clicked() {
|
||||
if app.engine.session().track(id).is_some_and(|track| track.folder.is_some())
|
||||
&& ui.button(crate::localization::text("Remove from Folder")).clicked()
|
||||
{
|
||||
let _ = app.run("track.remove_from_folder", json!({"tracks": selection}));
|
||||
}
|
||||
// Only the track clicked: the command has one target, and the selection stays as it is.
|
||||
if ui.button("Scroll Into View").clicked() {
|
||||
if ui.button(crate::localization::text("Scroll Into View")).clicked() {
|
||||
let _ = app.run("view.scroll_into_view", json!({"track": id.0}));
|
||||
}
|
||||
ui.separator();
|
||||
ui.menu_button("Track Height", |ui| {
|
||||
ui.menu_button(crate::localization::text("Track Height"), |ui| {
|
||||
for h in TrackHeight::ALL {
|
||||
if ui.button(h.label()).clicked() {
|
||||
if ui.button(crate::localization::text(h.label())).clicked() {
|
||||
let own: Vec<TrackId> = selection.iter().map(|&t| TrackId(t)).collect();
|
||||
let tracks = height_targets(app.engine.session(), ui.input(|i| i.modifiers), &own);
|
||||
let _ = app.run("track.height", json!({"tracks": tracks, "height": h.label()}));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.menu_button("Track Color", |ui| {
|
||||
ui.menu_button(crate::localization::text("Track Color"), |ui| {
|
||||
for (i, c) in soundcraft_model::TRACK_COLORS.iter().enumerate() {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(120.0, 14.0), Sense::click());
|
||||
ui.painter().rect_filled(r, 2.0, rgb(*c));
|
||||
|
||||
@@ -137,7 +137,7 @@ fn finish(app: &mut SoundApp) {
|
||||
Ok(decoded) => {
|
||||
app.engine.offer_import(decoded);
|
||||
if run_now(app, params) {
|
||||
app.ui.status = format!("Imported {name}");
|
||||
app.ui.status = crate::localized_format!("Imported {name}", name = name);
|
||||
}
|
||||
app.engine.drop_offered_imports();
|
||||
}
|
||||
@@ -166,7 +166,7 @@ pub fn show(app: &SoundApp, ctx: &egui::Context) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Spinner::new());
|
||||
let more = if waiting > 0 { format!(" ({waiting} more)") } else { String::new() };
|
||||
ui.label(format!("Importing {name}{more}"));
|
||||
ui.label(crate::localized_format!("Importing {name}{more}", name = name, more = more));
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod edit_window;
|
||||
pub mod fonts;
|
||||
pub mod icons;
|
||||
pub mod import;
|
||||
pub mod localization;
|
||||
pub mod menus;
|
||||
pub mod mix_window;
|
||||
pub mod palette;
|
||||
@@ -102,6 +103,9 @@ pub struct UiState {
|
||||
/// The send in the Send window (track, slot).
|
||||
#[serde(skip)]
|
||||
pub send_window: Option<(TrackId, usize)>,
|
||||
/// The track in the Output window.
|
||||
#[serde(skip)]
|
||||
pub output_window: Option<TrackId>,
|
||||
pub audiosuite: Option<String>,
|
||||
pub status: String,
|
||||
pub show_automation: bool,
|
||||
@@ -143,6 +147,8 @@ pub struct UiState {
|
||||
pub video_burn_in: bool,
|
||||
pub workspace_dir: String,
|
||||
pub configurations: Vec<(String, Value)>,
|
||||
/// Interface language (`ui.language`).
|
||||
pub language: localization::Language,
|
||||
/// Appearance (`ui.theme`): dark by default, light or follow the system on request.
|
||||
pub theme: theme::ThemeMode,
|
||||
/// The main window's size (logical points) and maximized state, and the interface scale, as
|
||||
@@ -177,6 +183,7 @@ impl Default for UiState {
|
||||
track_tint: 0.5,
|
||||
plugin_windows: Vec::new(),
|
||||
send_window: None,
|
||||
output_window: None,
|
||||
audiosuite: None,
|
||||
status: String::new(),
|
||||
show_automation: false,
|
||||
@@ -212,6 +219,7 @@ impl Default for UiState {
|
||||
video_burn_in: false,
|
||||
workspace_dir: String::new(),
|
||||
configurations: Vec::new(),
|
||||
language: localization::Language::default(),
|
||||
theme: theme::ThemeMode::Dark,
|
||||
window_size: [1600.0, 1000.0],
|
||||
window_maximized: false,
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
//! Language selection and source-language fallback for UI strings.
|
||||
|
||||
#[path = "../locales/pt-BR/mod.rs"]
|
||||
mod pt_br;
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static CURRENT_LANGUAGE: Cell<Language> = const { Cell::new(Language::English) };
|
||||
}
|
||||
|
||||
/// A language supported by the UI.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Language {
|
||||
#[default]
|
||||
#[serde(rename = "en")]
|
||||
English,
|
||||
#[serde(rename = "pt-BR")]
|
||||
PortugueseBrazil,
|
||||
}
|
||||
|
||||
impl Language {
|
||||
/// All supported languages, in the order they are shown in the language menu.
|
||||
pub const ALL: [Self; 2] = [Self::English, Self::PortugueseBrazil];
|
||||
|
||||
/// Stable language tag used in preferences and control commands.
|
||||
pub const fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::English => "en",
|
||||
Self::PortugueseBrazil => "pt-BR",
|
||||
}
|
||||
}
|
||||
|
||||
/// English source name of the language; translate it with `text` for display.
|
||||
pub const fn native_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::English => "English",
|
||||
Self::PortugueseBrazil => "Portuguese (Brazil)",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(tag: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|language| language.id().eq_ignore_ascii_case(tag.trim()))
|
||||
}
|
||||
|
||||
/// Rewrites the decimal point of a rendered number for this language.
|
||||
pub fn localize_decimal(self, number: &str) -> String {
|
||||
match self {
|
||||
Self::English => number.to_owned(),
|
||||
Self::PortugueseBrazil => number.replace('.', ","),
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a UI string, falling back to its English source when no translation exists.
|
||||
pub fn text(self, source: &str) -> &str {
|
||||
match self {
|
||||
Self::English => source,
|
||||
Self::PortugueseBrazil => pt_br::translate(source).unwrap_or(source),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the language used by text widgets on this thread for the duration of a UI frame.
|
||||
pub fn enter(language: Language) -> LanguageScope {
|
||||
let previous = CURRENT_LANGUAGE.with(|current| current.replace(language));
|
||||
LanguageScope(previous)
|
||||
}
|
||||
|
||||
/// The language selected for the current UI frame.
|
||||
pub fn current_language() -> Language {
|
||||
CURRENT_LANGUAGE.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Translates a source string using the language selected for the current UI frame.
|
||||
pub fn text(source: &str) -> &str {
|
||||
current_language().text(source)
|
||||
}
|
||||
|
||||
/// Translates an engine error message for display. Messages are matched against the catalog's
|
||||
/// error templates and their embedded values are carried over; text that matches no template is
|
||||
/// returned unchanged, so low-level library errors stay in English.
|
||||
pub fn error_text(message: &str) -> String {
|
||||
error_text_in(current_language(), message, 0)
|
||||
}
|
||||
|
||||
const MAX_ERROR_DEPTH: usize = 4;
|
||||
|
||||
fn error_text_in(language: Language, message: &str, depth: usize) -> String {
|
||||
let templates: &[(&str, &str)] = match language {
|
||||
Language::English => &[],
|
||||
Language::PortugueseBrazil => pt_br::ERROR_TEMPLATES,
|
||||
};
|
||||
let mut best: Option<(usize, &str, Vec<(String, String)>)> = None;
|
||||
for (template, translation) in templates {
|
||||
if let Some((weight, captures)) = match_template(template, message)
|
||||
&& best.as_ref().is_none_or(|(w, ..)| weight > *w)
|
||||
{
|
||||
best = Some((weight, translation, captures));
|
||||
}
|
||||
}
|
||||
let Some((_, translation, captures)) = best else { return message.to_owned() };
|
||||
let captures: Vec<(String, String)> = captures
|
||||
.into_iter()
|
||||
.map(|(name, value)| {
|
||||
let value = if depth < MAX_ERROR_DEPTH { error_text_in(language, &value, depth + 1) } else { value };
|
||||
(name, value)
|
||||
})
|
||||
.collect();
|
||||
fill_captures(language, translation, &captures)
|
||||
}
|
||||
|
||||
enum Piece<'a> {
|
||||
Literal(String),
|
||||
Field(&'a str),
|
||||
}
|
||||
|
||||
fn split_template(template: &str) -> Vec<Piece<'_>> {
|
||||
let mut pieces = Vec::new();
|
||||
let mut literal = String::new();
|
||||
let mut rest = template;
|
||||
while let Some(ch) = rest.chars().next() {
|
||||
if let Some(after) = rest.strip_prefix("{{") {
|
||||
literal.push('{');
|
||||
rest = after;
|
||||
} else if let Some(after) = rest.strip_prefix("}}") {
|
||||
literal.push('}');
|
||||
rest = after;
|
||||
} else if ch == '{'
|
||||
&& let Some(end) = rest.find('}')
|
||||
{
|
||||
if !literal.is_empty() {
|
||||
pieces.push(Piece::Literal(std::mem::take(&mut literal)));
|
||||
}
|
||||
pieces.push(Piece::Field(rest.get(1..end).unwrap_or_default()));
|
||||
rest = rest.get(end + 1..).unwrap_or_default();
|
||||
} else {
|
||||
literal.push(ch);
|
||||
rest = rest.get(ch.len_utf8()..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
if !literal.is_empty() {
|
||||
pieces.push(Piece::Literal(literal));
|
||||
}
|
||||
pieces
|
||||
}
|
||||
|
||||
/// Matches `message` against `template`. Returns the template's literal length, used to prefer
|
||||
/// the most specific template, and the captured values by placeholder name.
|
||||
fn match_template(template: &str, message: &str) -> Option<(usize, Vec<(String, String)>)> {
|
||||
let pieces = split_template(template);
|
||||
let mut captures = Vec::new();
|
||||
let mut pos = 0usize;
|
||||
let mut weight = 0usize;
|
||||
let mut index = 0usize;
|
||||
while let Some(piece) = pieces.get(index) {
|
||||
match piece {
|
||||
Piece::Literal(text) => {
|
||||
if !message.get(pos..)?.starts_with(text.as_str()) {
|
||||
return None;
|
||||
}
|
||||
pos += text.len();
|
||||
weight += text.len();
|
||||
}
|
||||
Piece::Field(name) => {
|
||||
let rest = message.get(pos..)?;
|
||||
let end = match pieces.get(index + 1) {
|
||||
None => rest.len(),
|
||||
Some(Piece::Literal(next)) if pieces.len() == index + 2 => {
|
||||
if rest.len() < next.len() || !rest.ends_with(next.as_str()) {
|
||||
return None;
|
||||
}
|
||||
rest.len() - next.len()
|
||||
}
|
||||
Some(Piece::Literal(next)) => rest.find(next.as_str())?,
|
||||
Some(Piece::Field(_)) => return None,
|
||||
};
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
let name = name.split(':').next().unwrap_or_default();
|
||||
captures.push((name.to_owned(), rest.get(..end)?.to_owned()));
|
||||
pos += end;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
(pos == message.len() && weight > 0).then_some((weight, captures))
|
||||
}
|
||||
|
||||
fn fill_captures(language: Language, translation: &str, captures: &[(String, String)]) -> String {
|
||||
let mut out = String::with_capacity(translation.len());
|
||||
for piece in split_template(translation) {
|
||||
match piece {
|
||||
Piece::Literal(text) => out.push_str(&text),
|
||||
Piece::Field(field) => {
|
||||
let name = field.split(':').next().unwrap_or_default();
|
||||
match captures.iter().find(|(captured, _)| captured == name) {
|
||||
Some((_, value)) if value.parse::<f64>().is_ok() => out.push_str(&language.localize_decimal(value)),
|
||||
Some((_, value)) => out.push_str(value),
|
||||
None => {
|
||||
out.push('{');
|
||||
out.push_str(field);
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the Brazilian Portuguese catalog has an entry for `source`, even an identical one.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn has_pt_br_entry(source: &str) -> bool {
|
||||
pt_br::translate(source).is_some()
|
||||
}
|
||||
|
||||
/// Guard that restores the previously active language when dropped.
|
||||
pub struct LanguageScope(Language);
|
||||
|
||||
impl Drop for LanguageScope {
|
||||
/// Restores the language that was active when the scope was created.
|
||||
fn drop(&mut self) {
|
||||
CURRENT_LANGUAGE.with(|language| language.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// One formatting argument, kept as a reference and rendered only when the template asks for it.
|
||||
///
|
||||
/// The template is only known at run time, so the format specifier is too: the formatter reads a
|
||||
/// `:.N` precision from it and renders the value with that precision.
|
||||
pub struct Arg<'a> {
|
||||
value: &'a dyn std::fmt::Display,
|
||||
}
|
||||
|
||||
impl<'a> Arg<'a> {
|
||||
/// Wraps the argument without rendering it.
|
||||
pub fn new<T: std::fmt::Display>(value: &'a T) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
|
||||
/// Renders the argument for the given precision specifier (`.0` to `.3`), if any. A number
|
||||
/// given a precision uses the active language's decimal separator.
|
||||
fn render(&self, spec: Option<&str>) -> String {
|
||||
let precision = spec.and_then(|spec| spec.strip_prefix('.')).and_then(|digits| digits.parse::<usize>().ok()).filter(|n| *n <= 3);
|
||||
match precision {
|
||||
Some(n) => {
|
||||
let text = format!("{:.*}", n, self.value);
|
||||
if text.parse::<f64>().is_ok() { current_language().localize_decimal(&text) } else { text }
|
||||
}
|
||||
None => self.value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats the translated `source` with positional arguments. Placeholders may carry a `:.N`
|
||||
/// precision, as in `format!`; other specifiers are ignored.
|
||||
pub fn format_positional(source: &str, args: &[Arg<'_>]) -> String {
|
||||
format_template(source, args, &[], true)
|
||||
}
|
||||
|
||||
/// Formats the translated `source` with named arguments (`name = value`).
|
||||
pub fn format_named(source: &str, args: &[(&str, Arg<'_>)]) -> String {
|
||||
format_template(source, &[], args, false)
|
||||
}
|
||||
|
||||
/// Shared implementation behind `format_positional` and `format_named`.
|
||||
fn format_template(source: &str, positional: &[Arg<'_>], named: &[(&str, Arg<'_>)], positional_mode: bool) -> String {
|
||||
let template = text(source);
|
||||
let mut out = String::with_capacity(template.len());
|
||||
let mut next = 0usize;
|
||||
let mut chars = template.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
match ch {
|
||||
'{' if chars.peek() == Some(&'{') => {
|
||||
chars.next();
|
||||
out.push('{');
|
||||
}
|
||||
'}' if chars.peek() == Some(&'}') => {
|
||||
chars.next();
|
||||
out.push('}');
|
||||
}
|
||||
'{' => {
|
||||
let mut field = String::new();
|
||||
let mut closed = false;
|
||||
for ch in chars.by_ref() {
|
||||
if ch == '}' {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
field.push(ch);
|
||||
}
|
||||
if !closed {
|
||||
out.push('{');
|
||||
out.push_str(&field);
|
||||
break;
|
||||
}
|
||||
let (key, spec) = match field.split_once(':') {
|
||||
Some((key, spec)) => (key, Some(spec)),
|
||||
None => (field.as_str(), None),
|
||||
};
|
||||
let value = if positional_mode {
|
||||
let value = positional.get(next);
|
||||
next += 1;
|
||||
value
|
||||
} else {
|
||||
named.iter().find(|(name, _)| *name == key).map(|(_, value)| value)
|
||||
};
|
||||
match value {
|
||||
Some(value) => out.push_str(&value.render(spec)),
|
||||
None => {
|
||||
out.push('{');
|
||||
out.push_str(&field);
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
'}' => out.push('}'),
|
||||
ch => out.push(ch),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! localized_format {
|
||||
($source:literal) => {
|
||||
$crate::localization::text($source).to_owned()
|
||||
};
|
||||
($source:literal, $($name:ident = $value:expr),+ $(,)?) => {{
|
||||
$crate::localization::format_named(
|
||||
$source,
|
||||
&[$( (stringify!($name), $crate::localization::Arg::new(&$value)) ),+],
|
||||
)
|
||||
}};
|
||||
($source:literal, $($value:expr),+ $(,)?) => {{
|
||||
$crate::localization::format_positional(
|
||||
$source,
|
||||
&[$($crate::localization::Arg::new(&$value)),+],
|
||||
)
|
||||
}};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Arg, Language, enter, error_text, format_named, format_positional, text};
|
||||
|
||||
#[test]
|
||||
fn language_tags_are_stable_and_round_trip() {
|
||||
for language in Language::ALL {
|
||||
assert_eq!(Language::parse(language.id()), Some(language));
|
||||
let encoded = serde_json::to_value(language).unwrap_or_default();
|
||||
let decoded: Language = serde_json::from_value(encoded).unwrap_or_default();
|
||||
assert_eq!(decoded, language);
|
||||
}
|
||||
assert_eq!(Language::parse(" PT-br "), Some(Language::PortugueseBrazil));
|
||||
assert_eq!(Language::parse("fr"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_translations_fall_back_to_the_english_source() {
|
||||
assert_ne!(Language::PortugueseBrazil.text("Appearance"), "Appearance");
|
||||
assert_eq!(Language::PortugueseBrazil.text("A source string with no catalog entry"), "A source string with no catalog entry");
|
||||
assert_eq!(Language::English.text("Appearance"), "Appearance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_restores_the_previous_language() {
|
||||
assert_eq!(text("Appearance"), "Appearance");
|
||||
{
|
||||
let _scope = enter(Language::PortugueseBrazil);
|
||||
assert_ne!(text("Appearance"), "Appearance");
|
||||
{
|
||||
let _inner = enter(Language::English);
|
||||
assert_eq!(text("Appearance"), "Appearance");
|
||||
}
|
||||
assert_ne!(text("Appearance"), "Appearance");
|
||||
}
|
||||
assert_eq!(text("Appearance"), "Appearance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portuguese_catalog_covers_every_menu_label() {
|
||||
for path in include_str!("../../engine/catalog/menus.txt").lines() {
|
||||
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
|
||||
assert!(super::pt_br::translate(label).is_some(), "missing pt-BR menu label: {label}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_errors_are_translated_with_their_values() {
|
||||
assert_eq!(error_text("select a clip"), "select a clip");
|
||||
let _scope = enter(Language::PortugueseBrazil);
|
||||
assert_ne!(error_text("select a clip"), "select a clip");
|
||||
assert_ne!(error_text("no track"), "no track");
|
||||
let wrapped = error_text("bad parameters for `track.new`: `name` required");
|
||||
assert!(wrapped.contains("`track.new`") && wrapped.contains("`name`"), "{wrapped}");
|
||||
assert!(!wrapped.contains("bad parameters") && !wrapped.contains("required"), "{wrapped}");
|
||||
let ratio = error_text("stretch ratio 12.500 is outside 0.1..10");
|
||||
assert!(ratio.contains("12,500"), "{ratio}");
|
||||
assert_eq!(error_text("some unknown library failure"), "some unknown library failure");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positional_templates_fill_in_order() {
|
||||
assert_eq!(format_positional("{} of {}", &[Arg::new(&1), Arg::new(&"two")]), "1 of two");
|
||||
assert_eq!(format_positional("no fields", &[Arg::new(&1)]), "no fields");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_templates_fill_by_name_in_any_order() {
|
||||
assert_eq!(format_named("{b}-{a}-{b}", &[("a", Arg::new(&1)), ("b", Arg::new(&2))]), "2-1-2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precision_specifiers_are_honoured() {
|
||||
let value = 3.14259_f64;
|
||||
for (template, expected) in [("{:.0}", "3"), ("{:.1}", "3.1"), ("{:.2}", "3.14"), ("{:.3}", "3.143"), ("{}", "3.14259")] {
|
||||
assert_eq!(format_positional(template, &[Arg::new(&value)]), expected, "{template}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn braces_can_be_escaped() {
|
||||
assert_eq!(format_positional("{{{}}}", &[Arg::new(&5)]), "{5}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_unknown_and_unclosed_fields_are_kept_verbatim() {
|
||||
assert_eq!(format_positional("{} {}", &[Arg::new(&1)]), "1 {}");
|
||||
assert_eq!(format_named("{nope}", &[("a", Arg::new(&1))]), "{nope}");
|
||||
assert_eq!(format_positional("open {", &[]), "open {");
|
||||
assert_eq!(format_positional("tail {abc", &[]), "tail {abc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portuguese_numbers_use_a_decimal_comma_only_with_a_precision() {
|
||||
let _scope = enter(Language::PortugueseBrazil);
|
||||
assert_eq!(format_positional("{:.1} dB", &[Arg::new(&-6.04_f64)]), "-6,0 dB");
|
||||
assert_eq!(format_positional("{}", &[Arg::new(&"v1.2")]), "v1.2");
|
||||
let _english = enter(Language::English);
|
||||
assert_eq!(format_positional("{:.1}", &[Arg::new(&2.5_f64)]), "2.5");
|
||||
}
|
||||
|
||||
/// Parses a Rust string literal at the start of `s`; returns its value and the rest.
|
||||
fn literal(s: &str) -> Option<(String, &str)> {
|
||||
let mut chars = s.strip_prefix('"')?.char_indices();
|
||||
let mut out = String::new();
|
||||
while let Some((i, c)) = chars.next() {
|
||||
match c {
|
||||
'"' => return Some((out, &s[i + 2..])),
|
||||
'\\' => match chars.next()?.1 {
|
||||
'n' => out.push('\n'),
|
||||
other => out.push(other),
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Every `"source" => "translation"` pair of the catalog, read from its source file.
|
||||
fn catalog_entries() -> Vec<(String, String)> {
|
||||
let text = include_str!("../locales/pt-BR/mod.rs");
|
||||
let mut lines = text.lines().map(str::trim);
|
||||
let mut entries = Vec::new();
|
||||
while let Some(line) = lines.next() {
|
||||
let Some((key, rest)) = literal(line) else { continue };
|
||||
let Some(rest) = rest.trim_start().strip_prefix("=>") else { continue };
|
||||
let rest = rest.trim();
|
||||
let value =
|
||||
if rest.starts_with('{') { lines.next().and_then(|next| literal(next).map(|(v, _)| v)) } else { literal(rest).map(|(v, _)| v) };
|
||||
if let Some(value) = value {
|
||||
entries.push((key, value));
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
fn placeholders(template: &str) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let mut chars = template.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '{' && chars.peek() == Some(&'{') {
|
||||
chars.next();
|
||||
} else if c == '{' {
|
||||
let field: String = chars.by_ref().take_while(|c| *c != '}').collect();
|
||||
found.push(field);
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_entries_are_parsed_and_unique() {
|
||||
let entries = catalog_entries();
|
||||
assert!(entries.len() > 1000, "parsed only {} catalog entries", entries.len());
|
||||
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
|
||||
keys.sort_unstable();
|
||||
let before = keys.len();
|
||||
keys.dedup();
|
||||
assert_eq!(before, keys.len(), "duplicate catalog keys");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_translations_keep_the_english_placeholders() {
|
||||
for (source, translation) in catalog_entries() {
|
||||
assert_eq!(placeholders(&source), placeholders(&translation), "placeholders differ for {source:?}");
|
||||
assert_eq!(super::pt_br::translate(&source), Some(translation.as_str()), "lookup differs for {source:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_localized_source_string_has_a_catalog_entry() {
|
||||
fn visit(dir: &std::path::Path, missing: &mut Vec<String>) {
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return };
|
||||
for entry in read.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
visit(&path, missing);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("localization.rs") {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
for marker in ["localization::text(\"", "localized_format!(\""] {
|
||||
for (at, _) in text.match_indices(marker) {
|
||||
let start = at + marker.len() - 1;
|
||||
if let Some((source, _)) = literal(&text[start..])
|
||||
&& super::pt_br::translate(&source).is_none()
|
||||
{
|
||||
missing.push(format!("{}: {source:?}", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut missing = Vec::new();
|
||||
visit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut missing);
|
||||
assert!(missing.is_empty(), "strings without a pt-BR entry:\n{}", missing.join("\n"));
|
||||
}
|
||||
}
|
||||
+47
-21
@@ -77,6 +77,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
|
||||
("ui.new_tracks_dialog", "New Tracks…", "", None),
|
||||
("ui.bounce_dialog", "Bounce Mix…", "", None),
|
||||
("ui.set", "Set UI State", "", None),
|
||||
("ui.language", "Language", "", None),
|
||||
("ui.theme", "Appearance", "", None),
|
||||
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
|
||||
("ui.undo_levels", "Levels of Undo", "", None),
|
||||
@@ -272,32 +273,32 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
ui,
|
||||
|ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button("SoundCraft", |ui| {
|
||||
ui.menu_button(crate::localization::text("SoundCraft"), |ui| {
|
||||
ui.add_enabled_ui(menu_entries_enabled, |ui| {
|
||||
if ui.button("About SoundCraft").clicked() {
|
||||
if ui.button(crate::localization::text("About SoundCraft")).clicked() {
|
||||
app.ui.show_about = true;
|
||||
}
|
||||
if ui.add_enabled(preferences_enabled, egui::Button::new("Preferences...")).clicked() {
|
||||
if ui.add_enabled(preferences_enabled, egui::Button::new(crate::localization::text("Preferences..."))).clicked() {
|
||||
let _ = app.run("setup.preferences", json!({"value": true}));
|
||||
}
|
||||
if ui.button("Check for Updates…").clicked() {
|
||||
if ui.button(crate::localization::text("Check for Updates…")).clicked() {
|
||||
let _ = app.run("app.checkForUpdates", json!({}));
|
||||
}
|
||||
if ui.button("Session Info").clicked() {
|
||||
if ui.button(crate::localization::text("Session Info")).clicked() {
|
||||
app.ui.show_session_info = true;
|
||||
}
|
||||
if ui.button("Session Audio Health").clicked() {
|
||||
if ui.button(crate::localization::text("Session Audio Health")).clicked() {
|
||||
let _ = app.run("window.audio_health", json!({"value": true}));
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Quit").clicked() {
|
||||
if ui.button(crate::localization::text("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| {
|
||||
ui.menu_button(crate::localization::text(&root.label), |ui| {
|
||||
scrolling(ui, |ui| {
|
||||
ui.add_enabled_ui(menu_entries_enabled, |ui| {
|
||||
for c in &root.children {
|
||||
@@ -311,14 +312,16 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
if root.path == "AudioSuite" {
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new("Processes selected clips offline").small().color(t.text_dim));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text("Processes selected clips offline")).small().color(t.text_dim),
|
||||
);
|
||||
}
|
||||
if root.path == "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")
|
||||
.checkbox(&mut separate, crate::localization::text("Mix in Separate Window"))
|
||||
.on_hover_text(crate::localization::text("Show Edit and Mix at once, e.g. one per monitor"))
|
||||
.changed()
|
||||
{
|
||||
let _ = run_ui_command(app, "window.mix_separate", &json!({"value": separate}));
|
||||
@@ -333,7 +336,11 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
"{}{} — {}",
|
||||
app.engine.session().name,
|
||||
if app.engine.is_dirty() { " *" } else { "" },
|
||||
if app.ui.window == MainWindow::Edit || app.ui.mix_separate { "Edit" } else { "Mix" }
|
||||
if app.ui.window == MainWindow::Edit || app.ui.mix_separate {
|
||||
crate::localization::text("Edit")
|
||||
} else {
|
||||
crate::localization::text("Mix")
|
||||
}
|
||||
);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(egui::RichText::new(title).color(t.text_dim));
|
||||
@@ -353,10 +360,11 @@ fn scrolling<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
fn instrument_menu(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
match instrument_track(app.engine.session()) {
|
||||
Some(id) => {
|
||||
ui.menu_button("Instrument", |ui| crate::mix_window::instrument_menu(app, ui, id));
|
||||
ui.menu_button(crate::localization::text("Instrument"), |ui| crate::mix_window::instrument_menu(app, ui, id));
|
||||
}
|
||||
None => {
|
||||
ui.add_enabled(false, egui::Button::new("Instrument")).on_disabled_hover_text("Select an instrument track");
|
||||
ui.add_enabled(false, egui::Button::new(crate::localization::text("Instrument")))
|
||||
.on_disabled_hover_text(crate::localization::text("Select an instrument track"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -368,7 +376,7 @@ fn instrument_track(s: &soundcraft_model::Session) -> Option<soundcraft_model::T
|
||||
|
||||
fn menu_node(app: &mut SoundApp, ui: &mut egui::Ui, n: &MenuNode, extra: &[(&str, &str)]) {
|
||||
if !n.children.is_empty() {
|
||||
ui.menu_button(&n.label, |ui| {
|
||||
ui.menu_button(crate::localization::text(&n.label).to_string(), |ui| {
|
||||
scrolling(ui, |ui| {
|
||||
for c in &n.children {
|
||||
menu_node(app, ui, c, extra);
|
||||
@@ -379,12 +387,13 @@ fn menu_node(app: &mut SoundApp, ui: &mut egui::Ui, n: &MenuNode, extra: &[(&str
|
||||
}
|
||||
let id = command_for_path(&n.path, extra);
|
||||
let (enabled, checked) = item_state(app, &n.path, id.as_deref());
|
||||
let label = live_label(app, id.as_deref()).unwrap_or_else(|| n.label.clone());
|
||||
let label = live_label(app, id.as_deref()).unwrap_or_else(|| crate::localization::text(&n.label).to_string());
|
||||
let label = if checked { format!("✔ {label}") } else { label };
|
||||
let shortcut = id.as_deref().and_then(shortcut_for).unwrap_or("");
|
||||
let btn = egui::Button::new(label).shortcut_text(crate::shortcuts::shortcut_label(shortcut, ui.ctx().os().is_mac()));
|
||||
let btn = egui::Button::new(label).shortcut_text(crate::shortcuts::display_shortcut(shortcut, ui.ctx().os().is_mac()));
|
||||
let response = ui.add_enabled(enabled, btn);
|
||||
let response = if catalog::is_placeholder(&n.path) { response.on_disabled_hover_text("Not available yet.") } else { response };
|
||||
let response =
|
||||
if catalog::is_placeholder(&n.path) { response.on_disabled_hover_text(crate::localization::text("Not available yet.")) } else { response };
|
||||
if response.clicked()
|
||||
&& let Some(id) = id
|
||||
{
|
||||
@@ -536,8 +545,14 @@ pub fn shortcut_for(id: &str) -> Option<&'static str> {
|
||||
pub fn live_label(app: &SoundApp, id: Option<&str>) -> Option<String> {
|
||||
let e = &app.engine;
|
||||
match id? {
|
||||
"edit.undo" => Some(e.undo_label().map_or_else(|| "Can't Undo".into(), |l| format!("Undo {l}"))),
|
||||
"edit.redo" => Some(e.redo_label().map_or_else(|| "Can't Redo".into(), |l| format!("Redo {l}"))),
|
||||
"edit.undo" => Some(e.undo_label().map_or_else(
|
||||
|| crate::localization::text("Can't Undo").into(),
|
||||
|l| crate::localized_format!("Undo {l}", l = crate::localization::text(l)),
|
||||
)),
|
||||
"edit.redo" => Some(e.redo_label().map_or_else(
|
||||
|| crate::localization::text("Can't Redo").into(),
|
||||
|l| crate::localized_format!("Redo {l}", l = crate::localization::text(l)),
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -607,6 +622,16 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
json!({"value": *v})
|
||||
};
|
||||
let r = match id {
|
||||
"ui.language" => {
|
||||
let Some(tag) = p.get("language").and_then(Value::as_str) else {
|
||||
return Some(Ok(json!({"language": app.ui.language.id()})));
|
||||
};
|
||||
let Some(language) = crate::localization::Language::parse(tag) else {
|
||||
return Some(Err(format!("unknown language `{tag}` (en or pt-BR)")));
|
||||
};
|
||||
app.ui.language = language;
|
||||
json!({"language": language.id()})
|
||||
}
|
||||
"app.checkForUpdates" | "help.checkForUpdates" => {
|
||||
crate::updates_ui::check(app);
|
||||
json!({})
|
||||
@@ -713,7 +738,7 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
}
|
||||
"window.arrange_tile" | "window.arrange_tile_h" | "window.arrange_tile_v" | "window.arrange_cascade" => {
|
||||
if let Err(error) = crate::docking::arrange(app) {
|
||||
app.ui.status = format!("Panel windows could not be arranged: {error}");
|
||||
app.ui.status = crate::localized_format!("Panel windows could not be arranged: {error}", error = error);
|
||||
}
|
||||
app.arrange_request = true;
|
||||
json!({})
|
||||
@@ -732,6 +757,7 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
|
||||
app.preferences.discard_draft();
|
||||
app.ui.show_automation = false;
|
||||
app.ui.plugin_windows.clear();
|
||||
app.ui.output_window = None;
|
||||
app.ui.audiosuite = None;
|
||||
json!({})
|
||||
}
|
||||
|
||||
@@ -11,11 +11,13 @@ use serde_json::json;
|
||||
use soundcraft_model::{ChannelFormat, Route, SurroundPan, Track, TrackId, TrackKind};
|
||||
use soundcraft_playback::MeterSnapshot;
|
||||
|
||||
mod output;
|
||||
mod plugin_menu;
|
||||
mod routing;
|
||||
mod sends;
|
||||
mod slots;
|
||||
|
||||
pub(crate) use output::{output_window, toggle_output_window};
|
||||
pub use plugin_menu::{instrument_menu, plugin_info, plugin_menu};
|
||||
pub(crate) use routing::{input_name, route_name, route_popup};
|
||||
#[cfg(test)]
|
||||
@@ -36,7 +38,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) {
|
||||
/// be seen at once, e.g. one per monitor. Closing that window brings Mix back into the main one.
|
||||
/// Backends without multiple windows show it as a floating egui window instead.
|
||||
pub fn show_separate(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let title = format!("{} — Mix", app.engine.session().name);
|
||||
let title = format!("{} — {}", app.engine.session().name, crate::localization::text("Mix"));
|
||||
let builder = egui::ViewportBuilder::default().with_title(title).with_inner_size([1100.0, 720.0]).with_min_inner_size([480.0, 320.0]);
|
||||
ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("soundcraft.mix"), builder, |ui, _class| {
|
||||
ui.set_style(ui.ctx().global_style());
|
||||
@@ -147,10 +149,13 @@ fn short_label(text: &str) -> &str {
|
||||
fn section_label(ui: &Ui, r: Rect, text: &str, narrow: bool) {
|
||||
let p = ui.painter();
|
||||
let color = Tokens::current().section_label;
|
||||
let text = if narrow { short_label(text) } else { text };
|
||||
let mut galley = p.layout_no_wrap(text.to_owned(), bold(10.0), color);
|
||||
let source = text;
|
||||
let short = crate::localization::text(short_label(source));
|
||||
let text = crate::localization::text(source);
|
||||
let label = if narrow { short } else { text };
|
||||
let mut galley = p.layout_no_wrap(label.to_owned(), bold(10.0), color);
|
||||
if galley.size().x > r.width() - 8.0 {
|
||||
galley = p.layout_no_wrap(short_label(text).to_owned(), bold(10.0), color);
|
||||
galley = p.layout_no_wrap(short.to_owned(), bold(10.0), color);
|
||||
}
|
||||
p.galley(Align2::CENTER_CENTER.anchor_size(pos2(r.center().x, r.min.y + 7.0), galley.size()).min, galley, color);
|
||||
}
|
||||
@@ -237,7 +242,7 @@ fn preamp_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
|
||||
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(kr));
|
||||
let resp = c
|
||||
.add_sized(kr.size(), egui::DragValue::new(&mut db).range(-24.0..=24.0).speed(0.1).suffix(" dB").max_decimals(1))
|
||||
.accessible_name("Input trim (dB)");
|
||||
.accessible_name(crate::localization::text("Input trim (dB)"));
|
||||
if resp.changed() {
|
||||
let _ = app.engine.execute_merged("mix.trim", &json!({"tracks": [id.0], "db": db}), &format!("trim:{}", id.0));
|
||||
}
|
||||
@@ -264,7 +269,7 @@ fn instrument_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y:
|
||||
_ if track.kind == TrackKind::Instrument => instrument_slot(app, ui, track, sr),
|
||||
Some(k) => insert_slot(app, ui, track, k, sr),
|
||||
None if track.kind == TrackKind::Midi => {
|
||||
ui.painter().text(sr.center(), Align2::CENTER_CENTER, "MIDI in: all", regular(9.0), t.text_dim);
|
||||
ui.painter().text(sr.center(), Align2::CENTER_CENTER, crate::localization::text("MIDI in: all"), regular(9.0), t.text_dim);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
@@ -282,8 +287,11 @@ fn object_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
|
||||
if has_input {
|
||||
let on = app.engine.session().edit.flag(&format!("object.{}", id.0));
|
||||
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(sec));
|
||||
let label = egui::RichText::new(if on { "OBJECT" } else { "BED" }).font(bold(9.0));
|
||||
if c.add_sized(sec.size(), egui::Button::new(label).selected(on)).on_hover_text("Route as an immersive object or to the bed").clicked() {
|
||||
let label = egui::RichText::new(crate::localization::text(if on { "OBJECT" } else { "BED" })).font(bold(9.0));
|
||||
if c.add_sized(sec.size(), egui::Button::new(label).selected(on))
|
||||
.on_hover_text(crate::localization::text("Route as an immersive object or to the bed"))
|
||||
.clicked()
|
||||
{
|
||||
let _ = app.run("track.object", json!({"tracks": [id.0], "object": !on}));
|
||||
}
|
||||
}
|
||||
@@ -364,10 +372,10 @@ fn comments_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f
|
||||
let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 44.0));
|
||||
let mut c = track.comments.clone();
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(sec));
|
||||
let hint = if narrow { "" } else { "comments" };
|
||||
let hint = if narrow { "" } else { crate::localization::text("comments") };
|
||||
let field = crate::widgets::named_text_field(
|
||||
child.add(egui::TextEdit::multiline(&mut c).desired_width(inner_w).desired_rows(2).hint_text(hint).font(regular(10.0))),
|
||||
&format!("Comments for {}", track.name),
|
||||
&crate::localized_format!("Comments for {}", track.name),
|
||||
);
|
||||
if field.changed() {
|
||||
let _ = app.engine.execute_merged("track.comments", &json!({"track": id.0, "comments": c}), &format!("comments:{}", id.0));
|
||||
@@ -403,7 +411,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
|
||||
in_r.height(),
|
||||
&input,
|
||||
t.text,
|
||||
SelectorLabels { name: &format!("Input for {}", track.name), value: &input, tooltip: "Input" },
|
||||
SelectorLabels {
|
||||
name: &crate::localized_format!("Input for {}", track.name),
|
||||
value: &input,
|
||||
tooltip: crate::localization::text("Input"),
|
||||
},
|
||||
);
|
||||
route_popup(app, &resp, id, true);
|
||||
}
|
||||
@@ -415,7 +427,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
|
||||
out_r.height(),
|
||||
&output,
|
||||
t.text,
|
||||
SelectorLabels { name: &format!("Output for {}", track.name), value: &output, tooltip: "Output" },
|
||||
SelectorLabels {
|
||||
name: &crate::localized_format!("Output for {}", track.name),
|
||||
value: &output,
|
||||
tooltip: crate::localization::text("Output"),
|
||||
},
|
||||
);
|
||||
route_popup(app, &resp, id, false);
|
||||
// Automation mode.
|
||||
@@ -430,11 +446,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
|
||||
} else {
|
||||
t.auto_write
|
||||
};
|
||||
let full_label = format!("auto {}", mode.label());
|
||||
let full_label = crate::localized_format!("auto {}", crate::localization::text(mode.label()));
|
||||
let label = if mode == soundcraft_model::AutomationMode::TouchLatch {
|
||||
if narrow { "t/l" } else { mode.label() }
|
||||
if narrow { "t/l" } else { crate::localization::text(mode.label()) }
|
||||
} else if narrow {
|
||||
mode.label()
|
||||
crate::localization::text(mode.label())
|
||||
} else {
|
||||
&full_label
|
||||
};
|
||||
@@ -444,11 +460,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
|
||||
am_r.height(),
|
||||
label,
|
||||
col,
|
||||
SelectorLabels { name: &format!("Automation mode for {}", track.name), value: &full_label, tooltip: &full_label },
|
||||
SelectorLabels { name: &crate::localized_format!("Automation mode for {}", track.name), value: &full_label, tooltip: &full_label },
|
||||
);
|
||||
egui::Popup::menu(&resp).show(|ui| {
|
||||
for m in soundcraft_model::AutomationMode::ALL {
|
||||
if ui.selectable_label(m == mode, m.label()).clicked() {
|
||||
if ui.selectable_label(m == mode, crate::localization::text(m.label())).clicked() {
|
||||
let _ = app.run("mix.automation_mode", json!({"track": id.0, "mode": m.label()}));
|
||||
}
|
||||
}
|
||||
@@ -464,7 +480,13 @@ fn group_selector(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
|
||||
let t = Tokens::current();
|
||||
// Group selector.
|
||||
let no_group = if narrow { "nogrp" } else { "no group" };
|
||||
let gname = app.engine.session().groups.iter().find(|g| g.members.contains(&id)).map_or(no_group.to_string(), |g| g.name.clone());
|
||||
let gname = app
|
||||
.engine
|
||||
.session()
|
||||
.groups
|
||||
.iter()
|
||||
.find(|g| g.members.contains(&id))
|
||||
.map_or(crate::localization::text(no_group).to_string(), |g| g.name.clone());
|
||||
let gr = Rect::from_min_size(pos2(x0 + 2.0, y), vec2(inner_w - 4.0, 16.0));
|
||||
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(gr));
|
||||
let _ = selector_box_named(
|
||||
@@ -473,7 +495,7 @@ fn group_selector(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
|
||||
gr.height(),
|
||||
&gname,
|
||||
t.text_dim,
|
||||
SelectorLabels { name: &format!("Group for {}", track.name), value: &gname, tooltip: "Group" },
|
||||
SelectorLabels { name: &crate::localized_format!("Group for {}", track.name), value: &gname, tooltip: crate::localization::text("Group") },
|
||||
);
|
||||
y += 22.0;
|
||||
y
|
||||
@@ -526,7 +548,7 @@ fn pan_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
|
||||
pr,
|
||||
ui.scope_id().with(("pan-value", id.0, i)),
|
||||
Readout {
|
||||
name: &format!("{} pan {}", track.name, i + 1),
|
||||
name: &crate::localized_format!("{} pan {}", track.name, i + 1),
|
||||
display: &pan_text(v),
|
||||
edit_initial: &format!("{:.0}", v * 100.0),
|
||||
parse: parse_pan,
|
||||
@@ -553,11 +575,11 @@ fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
|
||||
);
|
||||
row.spacing_mut().item_spacing.x = 6.0;
|
||||
if track.kind.has_playlist() {
|
||||
let input_label = format!("Input monitoring for {}", track.name);
|
||||
let input_label = crate::localized_format!("Input monitoring for {}", track.name);
|
||||
if text_toggle(&mut row, vec2(bw, 18.0), "I", track.mixer.input_monitor, t.input, &input_label).clicked() {
|
||||
let _ = app.run("mix.input_monitor", json!({"track": id.0}));
|
||||
}
|
||||
let record_label = format!("Record enable for {}", track.name);
|
||||
let record_label = crate::localized_format!("Record enable for {}", track.name);
|
||||
if rec_toggle(&mut row, vec2(bw, 18.0), track.mixer.record_arm, &record_label).clicked() {
|
||||
let _ = app.run("mix.record_arm", json!({"track": id.0}));
|
||||
}
|
||||
@@ -568,11 +590,11 @@ fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
|
||||
);
|
||||
row.spacing_mut().item_spacing.x = 6.0;
|
||||
if track.kind != TrackKind::Master {
|
||||
let solo_label = format!("Solo for {}", track.name);
|
||||
let solo_label = crate::localized_format!("Solo for {}", track.name);
|
||||
if text_toggle(&mut row, vec2(bw, 18.0), "S", track.mixer.solo, t.solo, &solo_label).clicked() {
|
||||
let _ = app.run("mix.solo", json!({"track": id.0}));
|
||||
}
|
||||
let mute_label = format!("Mute for {}", track.name);
|
||||
let mute_label = crate::localized_format!("Mute for {}", track.name);
|
||||
if text_toggle(&mut row, vec2(bw, 18.0), "M", track.mixer.mute, t.mute, &mute_label).clicked() {
|
||||
let _ = app.run("mix.mute", json!({"track": id.0}));
|
||||
}
|
||||
@@ -632,7 +654,7 @@ fn name_and_readout(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>) {
|
||||
vr,
|
||||
ui.scope_id().with(("volume-value", id.0)),
|
||||
Readout {
|
||||
name: &format!("{} volume", track.name),
|
||||
name: &crate::localized_format!("{} volume", track.name),
|
||||
display: &db_text(track.mixer.volume_db),
|
||||
edit_initial: &format!("{:.1}", track.mixer.volume_db),
|
||||
parse: parse_db,
|
||||
@@ -652,7 +674,7 @@ fn name_and_readout(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>) {
|
||||
TrackKind::Folder => "folder",
|
||||
TrackKind::Video => "video",
|
||||
};
|
||||
ui.painter().text(pos2(vr.center().x, vr.max.y + 9.0), Align2::CENTER_CENTER, kind, regular(9.5), t.text_dim);
|
||||
ui.painter().text(pos2(vr.center().x, vr.max.y + 9.0), Align2::CENTER_CENTER, crate::localization::text(kind), regular(9.5), t.text_dim);
|
||||
let nr = Rect::from_min_size(pos2(x0, r.max.y - 26.0), vec2(inner_w, 18.0));
|
||||
ui.painter().rect(
|
||||
nr,
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! The Output window, as in Pro Tools: one track's volume fader and readout, pan, Solo and Mute,
|
||||
//! floating over the Edit window. The fader button beside a track's Output selector opens it.
|
||||
|
||||
use super::routing::route_name;
|
||||
use super::sends::{Readout, editable_readout, parse_db, parse_pan};
|
||||
use super::{SoundApp, Tokens, TrackId, TrackKind, db_text, fader, json, pan_knob, pan_text, pos2, surround_panned, text_toggle, vec2};
|
||||
|
||||
/// Open the Output window on `track`, or close it when it already shows that track.
|
||||
pub(crate) fn toggle_output_window(app: &mut SoundApp, track: TrackId) {
|
||||
app.ui.output_window = (app.ui.output_window != Some(track)).then_some(track);
|
||||
}
|
||||
|
||||
/// Draw the Output window; Escape closes it, unless a menu, a text field or a dialog takes it.
|
||||
pub(crate) fn output_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// As for the Send window: whether this Escape was a menu's or a text field's comes from the
|
||||
// last frame, because egui closes them before this runs.
|
||||
let busy_id = egui::Id::unique("output_window_escape");
|
||||
let busy = ctx.data(|d| d.get_temp(busy_id)).unwrap_or(false) || app.dialogs.open.is_some() || app.ui.show_search;
|
||||
if !busy && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.ui.output_window = None;
|
||||
}
|
||||
output_window_contents(app, ctx);
|
||||
let busy = egui::Popup::is_any_open(ctx) || ctx.text_edit_focused();
|
||||
ctx.data_mut(|d| d.insert_temp(busy_id, busy));
|
||||
}
|
||||
|
||||
/// The window for the remembered track; closes it when that track no longer exists.
|
||||
fn output_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let Some(id) = app.ui.output_window else { return };
|
||||
let Some(track) = app.engine.session().track(id).cloned() else {
|
||||
app.ui.output_window = None;
|
||||
return;
|
||||
};
|
||||
let t = Tokens::current();
|
||||
let name = track.name.clone();
|
||||
// The readouts' ids name the document too: a value typed for a track of the old session
|
||||
// never reaches a track of the new one with the same id.
|
||||
let doc = app.doc_epoch;
|
||||
let mut open = true;
|
||||
egui::Window::new(format!("{name} · Output"))
|
||||
.id(egui::Id::unique("output_window"))
|
||||
.open(&mut open)
|
||||
.auto_sized()
|
||||
.collapsible(false)
|
||||
.default_pos(ctx.pointer_latest_pos().map_or(pos2(200.0, 200.0), |p| p + vec2(24.0, -160.0)))
|
||||
.show(ctx, |ui| {
|
||||
ui.set_width(150.0);
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.label(egui::RichText::new(route_name(app, &track.mixer.output)).color(t.counter_text));
|
||||
if track.kind != TrackKind::Master {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
ui.add_space(((ui.available_width() - 48.0) / 2.0).max(0.0));
|
||||
if text_toggle(ui, vec2(22.0, 18.0), "S", track.mixer.solo, t.solo, &format!("{name} output solo")).clicked() {
|
||||
let _ = app.run("mix.solo", json!({"track": id.0}));
|
||||
}
|
||||
if text_toggle(ui, vec2(22.0, 18.0), "M", track.mixer.mute, t.mute, &format!("{name} output mute")).clicked() {
|
||||
let _ = app.run("mix.mute", json!({"track": id.0}));
|
||||
}
|
||||
});
|
||||
}
|
||||
// The stereo knobs, as on the track's strip; a surround panner stays in the Mix window.
|
||||
if !track.mixer.pan.is_empty() && track.kind != TrackKind::Vca && !surround_panned(app, &track) {
|
||||
ui.horizontal(|ui| {
|
||||
let n = track.mixer.pan.len().min(2);
|
||||
ui.add_space(((ui.available_width() - 36.0 * n as f32) / 2.0).max(0.0));
|
||||
for i in 0..n {
|
||||
ui.vertical(|ui| {
|
||||
let mut v = track.mixer.pan.get(i).copied().unwrap_or(0.0);
|
||||
let before = v;
|
||||
pan_knob(ui, 32.0, &mut v, &format!("{name} output pan {} (drag; double-click centres)", i + 1));
|
||||
if (v - before).abs() > f32::EPSILON {
|
||||
let _ = app.engine.execute_merged(
|
||||
"mix.pan",
|
||||
&json!({"track": id.0, "pan": v, "index": i}),
|
||||
&format!("pan:{}:{i}", id.0),
|
||||
);
|
||||
}
|
||||
let (pr, _) = ui.allocate_exact_size(vec2(32.0, 13.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(pr, 1.0, t.counter_bg);
|
||||
let (_, typed) = editable_readout(
|
||||
ui,
|
||||
pr,
|
||||
ui.scope_id().with(("output_pan_value", doc, id.0, i)),
|
||||
Readout {
|
||||
name: &format!("{name} output pan {} value", i + 1),
|
||||
display: &pan_text(v),
|
||||
edit_initial: &format!("{:.0}", v * 100.0),
|
||||
parse: parse_pan,
|
||||
reset: 0.0,
|
||||
},
|
||||
);
|
||||
// The strip's merge key, so a typed value joins a running automation pass.
|
||||
if let Some(v) = typed {
|
||||
let _ = app.engine.execute_merged(
|
||||
"mix.pan",
|
||||
&json!({"track": id.0, "pan": v, "index": i}),
|
||||
&format!("pan:{}:{i}", id.0),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
let (fr, _) = ui.allocate_exact_size(vec2(56.0, 220.0), egui::Sense::hover());
|
||||
// Distinct from the strip's "<track> level", so a label query while the Mix window
|
||||
// is open still picks one node.
|
||||
if let Some(db) = fader(ui, fr, track.mixer.volume_db, ui.scope_id().with("output_fader"), &format!("{name} output level")) {
|
||||
app.gesture = Some(crate::Gesture::Fader { track: id, start_db: track.mixer.volume_db });
|
||||
// The strip's merge key: one undo step for a drag, whichever fader it uses.
|
||||
let _ = app.engine.execute_merged("mix.volume", &json!({"track": id.0, "db": db}), &format!("fader:{}", id.0));
|
||||
}
|
||||
let (rr, _) = ui.allocate_exact_size(vec2(64.0, 15.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(rr, 1.0, t.counter_bg);
|
||||
let (_, typed) = editable_readout(
|
||||
ui,
|
||||
rr,
|
||||
ui.scope_id().with(("output_volume_value", doc, id.0)),
|
||||
Readout {
|
||||
name: &format!("{name} output volume"),
|
||||
display: &db_text(track.mixer.volume_db),
|
||||
edit_initial: &format!("{:.1}", track.mixer.volume_db),
|
||||
parse: parse_db,
|
||||
reset: 0.0,
|
||||
},
|
||||
);
|
||||
if let Some(db) = typed {
|
||||
let _ = app.engine.execute_merged("mix.volume", &json!({"track": id.0, "db": db}), &format!("fader:{}", id.0));
|
||||
}
|
||||
});
|
||||
});
|
||||
if !open {
|
||||
app.ui.output_window = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{MainWindow, Services};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
|
||||
/// The demo session in the Edit window with the I/O column shown and Kick tall enough for its
|
||||
/// Output row; returns the harness and Kick's id.
|
||||
fn edit_window_with_io() -> (Harness<'static, SoundApp>, TrackId) {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
app.run("view.edit_io", json!({})).unwrap();
|
||||
app.run("track.height", json!({"tracks": ["Kick"], "height": "medium"})).unwrap();
|
||||
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
(h, kick)
|
||||
}
|
||||
|
||||
fn kick_mixer(h: &Harness<'_, SoundApp>, kick: TrackId) -> soundcraft_model::Mixer {
|
||||
h.state().engine.session().track(kick).unwrap().mixer.clone()
|
||||
}
|
||||
|
||||
/// Drags the pointer from `from` by `dy` points with the primary button held.
|
||||
fn drag(h: &mut Harness<'_, SoundApp>, from: egui::Pos2, dy: f32) {
|
||||
use egui::{Event, Modifiers, PointerButton};
|
||||
h.input_mut().events.push(Event::PointerMoved(from));
|
||||
h.step();
|
||||
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
for i in 1..=10 {
|
||||
h.input_mut().events.push(Event::PointerMoved(from + egui::vec2(0.0, dy * i as f32 / 10.0)));
|
||||
h.step();
|
||||
}
|
||||
let to = from + egui::vec2(0.0, dy);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// Opens Kick's Output window, clicks its volume readout and replaces the text with `text`,
|
||||
/// leaving the draft open (not committed).
|
||||
fn open_kick_and_type_volume(h: &mut Harness<'_, SoundApp>, text: &str) {
|
||||
h.get_by_label("Output window for Kick").click();
|
||||
h.run_steps(2);
|
||||
let fader = h.get_by_label("Kick output level").rect();
|
||||
// The volume readout sits just below the fader.
|
||||
let readout = egui::pos2(fader.center().x, fader.bottom() + 10.0);
|
||||
h.input_mut().events.push(egui::Event::PointerMoved(readout));
|
||||
h.step();
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(egui::Event::PointerButton {
|
||||
pos: readout,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.step();
|
||||
}
|
||||
h.run_steps(1);
|
||||
assert!(h.query_by_label("Kick output volume").is_some(), "clicking the readout starts editing");
|
||||
// Replace the initial text, as a user typing a new value does.
|
||||
h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
|
||||
h.event(egui::Event::Text(text.into()));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// #1392: the fader button beside Kick's Output selector opens Kick's Output window, whose
|
||||
/// controls edit Kick; it stays in the Edit window, and a second click closes the window.
|
||||
#[test]
|
||||
fn the_output_fader_button_opens_the_tracks_output_window() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let (mut h, kick) = edit_window_with_io();
|
||||
assert!(h.query_by_label("Kick output level").is_none(), "no Output window before the click");
|
||||
h.get_by_label("Output window for Kick").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, Some(kick));
|
||||
assert_eq!(h.state().ui.window, MainWindow::Edit, "the Mix window did not take over");
|
||||
|
||||
let before = kick_mixer(&h, kick);
|
||||
let fader = h.get_by_label("Kick output level").rect();
|
||||
drag(&mut h, fader.center(), -40.0);
|
||||
let after = kick_mixer(&h, kick);
|
||||
assert!(after.volume_db > before.volume_db + 0.5, "dragging the fader up raised Kick: {} -> {}", before.volume_db, after.volume_db);
|
||||
|
||||
h.get_by_label("Kick output mute").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(kick_mixer(&h, kick).mute, !before.mute, "Mute toggles Kick");
|
||||
h.get_by_label("Kick output solo").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(kick_mixer(&h, kick).solo, !before.solo, "Solo toggles Kick");
|
||||
|
||||
h.get_by_label("Output window for Kick").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, None, "a second click closes it");
|
||||
assert!(h.query_by_label("Kick output level").is_none());
|
||||
}
|
||||
|
||||
/// Escape closes the Output window, and so does deleting its track.
|
||||
#[test]
|
||||
fn escape_or_deleting_the_track_closes_the_output_window() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let (mut h, kick) = edit_window_with_io();
|
||||
h.get_by_label("Output window for Kick").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, Some(kick));
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, None, "Escape closes it");
|
||||
|
||||
h.get_by_label("Output window for Kick").click();
|
||||
h.run_steps(2);
|
||||
h.state_mut().run("track.delete", json!({"tracks": [kick.0]})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, None, "the window closes with its track");
|
||||
}
|
||||
|
||||
/// A value being typed into Kick's volume readout stays with Kick: switching the window to
|
||||
/// Snare does not carry the draft over, and Enter there does not set Snare's volume.
|
||||
#[test]
|
||||
fn a_typed_readout_value_does_not_follow_the_window_to_another_track() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let (mut h, _) = edit_window_with_io();
|
||||
h.state_mut().run("track.height", json!({"tracks": ["Snare"], "height": "medium"})).unwrap();
|
||||
h.run_steps(2);
|
||||
let snare = h.state().engine.session().track_by_name("Snare").unwrap().id;
|
||||
let snare_db = |h: &Harness<'_, SoundApp>| h.state().engine.session().track(snare).unwrap().mixer.volume_db;
|
||||
let snare_before = snare_db(&h);
|
||||
|
||||
open_kick_and_type_volume(&mut h, "-20");
|
||||
|
||||
// The window now shows Snare (as when Snare's Output button is clicked), with Kick's draft open.
|
||||
h.state_mut().ui.output_window = Some(snare);
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label("Snare output volume").is_none(), "Snare's readout is not being edited");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(snare_db(&h), snare_before, "Kick's draft did not reach Snare");
|
||||
}
|
||||
|
||||
/// Opening another session retires the Output window and its draft, also when the new
|
||||
/// session has a track with the same id: here a fresh demo session, whose Kick has the old
|
||||
/// Kick's id. Enter does not commit the old draft to the new Kick, and reopening the window
|
||||
/// on the new Kick does not bring the draft back.
|
||||
#[test]
|
||||
fn opening_another_session_retires_the_output_window_and_its_draft() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let (mut h, kick) = edit_window_with_io();
|
||||
open_kick_and_type_volume(&mut h, "-20");
|
||||
|
||||
h.state_mut().run("session.new", json!({"template": "demo"})).unwrap();
|
||||
assert_eq!(h.state().engine.session().track_by_name("Kick").unwrap().id, kick, "the new Kick reuses the id");
|
||||
let new_kick_db = kick_mixer(&h, kick).volume_db;
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, None, "the window closes with its session");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(kick_mixer(&h, kick).volume_db, new_kick_db, "the old draft did not reach the new Kick");
|
||||
|
||||
h.state_mut().ui.output_window = Some(kick);
|
||||
h.step();
|
||||
assert!(h.query_by_label("Kick output level").is_some(), "the window is open on the new Kick");
|
||||
assert!(h.query_by_label("Kick output volume").is_none(), "the new Kick's readout is not being edited");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(kick_mixer(&h, kick).volume_db, new_kick_db);
|
||||
}
|
||||
|
||||
/// Window > Close Window and Hide All Floating Windows close the Output window, as they close
|
||||
/// the other floating windows.
|
||||
#[test]
|
||||
fn close_window_and_hide_all_floating_windows_close_the_output_window() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
let (mut h, kick) = edit_window_with_io();
|
||||
for command in ["window.close", "window.hide_floating"] {
|
||||
h.get_by_label("Output window for Kick").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, Some(kick), "{command}");
|
||||
h.state_mut().run(command, json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.output_window, None, "{command} closes it");
|
||||
assert!(h.query_by_label("Kick output level").is_none(), "{command}: the window is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use super::{Color32, Rect, SoundApp, TrackId, Ui, json, pos2, vec2};
|
||||
/// An insert's menu: a search field that takes typing at once, then (until something is typed)
|
||||
/// Bypass and removal and the plugins by category and format.
|
||||
pub fn plugin_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, occupied: bool) {
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("plugin-search", id.0, slot)), "Search plugins…");
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("plugin-search", id.0, slot)), crate::localization::text("Search plugins…"));
|
||||
if search.typing() {
|
||||
if let Some(plugin) = plugin_search(ui, &search, false) {
|
||||
pick_insert(app, ui, id, slot, &plugin);
|
||||
@@ -11,10 +11,10 @@ pub fn plugin_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, oc
|
||||
return;
|
||||
}
|
||||
if occupied {
|
||||
if ui.button("Bypass").clicked() {
|
||||
if ui.button(crate::localization::text("Bypass")).clicked() {
|
||||
run_pick(app, ui, "mix.insert_bypass", json!({"track": id.0, "slot": slot}));
|
||||
}
|
||||
if ui.button("no insert").clicked() {
|
||||
if ui.button(crate::localization::text("no insert")).clicked() {
|
||||
run_pick(app, ui, "mix.insert_remove", json!({"track": id.0, "slot": slot}));
|
||||
}
|
||||
ui.separator();
|
||||
@@ -44,7 +44,7 @@ pub fn plugin_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, oc
|
||||
/// instruments.
|
||||
pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
let slot = soundcraft_mix::INSTRUMENT_SLOT;
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("instrument-search", id.0)), "Search instruments…");
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("instrument-search", id.0)), crate::localization::text("Search instruments…"));
|
||||
if search.typing() {
|
||||
if let Some(plugin) = plugin_search(ui, &search, true) {
|
||||
run_pick(app, ui, "mix.instrument", json!({"track": id.0, "plugin": plugin}));
|
||||
@@ -54,7 +54,9 @@ pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
let current = app.engine.session().track(id).and_then(|t| t.instrument.clone());
|
||||
if let Some(info) = current.as_ref().and_then(|i| plugin_info(&i.plugin)) {
|
||||
ui.label(egui::RichText::new(info.name).strong());
|
||||
if current.as_ref().is_some_and(|i| !soundcraft_mix::is_third_party(&i.plugin)) && ui.button("Edit Parameters…").clicked() {
|
||||
if current.as_ref().is_some_and(|i| !soundcraft_mix::is_third_party(&i.plugin))
|
||||
&& ui.button(crate::localization::text("Edit Parameters…")).clicked()
|
||||
{
|
||||
if !app.ui.plugin_windows.contains(&(id, slot)) {
|
||||
app.ui.plugin_windows.push((id, slot));
|
||||
}
|
||||
@@ -64,13 +66,13 @@ pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
&& p.has_editor(id, slot)
|
||||
{
|
||||
if p.editor_open(id, slot) {
|
||||
if ui.button("Close Plugin Editor").clicked() {
|
||||
if ui.button(crate::localization::text("Close Plugin Editor")).clicked() {
|
||||
p.close_editor(id, slot);
|
||||
ui.close();
|
||||
}
|
||||
} else if ui.button("Open Plugin Editor").clicked() {
|
||||
} else if ui.button(crate::localization::text("Open Plugin Editor")).clicked() {
|
||||
if let Err(e) = p.open_editor(id, slot) {
|
||||
app.ui.status = format!("{}: {e}", info.name);
|
||||
app.ui.status = format!("{}: {}", info.name, crate::localization::error_text(&e.to_string()));
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
@@ -78,7 +80,7 @@ pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
ui.separator();
|
||||
}
|
||||
let mut picked = None;
|
||||
ui.menu_button("Built-in", |ui| {
|
||||
ui.menu_button(crate::localization::text("Built-in"), |ui| {
|
||||
for p in soundcraft_dsp::plugins().iter().filter(|p| p.is_instrument) {
|
||||
if ui.button(p.name).clicked() {
|
||||
picked = Some(p.id.to_string());
|
||||
@@ -141,15 +143,15 @@ fn plugin_search(ui: &mut Ui, search: &MenuSearch, instruments: bool) -> Option<
|
||||
}
|
||||
});
|
||||
if n == 0 {
|
||||
ui.weak("No matches");
|
||||
ui.weak(crate::localization::text("No matches"));
|
||||
}
|
||||
if clap.is_none() || vst3.is_none() {
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if clap.is_none() && ui.small_button("Scan CLAP").clicked() {
|
||||
if clap.is_none() && ui.small_button(crate::localization::text("Scan CLAP")).clicked() {
|
||||
soundcraft_clap_host::scan();
|
||||
}
|
||||
if vst3.is_none() && ui.small_button("Scan VST3").clicked() {
|
||||
if vst3.is_none() && ui.small_button(crate::localization::text("Scan VST3")).clicked() {
|
||||
soundcraft_vst3_host::scan();
|
||||
}
|
||||
});
|
||||
@@ -256,20 +258,20 @@ struct MenuPlugin {
|
||||
/// id picked. Each format is scanned the first time its submenu opens, then cached by its host.
|
||||
fn hosted_menus(ui: &mut Ui, instruments: bool) -> Option<String> {
|
||||
let mut picked = None;
|
||||
ui.menu_button("CLAP", |ui| {
|
||||
ui.menu_button(crate::localization::text("CLAP"), |ui| {
|
||||
let list = soundcraft_clap_host::scan().into_iter().filter(|d| d.is_instrument == instruments);
|
||||
if let Some(p) = vendor_menus(ui, list.map(|d| MenuPlugin { id: d.id, name: d.name, vendor: d.vendor }).collect(), "No CLAP plugins found") {
|
||||
picked = Some(p);
|
||||
}
|
||||
});
|
||||
ui.menu_button("VST3", |ui| {
|
||||
ui.menu_button(crate::localization::text("VST3"), |ui| {
|
||||
let list = soundcraft_vst3_host::scan().into_iter().filter(|d| d.is_instrument == instruments);
|
||||
if let Some(p) = vendor_menus(ui, list.map(|d| MenuPlugin { id: d.id, name: d.name, vendor: d.vendor }).collect(), "No VST3 plugins found") {
|
||||
picked = Some(p);
|
||||
}
|
||||
});
|
||||
if cfg!(target_os = "macos") {
|
||||
ui.menu_button("Audio Units", |ui| {
|
||||
ui.menu_button(crate::localization::text("Audio Units"), |ui| {
|
||||
let list = soundcraft_au_host::scan().into_iter().filter(|d| d.is_instrument == instruments);
|
||||
if let Some(p) = vendor_menus(ui, list.map(|d| MenuPlugin { id: d.id, name: d.name, vendor: d.vendor }).collect(), "No Audio Units found")
|
||||
{
|
||||
@@ -284,7 +286,7 @@ fn hosted_menus(ui: &mut Ui, instruments: bool) -> Option<String> {
|
||||
/// within the screen so that every plugin stays reachable however many are installed.
|
||||
fn vendor_menus(ui: &mut Ui, mut list: Vec<MenuPlugin>, none: &str) -> Option<String> {
|
||||
if list.is_empty() {
|
||||
ui.label(none);
|
||||
ui.label(crate::localization::text(none));
|
||||
return None;
|
||||
}
|
||||
list.sort_by_cached_key(|p| (p.vendor.to_lowercase(), p.name.to_lowercase()));
|
||||
@@ -294,7 +296,7 @@ fn vendor_menus(ui: &mut Ui, mut list: Vec<MenuPlugin>, none: &str) -> Option<St
|
||||
let mut picked = None;
|
||||
egui::ScrollArea::vertical().id_salt("vendors").max_height(max_h).show(ui, |ui| {
|
||||
for v in vendors {
|
||||
ui.menu_button(if v.is_empty() { "Unknown vendor" } else { v }, |ui| {
|
||||
ui.menu_button(if v.is_empty() { crate::localization::text("Unknown vendor") } else { v }, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("plugins").max_height(max_h).show(ui, |ui| {
|
||||
for p in list.iter().filter(|p| p.vendor == v) {
|
||||
if ui.button(&p.name).clicked() {
|
||||
|
||||
@@ -3,8 +3,8 @@ use super::{Route, SoundApp, Track, TrackId, Ui, json};
|
||||
|
||||
pub(crate) fn route_name(app: &SoundApp, r: &Route) -> String {
|
||||
match r {
|
||||
Route::None => "no output".into(),
|
||||
Route::Main => app.engine.session().outputs.first().map_or_else(|| "Out 1-2".into(), |o| o.name.clone()),
|
||||
Route::None => crate::localization::text("no output").to_string(),
|
||||
Route::Main => app.engine.session().outputs.first().map_or_else(|| crate::localization::text("Out 1-2").to_string(), |o| o.name.clone()),
|
||||
Route::Bus(b) => app.engine.session().bus(*b).map_or_else(|| "bus?".into(), |b| b.name.clone()),
|
||||
Route::Hardware(h) => h.clone(),
|
||||
}
|
||||
@@ -13,7 +13,7 @@ pub(crate) fn route_name(app: &SoundApp, r: &Route) -> String {
|
||||
pub(crate) fn input_name(app: &SoundApp, track: &Track) -> String {
|
||||
if track.kind.has_playlist() && track.mixer.input == Route::None {
|
||||
let channels = track.format.channels();
|
||||
if channels == 1 { "In 1".to_string() } else { format!("In 1-{channels}") }
|
||||
if channels == 1 { crate::localized_format!("In {}", 1) } else { crate::localized_format!("In 1-{}", channels) }
|
||||
} else {
|
||||
route_name(app, &track.mixer.input)
|
||||
}
|
||||
@@ -30,14 +30,14 @@ pub(crate) fn route_popup(app: &mut SoundApp, resp: &egui::Response, id: TrackId
|
||||
fn route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, input: bool) {
|
||||
let key = if input { "input" } else { "output" };
|
||||
let cmd = if input { "track.input" } else { "track.output" };
|
||||
let hint = if input { "Search inputs…" } else { "Search outputs…" };
|
||||
let hint = crate::localization::text(if input { "Search inputs…" } else { "Search outputs…" });
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("route-search", id.0, input)), hint);
|
||||
let busses: Vec<String> = app.engine.session().busses.iter().map(|b| b.name.clone()).collect();
|
||||
let main_name = app.engine.session().outputs.first().map_or_else(|| "Out 1-2".to_string(), |o| o.name.clone());
|
||||
// (label, the route the command is given)
|
||||
let mut fixed = vec![(if input { "no input" } else { "no output" }.to_string(), "none".to_string())];
|
||||
let mut fixed = vec![(crate::localization::text(if input { "no input" } else { "no output" }).to_string(), "none".to_string())];
|
||||
if input {
|
||||
fixed.extend((1..=8).map(|i| (format!("In {i}"), format!("In {i}"))));
|
||||
fixed.extend((1..=8).map(|i| (crate::localized_format!("In {}", i), format!("In {i}"))));
|
||||
} else {
|
||||
fixed.push((main_name, "main".to_string()));
|
||||
}
|
||||
@@ -58,7 +58,7 @@ fn route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, input: bool) {
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
ui.strong("Bus");
|
||||
ui.strong(crate::localization::text("Bus"));
|
||||
if let Some(bus) = search
|
||||
.rows(ui, busses.len(), 420.0, |ui, i, highlighted| busses.get(i).is_some_and(|b| menu_row(ui, highlighted, b)))
|
||||
.and_then(|i| busses.get(i))
|
||||
@@ -66,7 +66,7 @@ fn route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, input: bool) {
|
||||
let _ = app.run(cmd, json!({"track": id.0, key: bus}));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("new bus...").clicked() {
|
||||
if ui.button(crate::localization::text("new bus...")).clicked() {
|
||||
let mut n = busses.len() + 1;
|
||||
while busses.contains(&format!("Bus {n}")) || app.engine.session().track_by_name(&format!("Bus {n}")).is_some() {
|
||||
n += 1;
|
||||
|
||||
@@ -18,8 +18,9 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
|
||||
let level_r = if compact { r } else { level_icon(r).expand2(vec2(3.0, 0.0)).with_min_y(r.min.y).with_max_y(r.max.y) };
|
||||
let route_r = Rect::from_min_max(r.min, pos2((level_r.min.x - 1.0).max(r.min.x), r.max.y));
|
||||
let route_resp = ui.interact(if snd.is_some() { route_r } else { r }, ui.scope_id().with(("snd-route", id.0, slot)), Sense::click());
|
||||
route_resp
|
||||
.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Send {} for {}", (b'A' + slot as u8) as char, track.name)));
|
||||
route_resp.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localized_format!("Send {} for {}", (b'A' + slot as u8) as char, track.name))
|
||||
});
|
||||
let mark = if compact { Mark::Arrow } else { Mark::Letter((b'a' + slot as u8) as char) };
|
||||
match &snd {
|
||||
Some(s) => {
|
||||
@@ -30,7 +31,13 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
|
||||
let which = (b'A' + slot as u8) as char;
|
||||
let shown = app.ui.send_window == Some((id, slot));
|
||||
let level_resp = ui.interact(level_r, ui.scope_id().with(("send-value", id.0, slot)), Sense::click_and_drag());
|
||||
level_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Send {which} level for {}", track.name)));
|
||||
level_resp.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::Role::Button,
|
||||
true,
|
||||
crate::localized_format!("Send {which} level for {track}", which = which, track = track.name),
|
||||
)
|
||||
});
|
||||
if shown {
|
||||
ui.painter().rect_stroke(level_r.shrink(0.5), 1.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
|
||||
}
|
||||
@@ -50,9 +57,11 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
|
||||
let _ =
|
||||
app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "db": db}), &format!("send:{}:{slot}", id.0));
|
||||
}
|
||||
let _ = level_resp.clone().on_hover_text(format!(
|
||||
"Send {which} to {name}: {} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options",
|
||||
db_text(s.level_db)
|
||||
let _ = level_resp.clone().on_hover_text(crate::localized_format!(
|
||||
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options",
|
||||
which = which,
|
||||
name = name,
|
||||
db = db_text(s.level_db)
|
||||
));
|
||||
level_resp.context_menu(|ui| send_options_menu(app, ui, id, slot, s));
|
||||
}
|
||||
@@ -86,7 +95,7 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
};
|
||||
let t = Tokens::current();
|
||||
let mut open = true;
|
||||
egui::Window::new(format!("{name} · Send {}", (b'A' + slot as u8) as char))
|
||||
egui::Window::new(crate::localized_format!("{name} · Send {letter}", name = name, letter = (b'A' + slot as u8) as char))
|
||||
.id(egui::Id::unique("send_window"))
|
||||
.open(&mut open)
|
||||
.auto_sized()
|
||||
@@ -117,7 +126,7 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
ui.label(egui::RichText::new(pan_text(send.pan)).color(t.counter_text).small());
|
||||
let (fr, fresp) = ui.allocate_exact_size(vec2(56.0, 220.0), Sense::hover());
|
||||
fresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, true, "Send level"));
|
||||
fresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, true, crate::localization::text("Send level")));
|
||||
// Distinct from the strip's "Send A level for <track>" icon and from the slot's "Send level", so a
|
||||
// label query while the window is open still picks one node.
|
||||
if let Some(db) = fader(ui, fr, send.level_db, ui.scope_id().with("send_fader"), "Send level fader") {
|
||||
@@ -136,7 +145,7 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
rr,
|
||||
ui.scope_id().with("send_level_value"),
|
||||
Readout {
|
||||
name: &format!("{name} send level"),
|
||||
name: &crate::localized_format!("{name} send level", name = name),
|
||||
display: &shown,
|
||||
edit_initial: &format!("{:.1}", send.level_db),
|
||||
parse: parse_db,
|
||||
@@ -156,9 +165,9 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
/// Secondary controls live behind the amount readout, separate from the bus selector like Logic.
|
||||
fn send_options_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, send: &soundcraft_model::SendSlot) {
|
||||
ui.set_min_width(230.0);
|
||||
ui.strong(format!("Send {} · {}", (b'A' + slot as u8) as char, route_name(app, &send.target)));
|
||||
ui.strong(crate::localized_format!("Send {} · {}", (b'A' + slot as u8) as char, route_name(app, &send.target)));
|
||||
let mut db = send.level_db.max(-60.0);
|
||||
if ui.add(egui::Slider::new(&mut db, -60.0..=12.0).text("Level").suffix(" dB")).changed() {
|
||||
if ui.add(egui::Slider::new(&mut db, -60.0..=12.0).text(crate::localization::text("Level")).suffix(" dB")).changed() {
|
||||
let _ = app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "db": db}), &format!("send:{}:{slot}", id.0));
|
||||
}
|
||||
send_level_scale(ui, send.level_db);
|
||||
@@ -169,31 +178,31 @@ fn send_options_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize,
|
||||
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": db}));
|
||||
}
|
||||
}
|
||||
if ui.small_button("0 dB").clicked() {
|
||||
if ui.small_button(crate::localization::text("0 dB")).clicked() {
|
||||
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": 0.0}));
|
||||
}
|
||||
if ui.small_button("−∞").clicked() {
|
||||
if ui.small_button(crate::localization::text("−∞")).clicked() {
|
||||
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": -144.0}));
|
||||
}
|
||||
});
|
||||
let mut pan = send.pan;
|
||||
if ui.add(egui::Slider::new(&mut pan, -1.0..=1.0).text("Pan")).changed() {
|
||||
if ui.add(egui::Slider::new(&mut pan, -1.0..=1.0).text(crate::localization::text("Pan"))).changed() {
|
||||
let _ = app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "pan": pan}), &format!("send-pan:{}:{slot}", id.0));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let mut mute = send.mute;
|
||||
if crate::widgets::checkbox(ui, &mut mute, "Mute").changed() {
|
||||
if crate::widgets::checkbox(ui, &mut mute, crate::localization::text("Mute")).changed() {
|
||||
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "mute": mute}));
|
||||
}
|
||||
let mut pre = send.pre_fader;
|
||||
if crate::widgets::checkbox(ui, &mut pre, "Pre-fader").changed() {
|
||||
if crate::widgets::checkbox(ui, &mut pre, crate::localization::text("Pre-fader")).changed() {
|
||||
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "pre_fader": pre}));
|
||||
}
|
||||
});
|
||||
if let Route::Bus(bus) = send.target
|
||||
&& let Some(aux) =
|
||||
app.engine.session().tracks.iter().find(|t| t.kind == TrackKind::Aux && t.mixer.input == Route::Bus(bus)).map(|t| (t.id, t.name.clone()))
|
||||
&& ui.button("Rename bus…").clicked()
|
||||
&& ui.button(crate::localization::text("Rename bus…")).clicked()
|
||||
{
|
||||
app.dialogs.open_rename_track(aux.0, &aux.1);
|
||||
ui.close();
|
||||
@@ -342,18 +351,18 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
match ¤t {
|
||||
Some((_, name)) => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.strong(format!("Send {which}"));
|
||||
ui.strong(crate::localized_format!("Send {which}", which = which));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(egui::RichText::new(name).color(Tokens::current().counter_text));
|
||||
});
|
||||
});
|
||||
ui.label(egui::RichText::new("DESTINATION").size(8.0).color(Tokens::current().text_dim));
|
||||
ui.label(egui::RichText::new(crate::localization::text("DESTINATION")).size(8.0).color(Tokens::current().text_dim));
|
||||
}
|
||||
None => {
|
||||
ui.strong(format!("Send {which} · Choose destination"));
|
||||
ui.strong(crate::localized_format!("Send {which} · Choose destination", which = which));
|
||||
}
|
||||
}
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("send-bus-search", id.0, slot)), "Search buses…");
|
||||
let search = MenuSearch::show(ui, egui::Id::unique(("send-bus-search", id.0, slot)), crate::localization::text("Search buses…"));
|
||||
let busses = &app.engine.session().busses;
|
||||
let visible: Vec<_> = busses.iter().filter(|bus| search.matches(&bus.name)).collect();
|
||||
(search, visible)
|
||||
@@ -376,11 +385,11 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
})
|
||||
},
|
||||
|ui| {
|
||||
if ui.button("new bus...").clicked() {
|
||||
if ui.button(crate::localization::text("new bus...")).clicked() {
|
||||
ui.close();
|
||||
return Some(SendFooter::NewBus);
|
||||
}
|
||||
if has_send && ui.button("Remove send").clicked() {
|
||||
if has_send && ui.button(crate::localization::text("Remove send")).clicked() {
|
||||
ui.close();
|
||||
return Some(SendFooter::RemoveSend);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ pub(crate) fn instrument_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, r:
|
||||
let ins = track.instrument.as_ref();
|
||||
let info = ins.and_then(|i| plugin_info(&i.plugin));
|
||||
let resp = ui.interact(r, ui.scope_id().with(("instrument", id.0)), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Instrument for {}", track.name)));
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localized_format!("Instrument for {}", track.name)));
|
||||
match info {
|
||||
Some(info) => used_slot(ui.painter(), r, t.slot_face, Mark::Dot, info.short_name, t.text, None),
|
||||
None => empty_slot(ui.painter(), r, resp.hovered(), Mark::Dot),
|
||||
@@ -19,7 +19,8 @@ pub(crate) fn instrument_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, r:
|
||||
if resp.clicked() && hosted && !app.ui.plugin_windows.contains(&(id, slot)) {
|
||||
app.ui.plugin_windows.push((id, slot));
|
||||
}
|
||||
let menu_resp = if hosted { resp.clone().on_hover_text("Click: open instrument · right-click: change") } else { resp.clone() };
|
||||
let menu_resp =
|
||||
if hosted { resp.clone().on_hover_text(crate::localization::text("Click: open instrument · right-click: change")) } else { resp.clone() };
|
||||
let popup = if hosted { egui::Popup::context_menu(&menu_resp) } else { egui::Popup::menu(&menu_resp) };
|
||||
let popup = popup.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
|
||||
popup.show(|ui| instrument_menu(app, ui, id));
|
||||
@@ -103,7 +104,9 @@ pub(crate) fn insert_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot:
|
||||
let id = track.id;
|
||||
let ins = track.mixer.inserts.get(slot).cloned().flatten();
|
||||
let resp = ui.interact(r, ui.scope_id().with(("ins", id.0, slot)), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Insert {} for {}", (b'A' + slot as u8) as char, track.name)));
|
||||
resp.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localized_format!("Insert {} for {}", (b'A' + slot as u8) as char, track.name))
|
||||
});
|
||||
let info = ins.as_ref().and_then(|i| plugin_info(&i.plugin));
|
||||
let name = ins.as_ref().map(|i| info.map_or(i.plugin.as_str(), |p| p.short_name)).unwrap_or_default();
|
||||
match &ins {
|
||||
|
||||
@@ -65,19 +65,30 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let t = Tokens::current();
|
||||
let mut run: Option<String> = None;
|
||||
let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
|
||||
egui::Window::new("Search")
|
||||
egui::Window::new(crate::localization::text("Search"))
|
||||
.id(egui::Id::unique("Search"))
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.title_bar(false)
|
||||
.anchor(Align2::CENTER_TOP, vec2(0.0, 90.0))
|
||||
.fixed_size(vec2(560.0, 380.0))
|
||||
.show(ctx, |ui| {
|
||||
let r = ui
|
||||
.add(egui::TextEdit::singleline(&mut app.palette.query).hint_text("Search commands…").desired_width(f32::INFINITY).font(mono(15.0)));
|
||||
let r = ui.add(
|
||||
egui::TextEdit::singleline(&mut app.palette.query)
|
||||
.hint_text(crate::localization::text("Search commands…"))
|
||||
.desired_width(f32::INFINITY)
|
||||
.font(mono(15.0)),
|
||||
);
|
||||
r.request_focus();
|
||||
let q = app.palette.query.trim().to_string();
|
||||
let mut hits: Vec<(i32, Entry)> =
|
||||
entries().into_iter().filter_map(|e| score(&format!("{} {} {}", e.label, e.path, e.id), &q).map(|s| (s, e))).collect();
|
||||
let mut hits: Vec<(i32, Entry)> = entries()
|
||||
.into_iter()
|
||||
.filter_map(|e| {
|
||||
let label = crate::localization::text(&e.label);
|
||||
let path = e.path.split(" › ").map(crate::localization::text).collect::<Vec<_>>().join(" › ");
|
||||
score(&format!("{label} {path} {} {} {}", e.label, e.path, e.id), &q).map(|s| (s, e))
|
||||
})
|
||||
.collect();
|
||||
hits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.label.cmp(&b.1.label)));
|
||||
hits.truncate(14);
|
||||
let (down, up, enter) = ctx.input(|i| (i.key_pressed(Key::ArrowDown), i.key_pressed(Key::ArrowUp), i.key_pressed(Key::Enter)));
|
||||
@@ -92,10 +103,11 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
for (i, (_, e)) in hits.iter().enumerate() {
|
||||
let sel = i == app.palette.selected;
|
||||
let resp = ui.horizontal(|ui| {
|
||||
let l = ui.selectable_label(sel, &e.label);
|
||||
ui.label(egui::RichText::new(&e.path).small().color(t.text_dim));
|
||||
let l = ui.selectable_label(sel, crate::localization::text(&e.label));
|
||||
let path = e.path.split(" › ").map(crate::localization::text).collect::<Vec<_>>().join(" › ");
|
||||
ui.label(egui::RichText::new(path).small().color(t.text_dim));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let sc = crate::shortcuts::shortcut_label(&e.shortcut, ctx.os().is_mac());
|
||||
let sc = crate::shortcuts::display_shortcut(&e.shortcut, ctx.os().is_mac());
|
||||
ui.label(egui::RichText::new(sc).font(mono(10.0)).color(t.text_dim));
|
||||
});
|
||||
l
|
||||
|
||||
@@ -33,7 +33,7 @@ fn panel_header(ui: &mut Ui, title: &str) {
|
||||
let t = Tokens::current();
|
||||
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::hover());
|
||||
ui.painter().rect_filled(r, 0.0, t.panel_bg2);
|
||||
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, title, bold(11.5), t.header_text);
|
||||
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, crate::localization::text(title), bold(11.5), t.header_text);
|
||||
ui.painter().line_segment([pos2(r.min.x, r.max.y), pos2(r.max.x, r.max.y)], Stroke::new(1.0, t.border));
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ pub fn floating(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
big_counter(app, ctx);
|
||||
plugin_windows(app, ctx);
|
||||
crate::mix_window::send_window(app, ctx);
|
||||
crate::mix_window::output_window(app, ctx);
|
||||
about(app, ctx);
|
||||
session_info(app, ctx);
|
||||
}
|
||||
|
||||
@@ -7,30 +7,35 @@ 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(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"]) {
|
||||
if ui.selectable_label(tab == i, l).clicked() {
|
||||
tab = i;
|
||||
egui::Window::new(crate::localization::text("About SoundCraft"))
|
||||
.id(egui::Id::unique("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"]) {
|
||||
if ui.selectable_label(tab == i, crate::localization::text(l)).clicked() {
|
||||
tab = i;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(tab_id, tab));
|
||||
ui.separator();
|
||||
match tab {
|
||||
1 => crate::credits::contributors_ui(ui),
|
||||
2 => crate::credits::models_ui(ui),
|
||||
_ => {
|
||||
ui.label(egui::RichText::new(crate::localization::text("SoundCraft")).font(bold(22.0)));
|
||||
ui.label(crate::localized_format!("Version {}", env!("CARGO_PKG_VERSION")));
|
||||
ui.label(crate::localization::text("An open-source digital audio workstation from the ArtCraft team."));
|
||||
ui.label(crate::localization::text("Dual-licensed MIT OR Apache-2.0. Made with Rust and egui."));
|
||||
ui.hyperlink_to("getartcraft.com/apps/soundcraft", "https://getartcraft.com/apps/soundcraft");
|
||||
ui.hyperlink_to(crate::localization::text("Join us on Discord"), "https://discord.gg/artcraft");
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(tab_id, tab));
|
||||
ui.separator();
|
||||
match tab {
|
||||
1 => crate::credits::contributors_ui(ui),
|
||||
2 => crate::credits::models_ui(ui),
|
||||
_ => {
|
||||
ui.label(egui::RichText::new("SoundCraft").font(bold(22.0)));
|
||||
ui.label(format!("Version {}", env!("CARGO_PKG_VERSION")));
|
||||
ui.label("An open-source digital audio workstation from the ArtCraft team.");
|
||||
ui.label("Dual-licensed MIT OR Apache-2.0. Made with Rust and egui.");
|
||||
ui.hyperlink_to("getartcraft.com/apps/soundcraft", "https://getartcraft.com/apps/soundcraft");
|
||||
ui.hyperlink_to("Join us on Discord", "https://discord.gg/artcraft");
|
||||
}
|
||||
}
|
||||
});
|
||||
app.ui.show_about = open;
|
||||
}
|
||||
|
||||
@@ -39,11 +44,15 @@ pub(super) fn session_info(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Session Info").open(&mut open).default_size(vec2(480.0, 360.0)).show(ctx, |ui| {
|
||||
let text = soundcraft_engine::inspect::session_text(&app.engine);
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
ui.label(egui::RichText::new(text).font(mono(11.0)));
|
||||
egui::Window::new(crate::localization::text("Session Info"))
|
||||
.id(egui::Id::unique("Session Info"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(480.0, 360.0))
|
||||
.show(ctx, |ui| {
|
||||
let text = soundcraft_engine::inspect::session_text(&app.engine);
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
ui.label(egui::RichText::new(text).font(mono(11.0)));
|
||||
});
|
||||
});
|
||||
});
|
||||
app.ui.show_session_info = open;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn clip_list(app: &mut SoundApp, ui: &mut Ui) {
|
||||
panel_header(ui, "CLIPS");
|
||||
let fkey = egui::Id::unique("clip_filter");
|
||||
let mut filter: String = ui.ctx().memory(|m| m.data.get_temp(fkey)).unwrap_or_default();
|
||||
ui.add(egui::TextEdit::singleline(&mut filter).hint_text("🔍 Find clips").desired_width(f32::INFINITY));
|
||||
ui.add(egui::TextEdit::singleline(&mut filter).hint_text(crate::localization::text("🔍 Find clips")).desired_width(f32::INFINITY));
|
||||
ui.ctx().memory_mut(|m| m.data.insert_temp(fkey, filter.clone()));
|
||||
let needle = filter.to_lowercase();
|
||||
let rkey = egui::Id::unique("clip_rows");
|
||||
@@ -73,26 +73,26 @@ pub fn clip_list(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), if whole { Sense::click_and_drag() } else { Sense::click() });
|
||||
resp.context_menu(|ui| {
|
||||
if whole {
|
||||
if ui.button("Place on New Track").clicked() {
|
||||
if ui.button(crate::localization::text("Place on New Track")).clicked() {
|
||||
let _ = app.run("clip.place_source", json!({"source": id}));
|
||||
ui.close();
|
||||
}
|
||||
let sel_track = app.engine.session().edit.selected_tracks.first().map(|t| t.0);
|
||||
if let Some(t) = sel_track
|
||||
&& ui.button("Place on Selected Track").clicked()
|
||||
&& ui.button(crate::localization::text("Place on Selected Track")).clicked()
|
||||
{
|
||||
let _ = app.run("clip.place_source", json!({"source": id, "track": t}));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
if !whole && ui.button("Auto Rename…").clicked() {
|
||||
if !whole && ui.button(crate::localization::text("Auto Rename…")).clicked() {
|
||||
// The selected clips when the row is one of them, otherwise the row's clip.
|
||||
let clips = if selected { app.engine.session().edit.selected_clips.clone() } else { vec![ClipId(id)] };
|
||||
app.dialogs.open_auto_rename(&app.engine, clips);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Clear…").clicked() {
|
||||
if ui.button(crate::localization::text("Clear…")).clicked() {
|
||||
let (clips, sources) = if whole { (vec![], vec![SourceId(id)]) } else { (vec![ClipId(id)], vec![]) };
|
||||
app.dialogs.open_clear(&app.engine, clips, sources);
|
||||
ui.close();
|
||||
|
||||
@@ -105,10 +105,13 @@ fn renderer(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
(tr.name.clone(), sp.x, sp.y, sp.z)
|
||||
})
|
||||
.collect();
|
||||
egui::Window::new(egui::RichText::new("Renderer").font(bold(13.0))).open(&mut open).default_size(vec2(380.0, 440.0)).resizable(true).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
ui.label(egui::RichText::new(format!("Main output: {}", fmt.label())).font(regular(11.0)).color(t.text));
|
||||
egui::Window::new(egui::RichText::new(crate::localization::text("Renderer")).font(bold(13.0)))
|
||||
.id(egui::Id::unique("Renderer"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(380.0, 440.0))
|
||||
.resizable(true)
|
||||
.show(ctx, |ui| {
|
||||
ui.label(egui::RichText::new(crate::localized_format!("Main output: {}", fmt.label())).font(regular(11.0)).color(t.text));
|
||||
let side = ui.available_width().min(360.0);
|
||||
let (r, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
|
||||
let p = ui.painter_at(r);
|
||||
@@ -117,7 +120,7 @@ fn renderer(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let rad = side * 0.40;
|
||||
p.circle_stroke(c, rad, Stroke::new(1.0, Color32::from_rgb(60, 68, 78)));
|
||||
p.circle_stroke(c, rad * 0.55, Stroke::new(1.0, Color32::from_rgb(44, 50, 58)));
|
||||
p.text(pos2(c.x, r.min.y + 8.0), Align2::CENTER_TOP, "front", regular(9.0), t.text_dim);
|
||||
p.text(pos2(c.x, r.min.y + 8.0), Align2::CENTER_TOP, crate::localization::text("front"), regular(9.0), t.text_dim);
|
||||
for (i, sp) in fmt.speakers().iter().enumerate() {
|
||||
let level = peaks.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
let ring = if sp.is_height() { rad * 0.55 } else { rad };
|
||||
@@ -136,27 +139,32 @@ fn renderer(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.add_space(4.0);
|
||||
if objects.is_empty() {
|
||||
ui.label(
|
||||
egui::RichText::new("No object tracks. Use the Object view in the Mix window to route tracks as objects.")
|
||||
.small()
|
||||
.color(t.text_dim),
|
||||
egui::RichText::new(crate::localization::text(
|
||||
"No object tracks. Use the Object view in the Mix window to route tracks as objects.",
|
||||
))
|
||||
.small()
|
||||
.color(t.text_dim),
|
||||
);
|
||||
} else {
|
||||
ui.label(egui::RichText::new(format!("{} object track(s)", objects.len())).small().color(t.text_dim));
|
||||
ui.label(egui::RichText::new(crate::localized_format!("{} object track(s)", objects.len())).small().color(t.text_dim));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
app.extra.show_renderer = open;
|
||||
}
|
||||
|
||||
/// Appearance window: interface scale, reduce-motion, theme, auto-update configuration and Reset.
|
||||
/// Appearance window: interface scale, reduce visual effects, theme, language, auto-update configuration and Reset.
|
||||
fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.extra.show_ui_customization;
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new(egui::RichText::new("Appearance").font(bold(13.0))).open(&mut open).default_size(vec2(320.0, 180.0)).resizable(false).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
let language = app.ui.language;
|
||||
egui::Window::new(egui::RichText::new(crate::localization::text("Appearance")).font(bold(13.0)))
|
||||
.id(egui::Id::unique("Appearance"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(320.0, 210.0))
|
||||
.resizable(false)
|
||||
.show(ctx, |ui| {
|
||||
// Each control carries its own visible label, which is also its accessible name. A
|
||||
// label in a neighbouring grid cell is only painted text: a screen reader (and the
|
||||
// kittest accessibility check) would see an unnamed slider, checkbox or combo box.
|
||||
@@ -164,38 +172,54 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
egui::Slider::new(&mut app.extra.ui_scale, 0.75..=1.5)
|
||||
.step_by(0.05)
|
||||
.custom_formatter(|v, _| format!("{:.0} %", v * 100.0))
|
||||
.text("Interface scale"),
|
||||
.text(crate::localization::text("Interface scale")),
|
||||
);
|
||||
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);
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Reduce visual effects"))
|
||||
.selected_text(crate::localization::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, crate::localization::text(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 {
|
||||
if ui.selectable_label(app.ui.theme == mode, mode.label()).clicked() {
|
||||
chosen = Some(mode);
|
||||
let mut selected_language = None;
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Language"))
|
||||
.selected_text(crate::localization::text(language.native_name()))
|
||||
.show_ui(ui, |ui| {
|
||||
for choice in crate::localization::Language::ALL {
|
||||
if ui.selectable_label(language == choice, crate::localization::text(choice.native_name())).clicked() {
|
||||
selected_language = Some(choice);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(choice) = selected_language {
|
||||
let _ = app.run("ui.language", json!({"language": choice.id()}));
|
||||
}
|
||||
let mut chosen = None;
|
||||
craft_ui::ComboBox::from_label(crate::localization::text("Theme"))
|
||||
.selected_text(crate::localization::text(app.ui.theme.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for mode in crate::theme::ThemeMode::ALL {
|
||||
if ui.selectable_label(app.ui.theme == mode, crate::localization::text(mode.label())).clicked() {
|
||||
chosen = Some(mode);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(mode) = chosen {
|
||||
let _ = app.run("ui.theme", json!({"mode": mode.id()}));
|
||||
}
|
||||
crate::widgets::checkbox(ui, &mut app.extra.auto_update_config, "Auto-update configuration");
|
||||
crate::widgets::checkbox(ui, &mut app.extra.auto_update_config, crate::localization::text("Auto-update configuration"));
|
||||
ui.add_space(4.0);
|
||||
if ui.button("Reset").clicked() {
|
||||
if ui.button(crate::localization::text("Reset")).clicked() {
|
||||
app.extra.ui_scale = 1.0;
|
||||
let _ = app.run("ui.reduce_visual_effects", json!({"mode": "never"}));
|
||||
let _ = app.run("ui.theme", json!({"mode": crate::theme::ThemeMode::default().id()}));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
app.extra.show_ui_customization = open;
|
||||
}
|
||||
|
||||
@@ -5,14 +5,18 @@ pub(crate) fn undo_history(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let n = hist.len();
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
for (i, h) in hist.iter().enumerate() {
|
||||
if ui.selectable_label(i + 1 == n, format!("{} {h}", i + 1)).clicked() {
|
||||
if ui.selectable_label(i + 1 == n, format!("{} {}", i + 1, crate::localization::text(h))).clicked() {
|
||||
for _ in 0..(n - i - 1) {
|
||||
let _ = app.run("edit.undo", json!({}));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(r) = app.engine.redo_label() {
|
||||
ui.label(egui::RichText::new(format!("(redo) {r}")).italics().color(Tokens::current().text_dim));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localized_format!("(redo) {r}", r = crate::localization::text(r)))
|
||||
.italics()
|
||||
.color(Tokens::current().text_dim),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ use super::{SoundApp, Ui, json, mono};
|
||||
|
||||
/// One recallable memory-location row: number button, editable name, time, length, kind and delete.
|
||||
fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc: &str, len: &str, kind: &str) {
|
||||
if ui.button(n.to_string()).on_hover_text("Recall").clicked() {
|
||||
if ui.button(n.to_string()).on_hover_text(crate::localization::text("Recall")).clicked() {
|
||||
let _ = app.run("markers.recall", json!({"number": n}));
|
||||
}
|
||||
let key = egui::Id::unique(("mem_name", n));
|
||||
let mut edit: String = ui.ctx().memory(|m| m.data.get_temp(key)).unwrap_or_else(|| name.to_string());
|
||||
let r = crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(&mut edit).desired_width(140.0)), "Name");
|
||||
let r = crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(&mut edit).desired_width(140.0)), crate::localization::text("Name"));
|
||||
if r.changed() {
|
||||
ui.ctx().memory_mut(|m| m.data.insert_temp(key, edit.clone()));
|
||||
}
|
||||
@@ -17,7 +17,7 @@ fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc:
|
||||
}
|
||||
ui.label(egui::RichText::new(loc).font(mono(11.0)));
|
||||
ui.label(egui::RichText::new(len).font(mono(11.0)));
|
||||
ui.label(kind);
|
||||
ui.label(crate::localization::text(kind));
|
||||
if crate::widgets::close_button(ui, "Delete marker").clicked() {
|
||||
let _ = app.run("markers.delete", json!({"number": n}));
|
||||
}
|
||||
@@ -26,10 +26,10 @@ fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc:
|
||||
|
||||
pub(crate) fn memory_locations(app: &mut SoundApp, ui: &mut Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("+ Marker").clicked() {
|
||||
if ui.button(crate::localization::text("+ Marker")).clicked() {
|
||||
let _ = app.run("markers.add", json!({}));
|
||||
}
|
||||
if ui.button("+ Selection").clicked() {
|
||||
if ui.button(crate::localization::text("+ Selection")).clicked() {
|
||||
let _ = app.run("markers.add", json!({"kind": "selection"}));
|
||||
}
|
||||
});
|
||||
@@ -52,7 +52,7 @@ pub(crate) fn memory_locations(app: &mut SoundApp, ui: &mut Ui) {
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
egui::Grid::new("mem_grid").striped(true).num_columns(6).show(ui, |ui| {
|
||||
for h in ["#", "Name", "Location", "Length", "Type", ""] {
|
||||
ui.label(egui::RichText::new(h).strong());
|
||||
ui.label(egui::RichText::new(crate::localization::text(h)).strong());
|
||||
}
|
||||
ui.end_row();
|
||||
for (n, name, loc, len, kind) in &rows {
|
||||
|
||||
@@ -122,7 +122,13 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) {
|
||||
ui.painter().rect_filled(full, 0.0, t.panel_bg);
|
||||
let header = Rect::from_min_size(full.min, vec2(full.width(), 22.0));
|
||||
ui.painter().rect_filled(header, 0.0, t.panel_bg2);
|
||||
ui.painter().text(pos2(header.min.x + 8.0, header.center().y), Align2::LEFT_CENTER, "MIDI EDITOR", bold(11.5), t.header_text);
|
||||
ui.painter().text(
|
||||
pos2(header.min.x + 8.0, header.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
crate::localization::text("MIDI EDITOR"),
|
||||
bold(11.5),
|
||||
t.header_text,
|
||||
);
|
||||
let Some(cid) = target_clip(app) else {
|
||||
empty_state(app, ui, full, header);
|
||||
return;
|
||||
@@ -184,8 +190,8 @@ fn empty_state(app: &mut SoundApp, ui: &mut Ui, full: Rect, header: Rect) {
|
||||
s.tracks.iter().find(|t| t.kind.is_midi() && s.edit.selected_tracks.contains(&t.id)).map(|t| (t.id, t.name.clone()))
|
||||
};
|
||||
let msg = match &track {
|
||||
Some((_, name)) => format!("Click to add a MIDI clip to {name} at the insertion point."),
|
||||
None => "Select a MIDI clip (or a MIDI track) to edit its notes.".into(),
|
||||
Some((_, name)) => crate::localized_format!("Click to add a MIDI clip to {name} at the insertion point.", name = name),
|
||||
None => crate::localization::text("Select a MIDI clip (or a MIDI track) to edit its notes.").into(),
|
||||
};
|
||||
ui.painter().text(full.center(), Align2::CENTER_CENTER, msg, regular(13.0), t.text_dim);
|
||||
let body = Rect::from_min_max(pos2(full.min.x, header.max.y), full.max);
|
||||
@@ -223,16 +229,16 @@ fn midi_toolbar(app: &mut SoundApp, ui: &mut Ui, header: Rect, cid: ClipId, grid
|
||||
let mut tb = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
tb.spacing_mut().item_spacing.x = 4.0;
|
||||
let mut op: Option<(&str, serde_json::Value)> = None;
|
||||
if tb.small_button("Legato").clicked() {
|
||||
if tb.small_button(crate::localization::text("Legato")).clicked() {
|
||||
op = Some(("event.change_duration", json!({"legato": 0})));
|
||||
}
|
||||
if tb.small_button("Vel −10").clicked() {
|
||||
if tb.small_button(crate::localization::text("Vel −10")).clicked() {
|
||||
op = Some(("event.change_velocity", json!({"add": -10})));
|
||||
}
|
||||
if tb.small_button("Vel +10").clicked() {
|
||||
if tb.small_button(crate::localization::text("Vel +10")).clicked() {
|
||||
op = Some(("event.change_velocity", json!({"add": 10})));
|
||||
}
|
||||
if tb.small_button("Quantize").on_hover_text("Quantize to the grid").clicked() {
|
||||
if tb.small_button(crate::localization::text("Quantize")).on_hover_text(crate::localization::text("Quantize to the grid")).clicked() {
|
||||
op = Some(("event.quantize", json!({"grid": grid_ticks, "strength": 100})));
|
||||
}
|
||||
if let Some((id, mut p)) = op {
|
||||
@@ -477,7 +483,7 @@ fn velocity_lane(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId, bas
|
||||
let t = Tokens::current();
|
||||
// Velocity lane.
|
||||
ui.painter().rect_filled(vel, 0.0, Color32::from_rgb(28, 28, 30));
|
||||
ui.painter().text(pos2(label_x, vel.center().y), Align2::LEFT_CENTER, "Velocity", regular(10.0), t.text_dim);
|
||||
ui.painter().text(pos2(label_x, vel.center().y), Align2::LEFT_CENTER, crate::localization::text("Velocity"), regular(10.0), t.text_dim);
|
||||
let vresp = ui.interact(vel, ui.scope_id().with(("vel", cid.0)), Sense::click_and_drag());
|
||||
for (i, n) in sequence.notes.iter().enumerate() {
|
||||
let x = g.x_of(n.start);
|
||||
|
||||
@@ -26,33 +26,39 @@ pub(super) fn plugin_windows(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// Bypass and presets act on insert slots.
|
||||
if !instrument {
|
||||
ui.label(egui::RichText::new(&ins.preset).color(Tokens::current().text_dim));
|
||||
let label = if ins.bypass { "BYPASSED" } else { "Bypass" };
|
||||
let label = crate::localization::text(if ins.bypass { "BYPASSED" } else { "Bypass" });
|
||||
if ui.button(label).clicked() {
|
||||
let _ = app.run("mix.insert_bypass", json!({"track": tid.0, "slot": slot}));
|
||||
}
|
||||
ui.menu_button("Presets v", |ui| preset_menu(app, ui, tid, slot, info, &ins));
|
||||
ui.menu_button(crate::localization::text("Presets v"), |ui| preset_menu(app, ui, tid, slot, info, &ins));
|
||||
}
|
||||
if soundcraft_mix::is_third_party(&ins.plugin) {
|
||||
let open = app.player.as_ref().is_some_and(|p| p.editor_open(tid, slot));
|
||||
let available = app.player.as_ref().is_some_and(|p| p.has_editor(tid, slot));
|
||||
let label = if open { "Close Plugin Editor" } else { "Open Plugin Editor" };
|
||||
let label = crate::localization::text(if open { "Close Plugin Editor" } else { "Open Plugin Editor" });
|
||||
let resp = ui.add_enabled(available, egui::Button::new(label));
|
||||
let resp =
|
||||
if available { resp } else { resp.on_disabled_hover_text("This plugin has no editor of its own, or it is not loaded") };
|
||||
let resp = if available {
|
||||
resp
|
||||
} else {
|
||||
resp.on_disabled_hover_text(crate::localization::text("This plugin has no editor of its own, or it is not loaded"))
|
||||
};
|
||||
if resp.clicked()
|
||||
&& let Some(p) = &app.player
|
||||
{
|
||||
if open {
|
||||
p.close_editor(tid, slot);
|
||||
} else if let Err(e) = p.open_editor(tid, slot) {
|
||||
app.ui.status = format!("{}: {e}", info.name);
|
||||
app.ui.status = format!("{}: {}", info.name, crate::localization::error_text(&e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if instrument && soundcraft_mix::is_third_party(&ins.plugin) {
|
||||
// A hosted instrument keeps its sounds and settings in its own editor.
|
||||
ui.label(egui::RichText::new("Load and edit sounds in the plugin's own editor.").color(Tokens::current().text_dim));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text("Load and edit sounds in the plugin's own editor."))
|
||||
.color(Tokens::current().text_dim),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if instrument && ins.plugin == crate::sampler_window::SAMPLER {
|
||||
@@ -64,19 +70,23 @@ pub(super) fn plugin_windows(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
egui::Grid::new(("pg", tid.0, slot)).num_columns(3).show(ui, |ui| {
|
||||
// Built-in parameters are translated; a third-party plugin supplies its own names.
|
||||
let localize_params = !soundcraft_mix::is_third_party(&ins.plugin);
|
||||
for p in info.params {
|
||||
let v = ins.params.get(p.id).copied().unwrap_or(p.default);
|
||||
let label = ui.label(p.name);
|
||||
let label_text = if localize_params { crate::localization::text(p.name) } else { p.name };
|
||||
let label = ui.label(label_text);
|
||||
let mut x = v;
|
||||
let resp = if !p.choices.is_empty() {
|
||||
let mut idx = x.round().max(0.0) as usize;
|
||||
let r = craft_ui::ComboBox::from_id_salt(("pc", tid.0, slot, p.id))
|
||||
.selected_text(p.choices.get(idx).copied().unwrap_or("?"))
|
||||
.show_ui(ui, |ui| {
|
||||
for (i, c) in p.choices.iter().enumerate() {
|
||||
ui.selectable_value(&mut idx, i, *c);
|
||||
}
|
||||
});
|
||||
let selected = p.choices.get(idx).copied().unwrap_or("?");
|
||||
let selected_text = if localize_params { crate::localization::text(selected) } else { selected };
|
||||
let r = craft_ui::ComboBox::from_id_salt(("pc", tid.0, slot, p.id)).selected_text(selected_text).show_ui(ui, |ui| {
|
||||
for (i, c) in p.choices.iter().enumerate() {
|
||||
let choice_text = if localize_params { crate::localization::text(c) } else { c };
|
||||
ui.selectable_value(&mut idx, i, choice_text);
|
||||
}
|
||||
});
|
||||
x = idx as f32;
|
||||
if r.response.clicked() && ui.input(|i| i.modifiers.alt) {
|
||||
x = p.default;
|
||||
@@ -182,13 +192,13 @@ fn preset_menu(
|
||||
info: &soundcraft_dsp::PluginInfo,
|
||||
ins: &soundcraft_model::Insert,
|
||||
) {
|
||||
if ui.button("<factory default>").clicked() {
|
||||
if ui.button(crate::localization::text("<factory default>")).clicked() {
|
||||
let defaults: serde_json::Map<String, serde_json::Value> = info.params.iter().map(|p| (p.id.to_string(), json!(p.default))).collect();
|
||||
let _ = app.run("mix.insert_params", json!({"track": tid.0, "slot": slot, "params": defaults, "preset": "<factory default>"}));
|
||||
ui.close();
|
||||
}
|
||||
let Some(dir) = preset_dir(app, info.id) else {
|
||||
ui.label("User presets need the desktop app.");
|
||||
ui.label(crate::localization::text("User presets need the desktop app."));
|
||||
return;
|
||||
};
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir)
|
||||
@@ -218,12 +228,19 @@ fn preset_menu(
|
||||
let key = egui::Id::unique(("preset_name", tid.0, slot));
|
||||
let mut name: String = ui.ctx().memory(|m| m.data.get_temp(key)).unwrap_or_else(|| format!("{} preset", info.name));
|
||||
ui.horizontal(|ui| {
|
||||
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(&mut name).desired_width(140.0)), "Preset name");
|
||||
if ui.button("Save").clicked() {
|
||||
crate::widgets::named_text_field(
|
||||
ui.add(egui::TextEdit::singleline(&mut name).desired_width(140.0)),
|
||||
crate::localization::text("Preset name"),
|
||||
);
|
||||
if ui.button(crate::localization::text("Save")).clicked() {
|
||||
let clean = soundcraft_engine::io::sanitize_name(&name);
|
||||
let body = json!({"format": "soundcraft-plugin-preset", "plugin": info.id, "params": ins.params});
|
||||
let ok = std::fs::create_dir_all(&dir).is_ok() && std::fs::write(dir.join(format!("{clean}.json")), body.to_string()).is_ok();
|
||||
app.ui.status = if ok { format!("Saved preset {clean}") } else { "Could not save the preset".into() };
|
||||
app.ui.status = if ok {
|
||||
crate::localized_format!("Saved preset {clean}", clean = clean)
|
||||
} else {
|
||||
crate::localization::text("Could not save the preset").into()
|
||||
};
|
||||
if ok {
|
||||
let _ = app.run("mix.insert_params", json!({"track": tid.0, "slot": slot, "params": {}, "preset": clean}));
|
||||
}
|
||||
|
||||
@@ -122,9 +122,9 @@ impl SoundApp {
|
||||
self.ui.plugin_windows.push((track, soundcraft_mix::INSTRUMENT_SLOT));
|
||||
}
|
||||
let name = v.get("name").and_then(|n| n.as_str()).unwrap_or(what);
|
||||
self.ui.status = format!("{name} loaded into the sampler");
|
||||
self.ui.status = crate::localized_format!("{name} loaded into the sampler", name = name);
|
||||
}
|
||||
Err(e) => self.ui.status = format!("{what}: {e}"),
|
||||
Err(e) => self.ui.status = format!("{}: {}", what, crate::localization::error_text(&e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,8 +137,8 @@ pub fn sample_strip(app: &mut SoundApp, ui: &mut Ui, tid: TrackId, ins: &Insert)
|
||||
let audio = ins.sample.and_then(|id| s.pool.get(id)).cloned();
|
||||
ui.horizontal(|ui| {
|
||||
let can_pick = app.services.pick_open.is_some();
|
||||
let load = ui.add_enabled(can_pick, egui::Button::new("Load Sample…"));
|
||||
let load = if can_pick { load } else { load.on_disabled_hover_text("Drop an audio file on this window") };
|
||||
let load = ui.add_enabled(can_pick, egui::Button::new(crate::localization::text("Load Sample…")));
|
||||
let load = if can_pick { load } else { load.on_disabled_hover_text(crate::localization::text("Drop an audio file on this window")) };
|
||||
if load.clicked()
|
||||
&& let Some(pick) = &app.services.pick_open
|
||||
&& let Some(path) = pick("mix.sampler_load", craft_audio::DECODE_EXTENSIONS)
|
||||
@@ -147,10 +147,10 @@ pub fn sample_strip(app: &mut SoundApp, ui: &mut Ui, tid: TrackId, ins: &Insert)
|
||||
Ok(path) => {
|
||||
let _ = app.run("mix.sampler_load", json!({"track": tid.0, "path": path}));
|
||||
}
|
||||
Err(e) => app.ui.status = e.to_string(),
|
||||
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
}
|
||||
}
|
||||
if ins.sample.is_some() && ui.button("Clear").clicked() {
|
||||
if ins.sample.is_some() && ui.button(crate::localization::text("Clear")).clicked() {
|
||||
let _ = app.run("mix.sampler_clear", json!({"track": tid.0}));
|
||||
}
|
||||
});
|
||||
@@ -174,7 +174,7 @@ pub fn sample_strip(app: &mut SoundApp, ui: &mut Ui, tid: TrackId, ins: &Insert)
|
||||
p.rect_filled(r, 4.0, t.playlist_bg);
|
||||
p.rect_stroke(r, 4.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
|
||||
let Some(audio) = audio else {
|
||||
p.text(r.center(), Align2::CENTER_CENTER, "Drop an audio file here", regular(12.0), t.text_dim);
|
||||
p.text(r.center(), Align2::CENTER_CENTER, crate::localization::text("Drop an audio file here"), regular(12.0), t.text_dim);
|
||||
return;
|
||||
};
|
||||
let frames = audio.frames().max(1);
|
||||
|
||||
@@ -40,118 +40,125 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Score Editor").open(&mut open).default_size(vec2(900.0, 340.0)).show(ctx, |ui| {
|
||||
let Some(cid) = crate::midi_editor::target_clip(app) else {
|
||||
ui.label("Select a MIDI clip or MIDI track.");
|
||||
return;
|
||||
};
|
||||
let s = app.engine.session();
|
||||
let Some((tid, clip)) = s.find_clip(cid).map(|(t, c)| (t, c.clone())) else { return };
|
||||
let ClipContent::Midi { sequence } = &clip.content else { return };
|
||||
let title = s.track(tid).map_or(String::new(), |t| t.name.clone());
|
||||
ui.label(egui::RichText::new(format!("{title} — {}", clip.name)).font(bold(13.0)));
|
||||
let len_ticks = (s.tempo.samples_to_ticks(clip.end(), s.sample_rate) - s.tempo.samples_to_ticks(clip.start, s.sample_rate)).max(1);
|
||||
let px_per_tick = 0.07f32;
|
||||
let width = (len_ticks as f32 * px_per_tick + 120.0).max(ui.available_width());
|
||||
egui::ScrollArea::horizontal().show(ui, |ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(width, 230.0), Sense::hover());
|
||||
let p = ui.painter_at(r);
|
||||
p.rect_filled(r, 4.0, Color32::from_rgb(246, 243, 236));
|
||||
let ink = Color32::from_rgb(20, 20, 24);
|
||||
let left = r.min.x + 70.0;
|
||||
// Treble staff: E4..F5 (steps 2..10 above C4); bass: G2..A3 (steps -10..-2).
|
||||
let c4_y = r.min.y + 115.0;
|
||||
let y_of = |step: i32| c4_y - step as f32 * STEP;
|
||||
for line in [2, 4, 6, 8, 10, -2, -4, -6, -8, -10] {
|
||||
let y = y_of(line);
|
||||
p.line_segment([pos2(r.min.x + 10.0, y), pos2(r.max.x - 10.0, y)], Stroke::new(1.0, ink));
|
||||
}
|
||||
p.text(pos2(r.min.x + 22.0, y_of(6)), Align2::CENTER_CENTER, "𝄞", regular(36.0), ink);
|
||||
// Bass clef, drawn: a curl from the F line plus two dots around it.
|
||||
let f = pos2(r.min.x + 18.0, y_of(-4));
|
||||
let curl: Vec<Pos2> = (0..=20)
|
||||
.map(|i| {
|
||||
let a = -2.6 + i as f32 * 0.19;
|
||||
let rad = 7.0 + i as f32 * 0.35;
|
||||
pos2(f.x + a.cos() * rad * 0.9 + 2.0, f.y + a.sin() * rad + 4.0)
|
||||
})
|
||||
.collect();
|
||||
p.circle_filled(pos2(f.x - 4.0, f.y), 3.0, ink);
|
||||
p.add(Shape::line(curl, Stroke::new(2.2, ink)));
|
||||
p.circle_filled(pos2(f.x + 14.0, y_of(-3)), 1.8, ink);
|
||||
p.circle_filled(pos2(f.x + 14.0, y_of(-5)), 1.8, ink);
|
||||
p.line_segment([pos2(r.min.x + 10.0, y_of(10)), pos2(r.min.x + 10.0, y_of(-10))], Stroke::new(2.0, ink));
|
||||
// Bar lines.
|
||||
let base = s.tempo.samples_to_ticks(clip.start, s.sample_rate);
|
||||
let mut bar_tick = 0i64;
|
||||
let mut guard = 0;
|
||||
while bar_tick <= len_ticks && guard < 2000 {
|
||||
let x = left + bar_tick as f32 * px_per_tick;
|
||||
p.line_segment([pos2(x - 8.0, y_of(10)), pos2(x - 8.0, y_of(-10))], Stroke::new(1.0, ink));
|
||||
let m = s.tempo.meter_at_tick(base + bar_tick);
|
||||
let bb = s.tempo.bar_beat_at_tick(base + bar_tick);
|
||||
p.text(pos2(x - 6.0, y_of(12)), Align2::LEFT_BOTTOM, bb.bar.to_string(), regular(9.0), Color32::from_rgb(120, 110, 100));
|
||||
bar_tick += m.ticks_per_bar().max(1);
|
||||
guard += 1;
|
||||
}
|
||||
// Notes.
|
||||
for n in &sequence.notes {
|
||||
let x = left + n.start as f32 * px_per_tick;
|
||||
let (step, sharp) = diatonic(n.pitch);
|
||||
let y = y_of(step);
|
||||
// Ledger lines.
|
||||
let ledgers: Vec<i32> = if step >= 12 {
|
||||
(12..=step).step_by(2).collect()
|
||||
} else if step <= -12 {
|
||||
(step..=-12).filter(|s| s % 2 == 0).collect()
|
||||
} else if step == 0 || step == 1 {
|
||||
vec![0]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for l in ledgers {
|
||||
p.line_segment([pos2(x - 7.0, y_of(l)), pos2(x + 7.0, y_of(l))], Stroke::new(1.0, ink));
|
||||
egui::Window::new(crate::localization::text("Score Editor"))
|
||||
.id(egui::Id::unique("Score Editor"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(900.0, 340.0))
|
||||
.show(ctx, |ui| {
|
||||
let Some(cid) = crate::midi_editor::target_clip(app) else {
|
||||
ui.label(crate::localization::text("Select a MIDI clip or MIDI track."));
|
||||
return;
|
||||
};
|
||||
let s = app.engine.session();
|
||||
let Some((tid, clip)) = s.find_clip(cid).map(|(t, c)| (t, c.clone())) else { return };
|
||||
let ClipContent::Midi { sequence } = &clip.content else { return };
|
||||
let title = s.track(tid).map_or(String::new(), |t| t.name.clone());
|
||||
ui.label(egui::RichText::new(format!("{title} — {}", clip.name)).font(bold(13.0)));
|
||||
let len_ticks = (s.tempo.samples_to_ticks(clip.end(), s.sample_rate) - s.tempo.samples_to_ticks(clip.start, s.sample_rate)).max(1);
|
||||
let px_per_tick = 0.07f32;
|
||||
let width = (len_ticks as f32 * px_per_tick + 120.0).max(ui.available_width());
|
||||
egui::ScrollArea::horizontal().show(ui, |ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(width, 230.0), Sense::hover());
|
||||
let p = ui.painter_at(r);
|
||||
p.rect_filled(r, 4.0, Color32::from_rgb(246, 243, 236));
|
||||
let ink = Color32::from_rgb(20, 20, 24);
|
||||
let left = r.min.x + 70.0;
|
||||
// Treble staff: E4..F5 (steps 2..10 above C4); bass: G2..A3 (steps -10..-2).
|
||||
let c4_y = r.min.y + 115.0;
|
||||
let y_of = |step: i32| c4_y - step as f32 * STEP;
|
||||
for line in [2, 4, 6, 8, 10, -2, -4, -6, -8, -10] {
|
||||
let y = y_of(line);
|
||||
p.line_segment([pos2(r.min.x + 10.0, y), pos2(r.max.x - 10.0, y)], Stroke::new(1.0, ink));
|
||||
}
|
||||
let q = n.length as f32 / TICKS_PER_QUARTER as f32;
|
||||
let hollow = q >= 1.75;
|
||||
let head = Rect::from_center_size(pos2(x, y), vec2(10.0, 7.5));
|
||||
if hollow {
|
||||
p.add(Shape::ellipse_stroke(head.center(), head.size() * 0.5, Stroke::new(1.6, ink)));
|
||||
} else {
|
||||
p.add(Shape::ellipse_filled(head.center(), head.size() * 0.5, ink));
|
||||
p.text(pos2(r.min.x + 22.0, y_of(6)), Align2::CENTER_CENTER, "𝄞", regular(36.0), ink);
|
||||
// Bass clef, drawn: a curl from the F line plus two dots around it.
|
||||
let f = pos2(r.min.x + 18.0, y_of(-4));
|
||||
let curl: Vec<Pos2> = (0..=20)
|
||||
.map(|i| {
|
||||
let a = -2.6 + i as f32 * 0.19;
|
||||
let rad = 7.0 + i as f32 * 0.35;
|
||||
pos2(f.x + a.cos() * rad * 0.9 + 2.0, f.y + a.sin() * rad + 4.0)
|
||||
})
|
||||
.collect();
|
||||
p.circle_filled(pos2(f.x - 4.0, f.y), 3.0, ink);
|
||||
p.add(Shape::line(curl, Stroke::new(2.2, ink)));
|
||||
p.circle_filled(pos2(f.x + 14.0, y_of(-3)), 1.8, ink);
|
||||
p.circle_filled(pos2(f.x + 14.0, y_of(-5)), 1.8, ink);
|
||||
p.line_segment([pos2(r.min.x + 10.0, y_of(10)), pos2(r.min.x + 10.0, y_of(-10))], Stroke::new(2.0, ink));
|
||||
// Bar lines.
|
||||
let base = s.tempo.samples_to_ticks(clip.start, s.sample_rate);
|
||||
let mut bar_tick = 0i64;
|
||||
let mut guard = 0;
|
||||
while bar_tick <= len_ticks && guard < 2000 {
|
||||
let x = left + bar_tick as f32 * px_per_tick;
|
||||
p.line_segment([pos2(x - 8.0, y_of(10)), pos2(x - 8.0, y_of(-10))], Stroke::new(1.0, ink));
|
||||
let m = s.tempo.meter_at_tick(base + bar_tick);
|
||||
let bb = s.tempo.bar_beat_at_tick(base + bar_tick);
|
||||
p.text(pos2(x - 6.0, y_of(12)), Align2::LEFT_BOTTOM, bb.bar.to_string(), regular(9.0), Color32::from_rgb(120, 110, 100));
|
||||
bar_tick += m.ticks_per_bar().max(1);
|
||||
guard += 1;
|
||||
}
|
||||
if sharp {
|
||||
// An original drawn sharp sign: no bundled family covers U+266F.
|
||||
let cx = x - 12.0;
|
||||
for dx in [-2.6, 1.2] {
|
||||
p.line_segment([pos2(cx + dx - 1.0, y - 5.0), pos2(cx + dx + 1.0, y + 5.0)], Stroke::new(1.1, ink));
|
||||
}
|
||||
for dy in [-1.8, 1.8] {
|
||||
p.line_segment([pos2(cx - 5.0, y + dy), pos2(cx + 5.0, y + dy - 1.0)], Stroke::new(1.1, ink));
|
||||
}
|
||||
}
|
||||
if q < 3.5 {
|
||||
// Stems up below the middle line of each staff, down above it.
|
||||
let up = if step >= 0 { step < 6 } else { step < -6 };
|
||||
let (sx, sy0, sy1): (f32, f32, f32) = if up { (x + 4.5, y, y - 26.0) } else { (x - 4.5, y, y + 26.0) };
|
||||
p.line_segment([pos2(sx, sy0), pos2(sx, sy1)], Stroke::new(1.2, ink));
|
||||
let flags = if q <= 0.3 {
|
||||
2
|
||||
} else if q <= 0.6 {
|
||||
1
|
||||
// Notes.
|
||||
for n in &sequence.notes {
|
||||
let x = left + n.start as f32 * px_per_tick;
|
||||
let (step, sharp) = diatonic(n.pitch);
|
||||
let y = y_of(step);
|
||||
// Ledger lines.
|
||||
let ledgers: Vec<i32> = if step >= 12 {
|
||||
(12..=step).step_by(2).collect()
|
||||
} else if step <= -12 {
|
||||
(step..=-12).filter(|s| s % 2 == 0).collect()
|
||||
} else if step == 0 || step == 1 {
|
||||
vec![0]
|
||||
} else {
|
||||
0
|
||||
Vec::new()
|
||||
};
|
||||
for f in 0..flags {
|
||||
let fy = sy1 + if up { f as f32 * 6.0 } else { -(f as f32) * 6.0 };
|
||||
let tip: Pos2 = pos2(sx + 8.0, fy + if up { 10.0 } else { -10.0 });
|
||||
p.line_segment([pos2(sx, fy), tip], Stroke::new(1.6, ink));
|
||||
for l in ledgers {
|
||||
p.line_segment([pos2(x - 7.0, y_of(l)), pos2(x + 7.0, y_of(l))], Stroke::new(1.0, ink));
|
||||
}
|
||||
let q = n.length as f32 / TICKS_PER_QUARTER as f32;
|
||||
let hollow = q >= 1.75;
|
||||
let head = Rect::from_center_size(pos2(x, y), vec2(10.0, 7.5));
|
||||
if hollow {
|
||||
p.add(Shape::ellipse_stroke(head.center(), head.size() * 0.5, Stroke::new(1.6, ink)));
|
||||
} else {
|
||||
p.add(Shape::ellipse_filled(head.center(), head.size() * 0.5, ink));
|
||||
}
|
||||
if sharp {
|
||||
// An original drawn sharp sign: no bundled family covers U+266F.
|
||||
let cx = x - 12.0;
|
||||
for dx in [-2.6, 1.2] {
|
||||
p.line_segment([pos2(cx + dx - 1.0, y - 5.0), pos2(cx + dx + 1.0, y + 5.0)], Stroke::new(1.1, ink));
|
||||
}
|
||||
for dy in [-1.8, 1.8] {
|
||||
p.line_segment([pos2(cx - 5.0, y + dy), pos2(cx + 5.0, y + dy - 1.0)], Stroke::new(1.1, ink));
|
||||
}
|
||||
}
|
||||
if q < 3.5 {
|
||||
// Stems up below the middle line of each staff, down above it.
|
||||
let up = if step >= 0 { step < 6 } else { step < -6 };
|
||||
let (sx, sy0, sy1): (f32, f32, f32) = if up { (x + 4.5, y, y - 26.0) } else { (x - 4.5, y, y + 26.0) };
|
||||
p.line_segment([pos2(sx, sy0), pos2(sx, sy1)], Stroke::new(1.2, ink));
|
||||
let flags = if q <= 0.3 {
|
||||
2
|
||||
} else if q <= 0.6 {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
for f in 0..flags {
|
||||
let fy = sy1 + if up { f as f32 * 6.0 } else { -(f as f32) * 6.0 };
|
||||
let tip: Pos2 = pos2(sx + 8.0, fy + if up { 10.0 } else { -10.0 });
|
||||
p.line_segment([pos2(sx, fy), tip], Stroke::new(1.6, ink));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text("Notation view of the MIDI clip; edit notes in the MIDI Editor or Event List."))
|
||||
.small(),
|
||||
);
|
||||
});
|
||||
ui.label(egui::RichText::new("Notation view of the MIDI clip; edit notes in the MIDI Editor or Event List.").small());
|
||||
});
|
||||
app.ui.show_score = open;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn tracks_and_groups(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let header = Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), 22.0));
|
||||
panel_header(ui, "TRACKS");
|
||||
let plus = Rect::from_center_size(pos2(header.max.x - 13.0, header.center().y), vec2(18.0, 18.0));
|
||||
let tip = format!("New Tracks… ({})", crate::shortcuts::shortcut_label("Cmd+Shift+N", ui.ctx().os().is_mac()));
|
||||
let tip = crate::localized_format!("New Tracks… ({})", crate::shortcuts::display_shortcut("Cmd+Shift+N", ui.ctx().os().is_mac()));
|
||||
if crate::widgets::icon_button(&mut ui.new_child(egui::UiBuilder::new().max_rect(plus)), plus.size(), "plus", false, &tip).clicked() {
|
||||
let _ = app.dialogs.open_for_command(&app.engine, "track.new");
|
||||
}
|
||||
@@ -112,14 +112,14 @@ pub fn tracks_and_groups(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let groups_area = with_pending_offset(egui::ScrollArea::vertical().id_salt("groups_scroll"), ui, "groups_scroll");
|
||||
let out = groups_area.auto_shrink([false, false]).scroll_bar_visibility(hidden).show(ui, |ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 17.0), Sense::hover());
|
||||
ui.painter().text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, "<ALL>", regular(11.5).clone(), t.text);
|
||||
ui.painter().text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, crate::localization::text("<ALL>"), regular(11.5).clone(), t.text);
|
||||
let all = ui.interact(r, ui.scope_id().with("group_all"), Sense::click());
|
||||
all.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "<ALL>"));
|
||||
all.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localization::text("<ALL>")));
|
||||
if all.double_clicked() {
|
||||
let _ = app.run("edit.select_all", json!({}));
|
||||
}
|
||||
all.context_menu(|ui| {
|
||||
if ui.button("New Group…").clicked() {
|
||||
if ui.button(crate::localization::text("New Group…")).clicked() {
|
||||
let _ = app.dialogs.open_for_command(&app.engine, "track.group");
|
||||
ui.close();
|
||||
}
|
||||
@@ -147,19 +147,19 @@ pub fn tracks_and_groups(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let _ = app.run("edit.select", json!({"tracks": members, "exact": true}));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button("Select Tracks in Group").clicked() {
|
||||
if ui.button(crate::localization::text("Select Tracks in Group")).clicked() {
|
||||
let _ = app.run("edit.select", json!({"tracks": members, "exact": true}));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(if active { "Disable" } else { "Enable" }).clicked() {
|
||||
if ui.button(crate::localization::text(if active { "Disable" } else { "Enable" })).clicked() {
|
||||
let _ = app.run("track.group_toggle", json!({"group": id}));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Modify Group…").clicked() {
|
||||
if ui.button(crate::localization::text("Modify Group…")).clicked() {
|
||||
let _ = app.dialogs.open_modify_group(&app.engine, soundcraft_model::GroupId(id));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Delete Group").clicked() {
|
||||
if ui.button(crate::localization::text("Delete Group")).clicked() {
|
||||
let _ = app.run("track.ungroup", json!({"group": id}));
|
||||
ui.close();
|
||||
}
|
||||
|
||||
@@ -6,86 +6,100 @@ pub(super) fn transport_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::current();
|
||||
egui::Window::new("Transport").open(&mut open).resizable(false).default_pos(pos2(400.0, 500.0)).show(ctx, |ui| {
|
||||
let flags = app.engine.session().edit.flags.clone();
|
||||
let expanded = flags.contains("view.transport.expanded");
|
||||
ui.horizontal(|ui| {
|
||||
for (icon, cmd) in [
|
||||
("rtz", "transport.rtz"),
|
||||
("rewind", "transport.rewind"),
|
||||
("stop", "transport.stop"),
|
||||
("play", "transport.play"),
|
||||
("ffwd", "transport.fast_forward"),
|
||||
("end", "transport.go_to_end"),
|
||||
("record", "transport.record"),
|
||||
] {
|
||||
let resp = crate::widgets::icon_button(
|
||||
ui,
|
||||
vec2(34.0, 26.0),
|
||||
icon,
|
||||
(cmd == "transport.play" && app.is_playing()) || (cmd == "transport.record" && app.engine.transport.recording),
|
||||
cmd,
|
||||
);
|
||||
if cmd == "transport.record"
|
||||
&& let Some(why) = app.record_hint()
|
||||
{
|
||||
egui::Tooltip::for_widget(&resp).show(|ui| ui.label(why));
|
||||
}
|
||||
if resp.clicked() {
|
||||
let _ = app.run(cmd, json!({}));
|
||||
}
|
||||
}
|
||||
if flags.contains("view.transport.output_meters") {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(22.0, 26.0), Sense::hover());
|
||||
let m = app.main_meter;
|
||||
crate::widgets::meter(ui, Rect::from_min_size(r.min, vec2(10.0, 26.0)), m.level[0], m.hold[0], m.clip);
|
||||
crate::widgets::meter(ui, Rect::from_min_size(pos2(r.min.x + 12.0, r.min.y), vec2(10.0, 26.0)), m.level[1], m.hold[1], m.clip);
|
||||
}
|
||||
});
|
||||
let s = app.engine.session();
|
||||
let fmt = |x: i64| s.format_position(x, s.edit.main_counter);
|
||||
if flags.contains("view.transport.counters") || expanded || flags.is_empty() {
|
||||
ui.label(egui::RichText::new(fmt(app.position())).font(mono(20.0)).color(t.counter_text));
|
||||
}
|
||||
if expanded {
|
||||
let e = s.edit.clone();
|
||||
egui::Grid::new("tx_exp").num_columns(4).show(ui, |ui| {
|
||||
ui.label("Start");
|
||||
ui.label(egui::RichText::new(fmt(e.selection.start)).font(mono(11.0)));
|
||||
ui.label("Pre-roll");
|
||||
ui.label(egui::RichText::new(format!("{:.2} s", s.sample_rate.seconds(e.pre_roll))).font(mono(11.0)));
|
||||
ui.end_row();
|
||||
ui.label("End");
|
||||
ui.label(egui::RichText::new(fmt(e.selection.end)).font(mono(11.0)));
|
||||
ui.label("Post-roll");
|
||||
ui.label(egui::RichText::new(format!("{:.2} s", s.sample_rate.seconds(e.post_roll))).font(mono(11.0)));
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
if flags.contains("view.transport.midi_controls") || expanded {
|
||||
let (click, countoff, merge, loop_rec, prepost) = {
|
||||
let e = &app.engine.session().edit;
|
||||
(e.click, e.countoff, e.midi_merge, e.loop_record, e.pre_post_roll)
|
||||
};
|
||||
egui::Window::new(crate::localization::text("Transport"))
|
||||
.id(egui::Id::unique("Transport"))
|
||||
.open(&mut open)
|
||||
.resizable(false)
|
||||
.default_pos(pos2(400.0, 500.0))
|
||||
.show(ctx, |ui| {
|
||||
let flags = app.engine.session().edit.flags.clone();
|
||||
let expanded = flags.contains("view.transport.expanded");
|
||||
ui.horizontal(|ui| {
|
||||
for (label, on, cmd) in [
|
||||
("Click", click, "options.click"),
|
||||
("Count Off", countoff, "options.countoff"),
|
||||
("MIDI Merge", merge, "options.midi_merge"),
|
||||
("Loop Rec", loop_rec, "options.loop_record"),
|
||||
("Pre/Post", prepost, "options.pre_post_roll"),
|
||||
for (icon, cmd) in [
|
||||
("rtz", "transport.rtz"),
|
||||
("rewind", "transport.rewind"),
|
||||
("stop", "transport.stop"),
|
||||
("play", "transport.play"),
|
||||
("ffwd", "transport.fast_forward"),
|
||||
("end", "transport.go_to_end"),
|
||||
("record", "transport.record"),
|
||||
] {
|
||||
if ui.selectable_label(on, label).clicked() {
|
||||
let resp = crate::widgets::icon_button(
|
||||
ui,
|
||||
vec2(34.0, 26.0),
|
||||
icon,
|
||||
(cmd == "transport.play" && app.is_playing()) || (cmd == "transport.record" && app.engine.transport.recording),
|
||||
cmd,
|
||||
);
|
||||
if cmd == "transport.record"
|
||||
&& let Some(why) = app.record_hint()
|
||||
{
|
||||
egui::Tooltip::for_widget(&resp).show(|ui| ui.label(why));
|
||||
}
|
||||
if resp.clicked() {
|
||||
let _ = app.run(cmd, json!({}));
|
||||
}
|
||||
}
|
||||
if flags.contains("view.transport.output_meters") {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(22.0, 26.0), Sense::hover());
|
||||
let m = app.main_meter;
|
||||
crate::widgets::meter(ui, Rect::from_min_size(r.min, vec2(10.0, 26.0)), m.level[0], m.hold[0], m.clip);
|
||||
crate::widgets::meter(ui, Rect::from_min_size(pos2(r.min.x + 12.0, r.min.y), vec2(10.0, 26.0)), m.level[1], m.hold[1], m.clip);
|
||||
}
|
||||
});
|
||||
let tick = app.engine.session().tempo.samples_to_ticks(app.position(), app.engine.session().sample_rate);
|
||||
let bpm = app.engine.session().tempo.tempo_at_tick(tick);
|
||||
let m = app.engine.session().tempo.meter_at_tick(tick);
|
||||
ui.label(egui::RichText::new(format!("♩ = {bpm:.2} {}/{}", m.numerator, m.denominator)).font(mono(12.0)).color(t.counter_text));
|
||||
}
|
||||
});
|
||||
let s = app.engine.session();
|
||||
let fmt = |x: i64| s.format_position(x, s.edit.main_counter);
|
||||
if flags.contains("view.transport.counters") || expanded || flags.is_empty() {
|
||||
ui.label(egui::RichText::new(fmt(app.position())).font(mono(20.0)).color(t.counter_text));
|
||||
}
|
||||
if expanded {
|
||||
let e = s.edit.clone();
|
||||
egui::Grid::new("tx_exp").num_columns(4).show(ui, |ui| {
|
||||
ui.label(crate::localization::text("Start"));
|
||||
ui.label(egui::RichText::new(fmt(e.selection.start)).font(mono(11.0)));
|
||||
ui.label(crate::localization::text("Pre-roll"));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localized_format!("{seconds:.2} s", seconds = s.sample_rate.seconds(e.pre_roll))).font(mono(11.0)),
|
||||
);
|
||||
ui.end_row();
|
||||
ui.label(crate::localization::text("End"));
|
||||
ui.label(egui::RichText::new(fmt(e.selection.end)).font(mono(11.0)));
|
||||
ui.label(crate::localization::text("Post-roll"));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localized_format!("{seconds:.2} s", seconds = s.sample_rate.seconds(e.post_roll)))
|
||||
.font(mono(11.0)),
|
||||
);
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
if flags.contains("view.transport.midi_controls") || expanded {
|
||||
let (click, countoff, merge, loop_rec, prepost) = {
|
||||
let e = &app.engine.session().edit;
|
||||
(e.click, e.countoff, e.midi_merge, e.loop_record, e.pre_post_roll)
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
for (label, on, cmd) in [
|
||||
("Click", click, "options.click"),
|
||||
("Count Off", countoff, "options.countoff"),
|
||||
("MIDI Merge", merge, "options.midi_merge"),
|
||||
("Loop Rec", loop_rec, "options.loop_record"),
|
||||
("Pre/Post", prepost, "options.pre_post_roll"),
|
||||
] {
|
||||
if ui.selectable_label(on, crate::localization::text(label)).clicked() {
|
||||
let _ = app.run(cmd, json!({}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let tick = app.engine.session().tempo.samples_to_ticks(app.position(), app.engine.session().sample_rate);
|
||||
let bpm = app.engine.session().tempo.tempo_at_tick(tick);
|
||||
let m = app.engine.session().tempo.meter_at_tick(tick);
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localized_format!("♩ = {bpm:.2} {n}/{d}", bpm = bpm, n = m.numerator, d = m.denominator))
|
||||
.font(mono(12.0))
|
||||
.color(t.counter_text),
|
||||
);
|
||||
}
|
||||
});
|
||||
app.ui.show_transport = open;
|
||||
}
|
||||
|
||||
@@ -94,13 +108,17 @@ pub(super) fn big_counter(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Big Counter").open(&mut open).default_size(vec2(520.0, 110.0)).show(ctx, |ui| {
|
||||
let s = app.engine.session();
|
||||
let txt = s.format_position(app.position(), s.edit.main_counter);
|
||||
let r = ui.available_rect_before_wrap();
|
||||
let t = Tokens::current();
|
||||
ui.painter().rect_filled(r, 4.0, t.big_counter_bg);
|
||||
ui.painter().text(r.center(), Align2::CENTER_CENTER, txt, mono((r.height() * 0.6).clamp(20.0, 120.0)), t.counter_text);
|
||||
});
|
||||
egui::Window::new(crate::localization::text("Big Counter"))
|
||||
.id(egui::Id::unique("Big Counter"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(520.0, 110.0))
|
||||
.show(ctx, |ui| {
|
||||
let s = app.engine.session();
|
||||
let txt = s.format_position(app.position(), s.edit.main_counter);
|
||||
let r = ui.available_rect_before_wrap();
|
||||
let t = Tokens::current();
|
||||
ui.painter().rect_filled(r, 4.0, t.big_counter_bg);
|
||||
ui.painter().text(r.center(), Align2::CENTER_CENTER, txt, mono((r.height() * 0.6).clamp(20.0, 120.0)), t.counter_text);
|
||||
});
|
||||
app.ui.show_big_counter = open;
|
||||
}
|
||||
|
||||
@@ -32,19 +32,19 @@ fn video_status_text(app: &SoundApp, pic: Option<&(MovieKey, Result<String, Stri
|
||||
|
||||
fn draw_video_surface(app: &SoundApp, painter: &egui::Painter, img: Rect, pic: Option<&(MovieKey, Result<String, String>, f64, f64)>, on: bool) {
|
||||
let msg = if !on {
|
||||
Some("Video Track Offline".to_string())
|
||||
Some(crate::localization::text("Video Track Offline").to_string())
|
||||
} else {
|
||||
match pic {
|
||||
None => None,
|
||||
Some((_, Err(why), ..)) => Some(why.clone()),
|
||||
Some((_, Err(why), ..)) => Some(crate::localization::text(why).to_string()),
|
||||
Some((k, ..)) => match (app.video.current(*k), app.video.current_error(*k)) {
|
||||
(Some(tex), _) => {
|
||||
painter.image(tex.id(), img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
None
|
||||
}
|
||||
(None, Some(e)) => Some(e.to_string()),
|
||||
(None, Some(e)) => Some(crate::localization::text(e).to_string()),
|
||||
(None, None) => match app.video.info(*k) {
|
||||
Some(Err(e)) => Some(e.clone()),
|
||||
Some(Err(e)) => Some(crate::localization::text(e).to_string()),
|
||||
_ => None,
|
||||
},
|
||||
},
|
||||
@@ -72,33 +72,38 @@ fn video(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.clamp(0.2, 5.0);
|
||||
let mut open = true;
|
||||
let mut burn = app.ui.video_burn_in;
|
||||
egui::Window::new("Video").open(&mut open).default_size(vec2(480.0, 480.0 / aspect + 28.0)).resizable(true).show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
crate::widgets::checkbox(ui, &mut burn, "Timecode burn-in");
|
||||
let text = video_status_text(app, pic.as_ref());
|
||||
ui.label(egui::RichText::new(text).font(regular(10.5)).color(Color32::from_gray(150)));
|
||||
egui::Window::new(crate::localization::text("Video"))
|
||||
.id(egui::Id::unique("Video"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(480.0, 480.0 / aspect + 28.0))
|
||||
.resizable(true)
|
||||
.show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
crate::widgets::checkbox(ui, &mut burn, crate::localization::text("Timecode burn-in"));
|
||||
let text = video_status_text(app, pic.as_ref());
|
||||
ui.label(egui::RichText::new(text).font(regular(10.5)).color(Color32::from_gray(150)));
|
||||
});
|
||||
let avail = ui.available_rect_before_wrap();
|
||||
let (r, _) = ui.allocate_exact_size(avail.size().max(vec2(64.0, 36.0)), Sense::hover());
|
||||
let painter = ui.painter_at(r);
|
||||
painter.rect_filled(r, 0.0, Color32::BLACK);
|
||||
// Fit the picture inside the area, keeping its aspect.
|
||||
let (mut w, mut h) = (r.width(), r.width() / aspect);
|
||||
if h > r.height() {
|
||||
h = r.height();
|
||||
w = h * aspect;
|
||||
}
|
||||
let img = Rect::from_center_size(r.center(), vec2(w, h));
|
||||
draw_video_surface(app, &painter, img, pic.as_ref(), on);
|
||||
if burn {
|
||||
let tc = s.format_position(pos, TimeFormat::Timecode);
|
||||
let size = (h / 12.0).clamp(10.0, 36.0);
|
||||
let galley = painter.layout_no_wrap(tc, mono(size), Color32::WHITE);
|
||||
let at = pos2(img.center().x - galley.size().x / 2.0, img.max.y - galley.size().y - size * 0.6);
|
||||
painter.rect_filled(Rect::from_min_size(at, galley.size()).expand2(vec2(6.0, 2.0)), 2.0, Color32::from_black_alpha(200));
|
||||
painter.galley(at, galley, Color32::WHITE);
|
||||
}
|
||||
});
|
||||
let avail = ui.available_rect_before_wrap();
|
||||
let (r, _) = ui.allocate_exact_size(avail.size().max(vec2(64.0, 36.0)), Sense::hover());
|
||||
let painter = ui.painter_at(r);
|
||||
painter.rect_filled(r, 0.0, Color32::BLACK);
|
||||
// Fit the picture inside the area, keeping its aspect.
|
||||
let (mut w, mut h) = (r.width(), r.width() / aspect);
|
||||
if h > r.height() {
|
||||
h = r.height();
|
||||
w = h * aspect;
|
||||
}
|
||||
let img = Rect::from_center_size(r.center(), vec2(w, h));
|
||||
draw_video_surface(app, &painter, img, pic.as_ref(), on);
|
||||
if burn {
|
||||
let tc = s.format_position(pos, TimeFormat::Timecode);
|
||||
let size = (h / 12.0).clamp(10.0, 36.0);
|
||||
let galley = painter.layout_no_wrap(tc, mono(size), Color32::WHITE);
|
||||
let at = pos2(img.center().x - galley.size().x / 2.0, img.max.y - galley.size().y - size * 0.6);
|
||||
painter.rect_filled(Rect::from_min_size(at, galley.size()).expand2(vec2(6.0, 2.0)), 2.0, Color32::from_black_alpha(200));
|
||||
painter.galley(at, galley, Color32::WHITE);
|
||||
}
|
||||
});
|
||||
app.ui.video_burn_in = burn;
|
||||
if !open {
|
||||
app.ui.show_video = false;
|
||||
@@ -137,57 +142,68 @@ fn universe(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let pos = app.position();
|
||||
let mut open = true;
|
||||
let mut locate = None;
|
||||
egui::Window::new("Video Universe").open(&mut open).default_size(vec2(640.0, 90.0)).resizable(true).show(ctx, |ui| {
|
||||
let avail = ui.available_rect_before_wrap();
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(avail.width().max(120.0), 64.0), Sense::click_and_drag());
|
||||
let painter = ui.painter_at(r);
|
||||
painter.rect_filled(r, 0.0, Color32::from_rgb(14, 14, 15));
|
||||
let end = s.content_end().max(s.sample_rate.samples(10.0)).max(1);
|
||||
let x_at = |at: i64| r.min.x + r.width() * (at as f32 / end as f32);
|
||||
let on = online(&s);
|
||||
let Some(track) = s.tracks.iter().find(|t| t.kind == TrackKind::Video) else {
|
||||
painter.text(r.center(), Align2::CENTER_CENTER, "No Video track — File › Import › Video…", regular(11.0), Color32::from_gray(150));
|
||||
return;
|
||||
};
|
||||
let ppp = ctx.pixels_per_point();
|
||||
for c in track.clips() {
|
||||
let ClipContent::Video { source, offset } = c.content else { continue };
|
||||
let Some(v) = s.video(source) else { continue };
|
||||
let key = MovieKey::new(source, &v.path);
|
||||
let cr = Rect::from_min_max(pos2(x_at(c.start), r.min.y + 4.0), pos2(x_at(c.end()).max(x_at(c.start) + 2.0), r.max.y - 4.0));
|
||||
painter.rect_filled(cr, 0.0, Color32::from_rgb(30, 30, 34));
|
||||
if !on || v.offline.is_some() {
|
||||
continue;
|
||||
}
|
||||
let tw = (cr.height() * v.aspect() as f32).max(8.0);
|
||||
let hpx = ((cr.height() * ppp / 16.0).ceil() * 16.0).clamp(16.0, 256.0) as u32;
|
||||
// Only the thumbnails inside the strip, counted rather than stepped: a clip starting
|
||||
// far left of it has an edge so large that adding a thumbnail's width wouldn't move it.
|
||||
let shown = cr.intersect(r);
|
||||
for x in thumb_xs(cr.min.x, shown.min.x, shown.max.x, tw) {
|
||||
let secs = movie_secs(&s, c.start, offset, strip_position(x, r.min.x, r.width(), end, c.start)).max(0.0);
|
||||
if let Some(tex) = app.video.thumb(ctx, key, &v.path, secs, hpx) {
|
||||
let tr = Rect::from_min_size(pos2(x, cr.min.y), vec2(tw, cr.height()));
|
||||
let vis = tr.intersect(cr);
|
||||
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2((vis.width() / tw).clamp(0.0, 1.0), 1.0));
|
||||
painter.image(tex.id(), vis, uv, Color32::WHITE);
|
||||
egui::Window::new(crate::localization::text("Video Universe"))
|
||||
.id(egui::Id::unique("Video Universe"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(640.0, 90.0))
|
||||
.resizable(true)
|
||||
.show(ctx, |ui| {
|
||||
let avail = ui.available_rect_before_wrap();
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(avail.width().max(120.0), 64.0), Sense::click_and_drag());
|
||||
let painter = ui.painter_at(r);
|
||||
painter.rect_filled(r, 0.0, Color32::from_rgb(14, 14, 15));
|
||||
let end = s.content_end().max(s.sample_rate.samples(10.0)).max(1);
|
||||
let x_at = |at: i64| r.min.x + r.width() * (at as f32 / end as f32);
|
||||
let on = online(&s);
|
||||
let Some(track) = s.tracks.iter().find(|t| t.kind == TrackKind::Video) else {
|
||||
painter.text(
|
||||
r.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
crate::localization::text("No Video track — File › Import › Video…"),
|
||||
regular(11.0),
|
||||
Color32::from_gray(150),
|
||||
);
|
||||
return;
|
||||
};
|
||||
let ppp = ctx.pixels_per_point();
|
||||
for c in track.clips() {
|
||||
let ClipContent::Video { source, offset } = c.content else { continue };
|
||||
let Some(v) = s.video(source) else { continue };
|
||||
let key = MovieKey::new(source, &v.path);
|
||||
let cr = Rect::from_min_max(pos2(x_at(c.start), r.min.y + 4.0), pos2(x_at(c.end()).max(x_at(c.start) + 2.0), r.max.y - 4.0));
|
||||
painter.rect_filled(cr, 0.0, Color32::from_rgb(30, 30, 34));
|
||||
if !on || v.offline.is_some() {
|
||||
continue;
|
||||
}
|
||||
let tw = (cr.height() * v.aspect() as f32).max(8.0);
|
||||
let hpx = ((cr.height() * ppp / 16.0).ceil() * 16.0).clamp(16.0, 256.0) as u32;
|
||||
// Only the thumbnails inside the strip, counted rather than stepped: a clip starting
|
||||
// far left of it has an edge so large that adding a thumbnail's width wouldn't move it.
|
||||
let shown = cr.intersect(r);
|
||||
for x in thumb_xs(cr.min.x, shown.min.x, shown.max.x, tw) {
|
||||
let secs = movie_secs(&s, c.start, offset, strip_position(x, r.min.x, r.width(), end, c.start)).max(0.0);
|
||||
if let Some(tex) = app.video.thumb(ctx, key, &v.path, secs, hpx) {
|
||||
let tr = Rect::from_min_size(pos2(x, cr.min.y), vec2(tw, cr.height()));
|
||||
let vis = tr.intersect(cr);
|
||||
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2((vis.width() / tw).clamp(0.0, 1.0), 1.0));
|
||||
painter.image(tex.id(), vis, uv, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Edit window's visible range and the playhead.
|
||||
let spp = s.edit.zoom.samples_per_px.max(1e-6);
|
||||
let vs = s.edit.zoom.scroll.max(0);
|
||||
let ve = vs.saturating_add((spp * f64::from(ui.ctx().content_rect().width())) as i64);
|
||||
let view = Rect::from_min_max(pos2(x_at(vs), r.min.y + 1.0), pos2(x_at(ve).min(r.max.x), r.max.y - 1.0));
|
||||
painter.rect_stroke(view, 0.0, egui::Stroke::new(1.0, Color32::from_rgb(230, 200, 80)), egui::StrokeKind::Inside);
|
||||
let px = x_at(pos);
|
||||
painter.line_segment([pos2(px, r.min.y), pos2(px, r.max.y)], egui::Stroke::new(1.5, Color32::from_rgb(240, 240, 240)));
|
||||
if (resp.clicked() || resp.dragged())
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
locate = Some((((p.x - r.min.x) / r.width()).clamp(0.0, 1.0) * end as f32) as i64);
|
||||
}
|
||||
});
|
||||
// The Edit window's visible range and the playhead.
|
||||
let spp = s.edit.zoom.samples_per_px.max(1e-6);
|
||||
let vs = s.edit.zoom.scroll.max(0);
|
||||
let ve = vs.saturating_add((spp * f64::from(ui.ctx().content_rect().width())) as i64);
|
||||
let view = Rect::from_min_max(pos2(x_at(vs), r.min.y + 1.0), pos2(x_at(ve).min(r.max.x), r.max.y - 1.0));
|
||||
painter.rect_stroke(view, 0.0, egui::Stroke::new(1.0, Color32::from_rgb(230, 200, 80)), egui::StrokeKind::Inside);
|
||||
let px = x_at(pos);
|
||||
painter.line_segment([pos2(px, r.min.y), pos2(px, r.max.y)], egui::Stroke::new(1.5, Color32::from_rgb(240, 240, 240)));
|
||||
if (resp.clicked() || resp.dragged())
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
locate = Some((((p.x - r.min.x) / r.width()).clamp(0.0, 1.0) * end as f32) as i64);
|
||||
}
|
||||
});
|
||||
if let Some(at) = locate {
|
||||
let _ = app.run("transport.locate", json!({"at": at}));
|
||||
let _ = app.run("edit.select", json!({"start": at, "end": at}));
|
||||
|
||||
@@ -30,34 +30,34 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
fn audio_health(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_audio_health;
|
||||
win(ctx, &mut open, "Session Audio Health", vec2(620.0, 360.0), |ui| {
|
||||
let refresh = ui.button("Refresh Report").clicked();
|
||||
let refresh = ui.button(crate::localization::text("Refresh Report")).clicked();
|
||||
if app.audio_health_report.is_none() || refresh {
|
||||
app.audio_health_report = Some(app.engine.execute("session.audio_health", &json!({})).map_err(|error| error.to_string()));
|
||||
}
|
||||
let Some(result) = &app.audio_health_report else { return };
|
||||
match result {
|
||||
Ok(report) => {
|
||||
ui.label(format!("{} audio clips checked · {} issues", report["audio_clips"], report["issue_count"]));
|
||||
ui.label(crate::localized_format!("{} audio clips checked · {} issues", report["audio_clips"], report["issue_count"]));
|
||||
ui.label(match report["active_audio_end_seconds"].as_f64() {
|
||||
Some(seconds) => format!("Active audio ends at {seconds:.2} seconds"),
|
||||
None => "Active audio end time is unknown (invalid session sample rate)".into(),
|
||||
Some(seconds) => crate::localized_format!("Active audio ends at {seconds:.2} seconds", seconds = seconds),
|
||||
None => crate::localization::text("Active audio end time is unknown (invalid session sample rate)").to_owned(),
|
||||
});
|
||||
ui.label("Includes alternate takes and muted clips. Refresh after editing.");
|
||||
ui.label(crate::localization::text("Includes alternate takes and muted clips. Refresh after editing."));
|
||||
ui.separator();
|
||||
if report["healthy"] == true {
|
||||
ui.label("All audio clips have loaded media within source bounds.");
|
||||
ui.label(crate::localization::text("All audio clips have loaded media within source bounds."));
|
||||
}
|
||||
egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
|
||||
if let Some(issues) = report["issues"].as_array() {
|
||||
for issue in issues {
|
||||
ui.group(|ui| {
|
||||
let text = |key: &str| issue[key].as_str().unwrap_or("");
|
||||
ui.label(format!(
|
||||
ui.label(crate::localized_format!(
|
||||
"{} / {} / {}{}",
|
||||
text("track"),
|
||||
text("playlist"),
|
||||
text("clip"),
|
||||
if issue["active"] == true { "" } else { " (alternate playlist)" }
|
||||
if issue["active"] == true { "" } else { crate::localization::text(" (alternate playlist)") }
|
||||
));
|
||||
ui.label(text("message"));
|
||||
if let Some(path) = issue["path"].as_str() {
|
||||
@@ -68,10 +68,10 @@ fn audio_health(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.label("Checks loaded media only, not files on disk, signal levels, plugins or routing.");
|
||||
ui.label(crate::localization::text("Checks loaded media only, not files on disk, signal levels, plugins or routing."));
|
||||
}
|
||||
Err(error) => {
|
||||
ui.label(error.to_string());
|
||||
ui.label(crate::localization::error_text(&error.to_string()));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -85,13 +85,15 @@ fn win(ctx: &egui::Context, open: &mut bool, title: &str, size: egui::Vec2, body
|
||||
if !*open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new(title).open(open).default_size(size).show(ctx, body);
|
||||
// The title is translated for display, but the id keeps the English source so a language
|
||||
// switch does not move or resize the window.
|
||||
egui::Window::new(crate::localization::text(title)).id(egui::Id::unique(title)).open(open).default_size(size).show(ctx, body);
|
||||
}
|
||||
|
||||
fn automation(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_automation;
|
||||
win(ctx, &mut open, "Automation", vec2(260.0, 260.0), |ui| {
|
||||
ui.label("Write automation for the selected tracks:");
|
||||
ui.label(crate::localization::text("Write automation for the selected tracks:"));
|
||||
let tracks = app.engine.session().edit.selected_tracks.clone();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for m in [
|
||||
@@ -103,14 +105,14 @@ fn automation(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
AutomationMode::Write,
|
||||
AutomationMode::Trim,
|
||||
] {
|
||||
if ui.button(m.label()).clicked() {
|
||||
if ui.button(crate::localization::text(m.label())).clicked() {
|
||||
let ids: Vec<u64> = tracks.iter().map(|t| t.0).collect();
|
||||
let _ = app.run("mix.automation_mode", json!({"tracks": ids, "mode": m.label()}));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.label("Enabled parameters");
|
||||
ui.label(crate::localization::text("Enabled parameters"));
|
||||
for f in ["volume", "pan", "mute", "send level", "send pan", "send mute", "plugin"] {
|
||||
let id = format!("automation.enable.{}", f.replace(' ', "_"));
|
||||
let mut on = !app.engine.session().edit.flag(&format!("{id}.off"));
|
||||
@@ -119,10 +121,10 @@ fn automation(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Write to Current").clicked() {
|
||||
if ui.button(crate::localization::text("Write to Current")).clicked() {
|
||||
let _ = app.run("automation.write_to_current", json!({}));
|
||||
}
|
||||
if ui.button("Thin All").clicked() {
|
||||
if ui.button(crate::localization::text("Thin All")).clicked() {
|
||||
let _ = app.run("automation.thin_all", json!({}));
|
||||
}
|
||||
});
|
||||
@@ -132,7 +134,7 @@ fn automation(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
fn color_palette(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_color_palette;
|
||||
win(ctx, &mut open, "Color Palette", vec2(300.0, 140.0), |ui| {
|
||||
ui.label("Apply to selected tracks (Shift: selected clips)");
|
||||
ui.label(crate::localization::text("Apply to selected tracks (Shift: selected clips)"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (i, c) in soundcraft_model::TRACK_COLORS.iter().enumerate() {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
|
||||
@@ -147,7 +149,9 @@ fn color_palette(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.add(egui::Slider::new(&mut app.ui.track_tint, 0.0..=1.0).show_value(false).text("Track tint in the Edit window"));
|
||||
ui.add(
|
||||
egui::Slider::new(&mut app.ui.track_tint, 0.0..=1.0).show_value(false).text(crate::localization::text("Track tint in the Edit window")),
|
||||
);
|
||||
});
|
||||
app.ui.show_color_palette = open;
|
||||
}
|
||||
@@ -157,11 +161,11 @@ fn disk_usage(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
win(ctx, &mut open, "Disk Usage", vec2(360.0, 160.0), |ui| {
|
||||
let s = app.engine.session();
|
||||
let bytes: u64 = s.sources.iter().map(|x| x.frames * u64::from(x.channels) * 4).sum();
|
||||
ui.label(format!("Session media: {} files, {:.1} MB in memory (32-bit float)", s.sources.len(), bytes as f64 / 1_048_576.0));
|
||||
ui.label(crate::localized_format!("Session media: {} files, {:.1} MB in memory (32-bit float)", s.sources.len(), bytes as f64 / 1_048_576.0));
|
||||
let per_min = f64::from(s.sample_rate.hz()) * 60.0 * 3.0 / 1_048_576.0;
|
||||
ui.label(format!("Recording at 24-bit uses {per_min:.1} MB per mono track-minute"));
|
||||
ui.label(crate::localized_format!("Recording at 24-bit uses {per_min:.1} MB per mono track-minute", per_min = per_min));
|
||||
if let Some(p) = &app.engine.path {
|
||||
ui.label(format!("Session file: {p}"));
|
||||
ui.label(crate::localized_format!("Session file: {p}", p = p));
|
||||
}
|
||||
});
|
||||
app.ui.show_disk_usage = open;
|
||||
@@ -170,12 +174,18 @@ fn disk_usage(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
fn system_usage(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_system_usage;
|
||||
win(ctx, &mut open, "System Usage", vec2(320.0, 140.0), |ui| {
|
||||
ui.label(format!("UI frame time: {:.1} ms", app.frame_ms));
|
||||
ui.label(format!("Audio: {}", app.player.as_ref().map_or("no engine".to_string(), |p| format!("{} @ {} Hz", p.device_name, p.device_rate))));
|
||||
ui.label(crate::localized_format!("UI frame time: {:.1} ms", app.frame_ms));
|
||||
ui.label(crate::localized_format!(
|
||||
"Audio: {}",
|
||||
app.player.as_ref().map_or_else(
|
||||
|| crate::localization::text("No engine").to_owned(),
|
||||
|p| crate::localized_format!("{} @ {} Hz", p.device_name, p.device_rate)
|
||||
)
|
||||
));
|
||||
let plugins: usize = app.engine.session().tracks.iter().map(|t| t.mixer.inserts.iter().flatten().count()).sum();
|
||||
ui.label(format!("Active plugin instances: {plugins}"));
|
||||
ui.label(format!("Tracks: {}", app.engine.session().tracks.len()));
|
||||
ui.label(format!("Undo steps: {}", app.engine.undo_history().len()));
|
||||
ui.label(crate::localized_format!("Active plugin instances: {plugins}", plugins = plugins));
|
||||
ui.label(crate::localized_format!("Tracks: {}", app.engine.session().tracks.len()));
|
||||
ui.label(crate::localized_format!("Undo steps: {}", app.engine.undo_history().len()));
|
||||
});
|
||||
app.ui.show_system_usage = open;
|
||||
}
|
||||
@@ -185,15 +195,17 @@ fn task_manager(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
win(ctx, &mut open, "Task Manager", vec2(320.0, 120.0), |ui| {
|
||||
match &app.bounce {
|
||||
Some(b) => {
|
||||
ui.label(format!("Bouncing {} ({:.0}%)", b.path().display(), b.progress() * 100.0));
|
||||
ui.label(crate::localized_format!("Bouncing {} ({:.0}%)", b.path().display(), b.progress() * 100.0));
|
||||
ui.add(egui::ProgressBar::new(b.progress()));
|
||||
}
|
||||
None => {
|
||||
ui.label("No background tasks are running.");
|
||||
ui.label(crate::localization::text("No background tasks are running."));
|
||||
}
|
||||
}
|
||||
ui.label(
|
||||
egui::RichText::new("Renders and AudioSuite processes run to completion before returning.").small().color(Tokens::current().text_dim),
|
||||
egui::RichText::new(crate::localization::text("Renders and AudioSuite processes run to completion before returning."))
|
||||
.small()
|
||||
.color(Tokens::current().text_dim),
|
||||
);
|
||||
});
|
||||
app.ui.show_task_manager = open;
|
||||
@@ -215,14 +227,14 @@ fn metadata(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
("Markers", s.markers.len().to_string()),
|
||||
("Length", s.format_position(s.content_end(), soundcraft_time::TimeFormat::MinSecs)),
|
||||
] {
|
||||
ui.label(k);
|
||||
ui.label(crate::localization::text(k));
|
||||
ui.label(v);
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
let mut c = s.comments.clone();
|
||||
ui.label("Session comments");
|
||||
ui.label(crate::localization::text("Session comments"));
|
||||
if ui.text_edit_multiline(&mut c).changed() {
|
||||
app.engine.session_mut().comments = c;
|
||||
}
|
||||
@@ -236,7 +248,7 @@ fn event_list(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_event_list;
|
||||
win(ctx, &mut open, "MIDI Event List", vec2(420.0, 360.0), |ui| {
|
||||
let Some(cid) = crate::midi_editor::target_clip(app) else {
|
||||
ui.label("Select a MIDI clip.");
|
||||
ui.label(crate::localization::text("Select a MIDI clip."));
|
||||
return;
|
||||
};
|
||||
let notes = match app.engine.session().find_clip(cid).map(|(_, c)| c.content.clone()) {
|
||||
@@ -246,14 +258,14 @@ fn event_list(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
egui::Grid::new("evl").num_columns(5).striped(true).show(ui, |ui| {
|
||||
for h in ["Start (ticks)", "Note", "Vel", "Length", ""] {
|
||||
ui.label(egui::RichText::new(h).strong());
|
||||
ui.label(egui::RichText::new(crate::localization::text(h)).strong());
|
||||
}
|
||||
ui.end_row();
|
||||
for (i, n) in notes.iter().enumerate() {
|
||||
ui.label(egui::RichText::new(n.start.to_string()).font(mono(11.0)));
|
||||
ui.label(soundcraft_midi::note_name(n.pitch));
|
||||
let mut v = i64::from(n.velocity);
|
||||
if ui.add(egui::DragValue::new(&mut v).range(1..=127)).accessible_name("Note velocity").changed() {
|
||||
if ui.add(egui::DragValue::new(&mut v).range(1..=127)).accessible_name(crate::localization::text("Note velocity")).changed() {
|
||||
let _ = app.engine.execute("midi.note_edit", &json!({"clip": cid.0, "index": i, "velocity": v}));
|
||||
}
|
||||
ui.label(n.length.to_string());
|
||||
@@ -313,7 +325,10 @@ fn midi_keyboard(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let next = s.tempo.tick_to_samples(s.tempo.samples_to_ticks(at, s.sample_rate) + len, s.sample_rate);
|
||||
let _ = app.run("transport.locate", json!({"at": next}));
|
||||
}
|
||||
ui.label(egui::RichText::new("Click keys to step-enter notes into the selected MIDI clip at the insertion point.").small());
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text("Click keys to step-enter notes into the selected MIDI clip at the insertion point."))
|
||||
.small(),
|
||||
);
|
||||
});
|
||||
app.ui.show_midi_keyboard = open;
|
||||
}
|
||||
@@ -323,57 +338,64 @@ fn workspace(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if !open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Workspace").open(&mut open).default_size(vec2(460.0, 420.0)).show(ctx, |ui| {
|
||||
let dir = if app.ui.workspace_dir.is_empty() { std::env::var("HOME").unwrap_or_else(|_| ".".into()) } else { app.ui.workspace_dir.clone() };
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("⬆").on_hover_text("Parent folder").clicked()
|
||||
&& let Some(p) = std::path::Path::new(&dir).parent()
|
||||
{
|
||||
app.ui.workspace_dir = p.to_string_lossy().into_owned();
|
||||
}
|
||||
ui.label(egui::RichText::new(&dir).small());
|
||||
});
|
||||
ui.separator();
|
||||
// Names stay paths: a name that is not valid Unicode is shown lossily, and opening it says so.
|
||||
let mut entries: Vec<(std::path::PathBuf, String, bool)> = std::fs::read_dir(&dir)
|
||||
.map(|rd| {
|
||||
rd.flatten()
|
||||
.filter_map(|e| {
|
||||
let path = e.path();
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if name.starts_with('.') {
|
||||
return None;
|
||||
egui::Window::new(crate::localization::text("Workspace"))
|
||||
.id(egui::Id::unique("Workspace"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(460.0, 420.0))
|
||||
.show(ctx, |ui| {
|
||||
let dir =
|
||||
if app.ui.workspace_dir.is_empty() { std::env::var("HOME").unwrap_or_else(|_| ".".into()) } else { app.ui.workspace_dir.clone() };
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(crate::localization::text("⬆")).on_hover_text(crate::localization::text("Parent folder")).clicked()
|
||||
&& let Some(p) = std::path::Path::new(&dir).parent()
|
||||
{
|
||||
app.ui.workspace_dir = p.to_string_lossy().into_owned();
|
||||
}
|
||||
ui.label(egui::RichText::new(&dir).small());
|
||||
});
|
||||
ui.separator();
|
||||
// Names stay paths: a name that is not valid Unicode is shown lossily, and opening it says so.
|
||||
let mut entries: Vec<(std::path::PathBuf, String, bool)> = std::fs::read_dir(&dir)
|
||||
.map(|rd| {
|
||||
rd.flatten()
|
||||
.filter_map(|e| {
|
||||
let path = e.path();
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if name.starts_with('.') {
|
||||
return None;
|
||||
}
|
||||
let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
|
||||
let ext = path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase();
|
||||
(is_dir
|
||||
|| craft_audio::DECODE_EXTENSIONS.contains(&ext.as_str())
|
||||
|| ["mid", "midi", SESSION_EXTENSION].contains(&ext.as_str()))
|
||||
.then_some((path, name, is_dir))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
entries.sort_by(|a, b| b.2.cmp(&a.2).then(a.1.to_lowercase().cmp(&b.1.to_lowercase())));
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
for (path, name, is_dir) in entries.into_iter().take(2000) {
|
||||
let label = if is_dir { format!("📁 {name}") } else { format!("🔊 {name}") };
|
||||
let r = ui.selectable_label(false, label);
|
||||
if r.double_clicked() {
|
||||
if is_dir {
|
||||
// The folder is kept as text in the preferences.
|
||||
match crate::dialogs::unicode(&path) {
|
||||
Ok(p) => app.ui.workspace_dir = p.to_owned(),
|
||||
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
|
||||
}
|
||||
} else {
|
||||
crate::dialogs::open_path(app, &path);
|
||||
}
|
||||
let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
|
||||
let ext = path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase();
|
||||
(is_dir
|
||||
|| craft_audio::DECODE_EXTENSIONS.contains(&ext.as_str())
|
||||
|| ["mid", "midi", SESSION_EXTENSION].contains(&ext.as_str()))
|
||||
.then_some((path, name, is_dir))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
entries.sort_by(|a, b| b.2.cmp(&a.2).then(a.1.to_lowercase().cmp(&b.1.to_lowercase())));
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
for (path, name, is_dir) in entries.into_iter().take(2000) {
|
||||
let label = if is_dir { format!("📁 {name}") } else { format!("🔊 {name}") };
|
||||
let r = ui.selectable_label(false, label);
|
||||
if r.double_clicked() {
|
||||
if is_dir {
|
||||
// The folder is kept as text in the preferences.
|
||||
match crate::dialogs::unicode(&path) {
|
||||
Ok(p) => app.ui.workspace_dir = p.to_owned(),
|
||||
Err(e) => app.ui.status = e.to_string(),
|
||||
}
|
||||
} else {
|
||||
crate::dialogs::open_path(app, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text("Double-click to import audio/MIDI at the insertion point or open a session.")).small(),
|
||||
);
|
||||
});
|
||||
ui.label(egui::RichText::new("Double-click to import audio/MIDI at the insertion point or open a session.").small());
|
||||
});
|
||||
app.ui.show_workspace = open;
|
||||
}
|
||||
|
||||
@@ -382,7 +404,7 @@ fn workspace(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
fn configurations(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_configurations;
|
||||
win(ctx, &mut open, "Window Configurations", vec2(320.0, 240.0), |ui| {
|
||||
if ui.button("New Configuration…").clicked() {
|
||||
if ui.button(crate::localization::text("New Configuration…")).clicked() {
|
||||
let n = app.ui.configurations.len() + 1;
|
||||
let mut snap = app.ui.clone();
|
||||
snap.configurations.clear();
|
||||
@@ -398,7 +420,7 @@ fn configurations(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if ui.button(format!("{} {name}", i + 1)).clicked()
|
||||
&& let Err(error) = recall_configuration(app, v)
|
||||
{
|
||||
app.ui.status = format!("Window configuration could not be restored: {error}");
|
||||
app.ui.status = crate::localized_format!("Window configuration could not be restored: {error}", error = error);
|
||||
}
|
||||
if crate::widgets::close_button(ui, "Remove configuration").clicked() {
|
||||
app.ui.configurations.remove(i);
|
||||
@@ -418,6 +440,8 @@ 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;
|
||||
// Language is a global preference like the theme: recalling a configuration keeps the current one.
|
||||
st.language = app.ui.language;
|
||||
st.show_preferences = app.ui.show_preferences;
|
||||
st.preferences_page = app.ui.preferences_page;
|
||||
st.preferences_window_pos = app.ui.preferences_window_pos;
|
||||
@@ -458,27 +482,30 @@ fn chosen_device<'a>(devices: &'a [DeviceInfo], name: Option<&str>) -> Option<&'
|
||||
|
||||
/// Device picker with a Default entry and channel counts, labelled for accessibility.
|
||||
fn device_combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut Option<String>, devices: &[DeviceInfo]) {
|
||||
let default = devices.iter().find(|d| d.is_default).map_or("none".to_string(), |d| d.name.clone());
|
||||
let shown = value.clone().unwrap_or_else(|| format!("Default ({default})"));
|
||||
let default = devices.iter().find(|d| d.is_default).map_or_else(|| crate::localization::text("none").to_string(), |d| d.name.clone());
|
||||
let shown = value.clone().unwrap_or_else(|| crate::localized_format!("Default ({default})", default = default));
|
||||
let combo = craft_ui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| {
|
||||
ui.selectable_value(value, None, format!("Default ({default})"));
|
||||
ui.selectable_value(value, None, crate::localized_format!("Default ({default})", default = default));
|
||||
for d in devices {
|
||||
ui.selectable_value(value, Some(d.name.clone()), format!("{} ({} ch)", d.name, d.max_channels));
|
||||
}
|
||||
});
|
||||
combo.response.accessible_name(name);
|
||||
combo.response.accessible_name(crate::localization::text(name));
|
||||
}
|
||||
|
||||
/// Optional-number picker with a Device default entry and a unit, labelled for accessibility.
|
||||
fn number_combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut Option<u32>, options: &[u32], unit: &str) {
|
||||
let shown = value.map_or("Device default".to_string(), |v| format!("{v} {unit}"));
|
||||
let shown = value.map_or_else(
|
||||
|| crate::localization::text("Device default").to_string(),
|
||||
|v| crate::localized_format!("{v} {unit}", v = v, unit = crate::localization::text(unit)),
|
||||
);
|
||||
let combo = craft_ui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| {
|
||||
ui.selectable_value(value, None, "Device default");
|
||||
ui.selectable_value(value, None, crate::localization::text("Device default"));
|
||||
for v in options {
|
||||
ui.selectable_value(value, Some(*v), format!("{v} {unit}"));
|
||||
ui.selectable_value(value, Some(*v), crate::localized_format!("{v} {unit}", v = v, unit = crate::localization::text(unit)));
|
||||
}
|
||||
});
|
||||
combo.response.accessible_name(name);
|
||||
combo.response.accessible_name(crate::localization::text(name));
|
||||
}
|
||||
|
||||
/// Setup › Playback Engine / Hardware: choose the audio system, devices, rate and buffer size.
|
||||
@@ -495,12 +522,12 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
win(ctx, &mut open, "Playback Engine", vec2(460.0, 360.0), |ui| {
|
||||
let t = Tokens::current();
|
||||
egui::Grid::new("pe").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| {
|
||||
let system_label = ui.label("Audio system");
|
||||
let system_label = ui.label(crate::localization::text("Audio system"));
|
||||
let def = systems.iter().find(|s| s.is_default).map_or("none".to_string(), |s| s.name.clone());
|
||||
let shown = draft.system.clone().unwrap_or_else(|| format!("Default ({def})"));
|
||||
let shown = draft.system.clone().unwrap_or_else(|| crate::localized_format!("Default ({default})", default = def));
|
||||
let system = craft_ui::ComboBox::from_id_salt("pe-system").width(300.0).selected_text(shown).show_ui(ui, |ui| {
|
||||
let before = draft.system.clone();
|
||||
ui.selectable_value(&mut draft.system, None, format!("Default ({def})"));
|
||||
ui.selectable_value(&mut draft.system, None, crate::localized_format!("Default ({default})", default = def));
|
||||
for s in systems.iter() {
|
||||
ui.selectable_value(&mut draft.system, Some(s.name.clone()), &s.name);
|
||||
}
|
||||
@@ -513,17 +540,17 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
system.response.labelled_by(system_label.id);
|
||||
ui.end_row();
|
||||
let sys = chosen_system(&systems, &draft);
|
||||
ui.label("Output device");
|
||||
ui.label(crate::localization::text("Output device"));
|
||||
device_combo(ui, "pe-out", "Output device", &mut draft.output, sys.map_or(&[][..], |s| &s.outputs));
|
||||
ui.end_row();
|
||||
ui.label("Input device");
|
||||
ui.label(crate::localization::text("Input device"));
|
||||
device_combo(ui, "pe-in", "Input device", &mut draft.input, sys.map_or(&[][..], |s| &s.inputs));
|
||||
ui.end_row();
|
||||
let out = sys.and_then(|s| chosen_device(&s.outputs, draft.output.as_deref()));
|
||||
ui.label("Sample rate");
|
||||
ui.label(crate::localization::text("Sample rate"));
|
||||
number_combo(ui, "pe-rate", "Sample rate", &mut draft.sample_rate, out.map_or(&[][..], |d| &d.sample_rates), "Hz");
|
||||
ui.end_row();
|
||||
ui.label("Buffer size");
|
||||
ui.label(crate::localization::text("Buffer size"));
|
||||
// The combo lists standard power-of-two sizes. `setup.playback_engine` does not round
|
||||
// onto this list: it keeps any integer 16..=8192, the same as `ui.audio_device`.
|
||||
let buffers = out.map(DeviceInfo::buffer_sizes).unwrap_or_else(|| soundcraft_playback::devices::STANDARD_BUFFERS.to_vec());
|
||||
@@ -532,50 +559,60 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Refresh devices").clicked() {
|
||||
if ui.button(crate::localization::text("Refresh devices")).clicked() {
|
||||
refresh = true;
|
||||
}
|
||||
let changed = draft != app.ui.audio;
|
||||
if ui.add_enabled(changed, egui::Button::new("Apply")).on_hover_text("Reopen the audio devices with these settings").clicked() {
|
||||
if ui
|
||||
.add_enabled(changed, egui::Button::new(crate::localization::text("Apply")))
|
||||
.on_hover_text(crate::localization::text("Reopen the audio devices with these settings"))
|
||||
.clicked()
|
||||
{
|
||||
apply = true;
|
||||
}
|
||||
if changed && ui.button("Revert").clicked() {
|
||||
if changed && ui.button(crate::localization::text("Revert")).clicked() {
|
||||
draft = app.ui.audio.clone();
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
egui::Grid::new("pe-state").num_columns(2).show(ui, |ui| {
|
||||
ui.label("Output");
|
||||
ui.label(app.player.as_ref().map_or("none".to_string(), |p| {
|
||||
ui.label(crate::localization::text("Output"));
|
||||
ui.label(app.player.as_ref().map_or(crate::localization::text("none").to_string(), |p| {
|
||||
if p.silent {
|
||||
"no device (silent clock)".to_string()
|
||||
crate::localization::text("no device (silent clock)").to_string()
|
||||
} else {
|
||||
let buf = p.device_buffer.map_or("default buffer".to_string(), |b| format!("{b} samples"));
|
||||
format!("{} · {} Hz · {} ch · {buf}", p.device_name, p.device_rate, p.device_channels)
|
||||
let buf = p
|
||||
.device_buffer
|
||||
.map_or(crate::localization::text("default buffer").to_string(), |b| crate::localized_format!("{} samples", b));
|
||||
crate::localized_format!("{} · {} Hz · {} ch · {}", p.device_name, p.device_rate, p.device_channels, buf)
|
||||
}
|
||||
}));
|
||||
ui.end_row();
|
||||
ui.label("Input");
|
||||
ui.label(app.recorder.as_ref().map_or("opened on first record or monitor".to_string(), |r| {
|
||||
format!("{} · {} Hz · {} ch", r.device_name, r.sample_rate, r.channels)
|
||||
ui.label(crate::localization::text("Input"));
|
||||
ui.label(app.recorder.as_ref().map_or(crate::localization::text("opened on first record or monitor").to_string(), |r| {
|
||||
crate::localized_format!("{} · {} Hz · {} ch", r.device_name, r.sample_rate, r.channels)
|
||||
}));
|
||||
ui.end_row();
|
||||
ui.label("Session rate");
|
||||
ui.label(crate::localization::text("Session rate"));
|
||||
let sr = app.engine.session().sample_rate.hz();
|
||||
let note = app
|
||||
.player
|
||||
.as_ref()
|
||||
.filter(|p| !p.silent && p.device_rate != sr)
|
||||
.map_or(String::new(), |_| " (resampled to the device rate)".to_string());
|
||||
ui.label(format!("{sr} Hz{note}"));
|
||||
.map_or(String::new(), |_| crate::localization::text(" (resampled to the device rate)").to_string());
|
||||
ui.label(crate::localized_format!("{sr} Hz{note}", sr = sr, note = note));
|
||||
ui.end_row();
|
||||
});
|
||||
ui.label(egui::RichText::new("The mix runs in 512-sample blocks; the buffer size sets the device's own latency.").small().color(t.text_dim));
|
||||
ui.label(
|
||||
egui::RichText::new(crate::localization::text("The mix runs in 512-sample blocks; the buffer size sets the device's own latency."))
|
||||
.small()
|
||||
.color(t.text_dim),
|
||||
);
|
||||
let mut dc = app.engine.session().edit.delay_compensation;
|
||||
if crate::widgets::checkbox(ui, &mut dc, "Delay compensation").changed() {
|
||||
if crate::widgets::checkbox(ui, &mut dc, crate::localization::text("Delay compensation")).changed() {
|
||||
let _ = app.run("options.delay_compensation", json!({"value": dc}));
|
||||
}
|
||||
if ui.button("Reconnect audio device").clicked() {
|
||||
if ui.button(crate::localization::text("Reconnect audio device")).clicked() {
|
||||
app.reconnect_audio();
|
||||
}
|
||||
});
|
||||
@@ -683,46 +720,48 @@ pub fn setup_audio_command(app: &mut SoundApp, id: &str, p: &serde_json::Value)
|
||||
pub fn io_setup(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut open = app.ui.show_io_setup;
|
||||
win(ctx, &mut open, "I/O Setup", vec2(420.0, 300.0), |ui| {
|
||||
ui.label(egui::RichText::new("Busses").strong());
|
||||
ui.label(egui::RichText::new(crate::localization::text("Busses")).strong());
|
||||
let busses: Vec<(String, String)> = app.engine.session().busses.iter().map(|b| (b.name.clone(), b.format.label().to_string())).collect();
|
||||
egui::Grid::new("busses").num_columns(3).striped(true).show(ui, |ui| {
|
||||
for (name, fmt) in busses {
|
||||
let key = egui::Id::unique(("bus_name", name.clone()));
|
||||
let mut edit: String = ui.ctx().memory(|m| m.data.get_temp(key)).unwrap_or_else(|| name.clone());
|
||||
let r = crate::widgets::named_text_field(ui.text_edit_singleline(&mut edit), &format!("Bus name: {name}"));
|
||||
let r =
|
||||
crate::widgets::named_text_field(ui.text_edit_singleline(&mut edit), &crate::localized_format!("Bus name: {name}", name = name));
|
||||
ui.ctx().memory_mut(|m| m.data.insert_temp(key, edit.clone()));
|
||||
if r.lost_focus() && edit != name {
|
||||
let _ = app.run("setup.io", json!({"action": "rename_bus", "name": name, "new_name": edit}));
|
||||
}
|
||||
ui.label(fmt);
|
||||
if ui.small_button("Delete").clicked() {
|
||||
if ui.small_button(crate::localization::text("Delete")).clicked() {
|
||||
let _ = app.run("setup.io", json!({"action": "delete_bus", "name": name}));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if ui.button("New Bus").clicked() {
|
||||
if ui.button(crate::localization::text("New Bus")).clicked() {
|
||||
let n = app.engine.session().busses.len() + 1;
|
||||
let _ = app.run("mix.new_bus", json!({"name": format!("Bus {n}")}));
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new("Outputs").strong());
|
||||
ui.label(egui::RichText::new(crate::localization::text("Outputs")).strong());
|
||||
// Main output format: stereo, or a surround format (the mix and master faders follow).
|
||||
let main = app.engine.session().main_format();
|
||||
ui.horizontal(|ui| {
|
||||
let main_label = ui.label("Main output");
|
||||
let format = craft_ui::ComboBox::from_id_salt("main_output_format").selected_text(main.label()).show_ui(ui, |ui| {
|
||||
for f in soundcraft_model::ChannelFormat::ALL.into_iter().filter(|f| (2..=16).contains(&f.channels())) {
|
||||
if ui.selectable_label(f == main, f.label()).clicked() && f != main {
|
||||
let _ = app.run("setup.main_format", json!({"format": f.label()}));
|
||||
let main_label = ui.label(crate::localization::text("Main output"));
|
||||
let format =
|
||||
craft_ui::ComboBox::from_id_salt("main_output_format").selected_text(crate::localization::text(main.label())).show_ui(ui, |ui| {
|
||||
for f in soundcraft_model::ChannelFormat::ALL.into_iter().filter(|f| (2..=16).contains(&f.channels())) {
|
||||
if ui.selectable_label(f == main, crate::localization::text(f.label())).clicked() && f != main {
|
||||
let _ = app.run("setup.main_format", json!({"format": f.label()}));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
format.response.labelled_by(main_label.id);
|
||||
ui.label(egui::RichText::new(format!("{} ch", main.channels())).small());
|
||||
ui.label(egui::RichText::new(crate::localized_format!("{n} ch", n = main.channels())).small());
|
||||
});
|
||||
for o in app.engine.session().outputs.clone() {
|
||||
ui.label(format!("{} — {} from channel {}", o.name, o.format.label(), o.first_channel + 1));
|
||||
ui.label(crate::localized_format!("{} — {} from channel {}", o.name, o.format.label(), o.first_channel + 1));
|
||||
}
|
||||
});
|
||||
app.ui.show_io_setup = open;
|
||||
@@ -739,8 +778,9 @@ pub fn shortcuts_window(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let windows = crate::menus::UI_COMMANDS.iter().map(|c| (c.3, c.1, c.2.replace(" > ", " › ")));
|
||||
for (shortcut, label, menu) in engine.chain(windows) {
|
||||
let Some(shortcut) = shortcut else { continue };
|
||||
ui.label(egui::RichText::new(crate::shortcuts::shortcut_label(shortcut, mac)).font(mono(11.0)));
|
||||
ui.label(label);
|
||||
ui.label(egui::RichText::new(crate::shortcuts::display_shortcut(shortcut, mac)).font(mono(11.0)));
|
||||
ui.label(crate::localization::text(label));
|
||||
let menu = menu.split(" › ").map(crate::localization::text).collect::<Vec<_>>().join(" › ");
|
||||
ui.label(egui::RichText::new(menu).small());
|
||||
ui.end_row();
|
||||
}
|
||||
@@ -764,20 +804,20 @@ pub fn clip_effects(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.map(|c| c.id)
|
||||
});
|
||||
let Some(cid) = clip else {
|
||||
ui.label("Select an audio clip.");
|
||||
ui.label(crate::localization::text("Select an audio clip."));
|
||||
return;
|
||||
};
|
||||
let name = app.engine.session().find_clip(cid).map(|(_, c)| c.name.clone()).unwrap_or_default();
|
||||
let bypass = app.engine.session().edit.flag(&format!("clip_fx.bypass.{}", cid.0));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(&name).strong());
|
||||
if ui.selectable_label(bypass, "Bypass").clicked() {
|
||||
if ui.selectable_label(bypass, crate::localization::text("Bypass")).clicked() {
|
||||
let _ = app.run("clip.effects_bypass", json!({"clips": [cid.0]}));
|
||||
}
|
||||
if ui.button("Render").clicked() {
|
||||
if ui.button(crate::localization::text("Render")).clicked() {
|
||||
let _ = app.run("clip.effects_render", json!({"clips": [cid.0]}));
|
||||
}
|
||||
if ui.button("Clear").clicked() {
|
||||
if ui.button(crate::localization::text("Clear")).clicked() {
|
||||
let _ = app.run("edit.clear_clip_effects", json!({"clips": [cid.0]}));
|
||||
}
|
||||
});
|
||||
@@ -813,7 +853,10 @@ pub fn clip_effects(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let mut g = get(app, "gain", 0.0);
|
||||
let before = g;
|
||||
let mut wide = f64::from(g);
|
||||
crate::widgets::FineSlider::new(&mut wide, -36.0..=24.0).text("Clip effects gain (dB)").default_value(0.0).show(ui);
|
||||
crate::widgets::FineSlider::new(&mut wide, -36.0..=24.0)
|
||||
.text(crate::localization::text("Clip effects gain (dB)"))
|
||||
.default_value(0.0)
|
||||
.show(ui);
|
||||
g = wide as f32;
|
||||
if (g - before).abs() > f32::EPSILON {
|
||||
let _ =
|
||||
|
||||
@@ -209,12 +209,18 @@ impl Control {
|
||||
|
||||
/// Builds the searchable text from a control's label, value and available choices.
|
||||
fn search_text(self) -> String {
|
||||
let both = bilingual;
|
||||
match self {
|
||||
Self::Choice(label, value) | Self::Value(label, value) => format!("{label} {value}"),
|
||||
Self::ChoiceOptions(label, value, values) => format!("{label} {value} {}", values.join(" ")),
|
||||
Self::Radios(label, values) => format!("{label} {}", values.join(" ")),
|
||||
Self::ReduceVisualEffects => format!("{} Never Only During Playback Always", self.label()),
|
||||
_ => self.label().to_string(),
|
||||
Self::Choice(label, value) | Self::Value(label, value) => format!("{} {}", both(label), both(value)),
|
||||
Self::ChoiceOptions(label, value, values) => {
|
||||
format!("{} {} {}", both(label), both(value), values.iter().map(|value| both(value)).collect::<Vec<_>>().join(" "))
|
||||
}
|
||||
Self::Radios(label, values) => format!("{} {}", both(label), values.iter().map(|value| both(value)).collect::<Vec<_>>().join(" ")),
|
||||
Self::ReduceVisualEffects => {
|
||||
let modes = ReduceVisualEffects::ALL.map(|mode| both(mode.label())).join(" ");
|
||||
format!("{} {modes}", both(self.label()))
|
||||
}
|
||||
_ => both(self.label()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -728,7 +734,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.allocate_exact_size(screen.size(), egui::Sense::click_and_drag());
|
||||
});
|
||||
|
||||
let mut window = egui::Window::new("SoundCraft Preferences")
|
||||
let mut window = egui::Window::new(crate::localization::text("SoundCraft Preferences"))
|
||||
.id(egui::Id::unique("preferences_window"))
|
||||
.open(&mut open)
|
||||
.order(egui::Order::Foreground)
|
||||
@@ -743,13 +749,13 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.horizontal(|ui| {
|
||||
let (icon_rect, _) = ui.allocate_exact_size(vec2(18.0, 18.0), egui::Sense::hover());
|
||||
crate::icons::draw(ui.painter(), icon_rect.shrink(1.0), "zoom", Tokens::current().text_dim);
|
||||
let search_label = ui.label("Search");
|
||||
let search_label = ui.label(crate::localization::text("Search"));
|
||||
let edit = egui::TextEdit::singleline(&mut search)
|
||||
.id(egui::Id::unique("preferences_search"))
|
||||
.hint_text("Type to search preferences")
|
||||
.hint_text(crate::localization::text("Type to search preferences"))
|
||||
.desired_width(f32::INFINITY);
|
||||
ui.add(edit).labelled_by(search_label.id);
|
||||
if !search.is_empty() && ui.small_button("Clear").clicked() {
|
||||
if !search.is_empty() && ui.small_button(crate::localization::text("Clear")).clicked() {
|
||||
search.clear();
|
||||
}
|
||||
});
|
||||
@@ -777,10 +783,10 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ui.available_width() - 176.0);
|
||||
if ui.add_sized([80.0, 24.0], egui::Button::new("Cancel")).clicked() {
|
||||
if ui.add_sized([80.0, 24.0], egui::Button::new(crate::localization::text("Cancel"))).clicked() {
|
||||
action = Some(Action::Cancel);
|
||||
}
|
||||
if ui.add_sized([80.0, 24.0], egui::Button::new("OK").fill(Tokens::current().accent_dark)).clicked() {
|
||||
if ui.add_sized([80.0, 24.0], egui::Button::new(crate::localization::text("OK")).fill(Tokens::current().accent_dark)).clicked() {
|
||||
action = Some(Action::Apply);
|
||||
}
|
||||
});
|
||||
@@ -836,8 +842,11 @@ fn tabs(ui: &mut egui::Ui, page: &mut PreferencesPage, search: &str) {
|
||||
ui.horizontal(|ui| {
|
||||
for candidate in PreferencesPage::ALL {
|
||||
let hit = page_matches(candidate, search);
|
||||
let text =
|
||||
if !search.is_empty() && hit { RichText::new(candidate.label()).color(t.meter_yellow) } else { RichText::new(candidate.label()) };
|
||||
let text = if !search.is_empty() && hit {
|
||||
RichText::new(crate::localization::text(candidate.label())).color(t.meter_yellow)
|
||||
} else {
|
||||
RichText::new(crate::localization::text(candidate.label()))
|
||||
};
|
||||
if ui.selectable_label(*page == candidate, text).clicked() {
|
||||
*page = candidate;
|
||||
}
|
||||
@@ -889,15 +898,15 @@ fn section_ui(ui: &mut egui::Ui, page: PreferencesPage, section: Section, search
|
||||
/// Draws a section's title and border, including search-match highlighting.
|
||||
fn section_frame(ui: &mut egui::Ui, section: Section, search: &str, add_contents: impl FnOnce(&mut egui::Ui)) {
|
||||
let t = Tokens::current();
|
||||
let section_hit = text_matches(section.title, search);
|
||||
let section_hit = text_matches(&bilingual(section.title), search);
|
||||
let stroke = if !search.is_empty() && section_hit { Stroke::new(1.5, t.meter_yellow) } else { Stroke::new(1.0, t.border) };
|
||||
egui::Frame::new().fill(t.panel_bg2).stroke(stroke).corner_radius(3.0).inner_margin(egui::Margin::same(6)).show(ui, |ui| {
|
||||
ui.set_min_width((ui.available_width() - 12.0).max(280.0));
|
||||
egui::Frame::new().fill(t.toolbar_group).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
|
||||
let title = if !search.is_empty() && section_hit {
|
||||
RichText::new(section.title).strong().color(t.meter_yellow)
|
||||
RichText::new(crate::localization::text(section.title)).strong().color(t.meter_yellow)
|
||||
} else {
|
||||
RichText::new(section.title).strong()
|
||||
RichText::new(crate::localization::text(section.title)).strong()
|
||||
};
|
||||
ui.label(title);
|
||||
});
|
||||
@@ -926,23 +935,26 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
|
||||
let t = Tokens::current();
|
||||
let hit = text_matches(&control.search_text(), search);
|
||||
let label = |text: &'static str| {
|
||||
let text = crate::localization::text(text);
|
||||
if !search.is_empty() && hit { RichText::new(text).color(t.meter_yellow) } else { RichText::new(text) }
|
||||
};
|
||||
let id = ("preference", page, section, index);
|
||||
match control {
|
||||
Control::Theme => {
|
||||
craft_ui::ComboBox::new(id, label("UI Theme")).selected_text(draft.theme.label()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::new(id, label("UI Theme")).selected_text(crate::localization::text(draft.theme.label())).show_ui(ui, |ui| {
|
||||
for mode in ThemeMode::ALL {
|
||||
ui.selectable_value(&mut draft.theme, mode, mode.label());
|
||||
ui.selectable_value(&mut draft.theme, mode, crate::localization::text(mode.label()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Control::ReduceVisualEffects => {
|
||||
craft_ui::ComboBox::new(id, label("Reduce Visual Effects")).selected_text(draft.reduce_visual_effects.label()).show_ui(ui, |ui| {
|
||||
for mode in ReduceVisualEffects::ALL {
|
||||
ui.selectable_value(&mut draft.reduce_visual_effects, mode, mode.label());
|
||||
}
|
||||
});
|
||||
craft_ui::ComboBox::new(id, label("Reduce Visual Effects"))
|
||||
.selected_text(crate::localization::text(draft.reduce_visual_effects.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for mode in ReduceVisualEffects::ALL {
|
||||
ui.selectable_value(&mut draft.reduce_visual_effects, mode, crate::localization::text(mode.label()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Control::UndoLevels => {
|
||||
ui.horizontal(|ui| {
|
||||
@@ -952,28 +964,30 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
|
||||
}
|
||||
Control::Check(text) => {
|
||||
let mut value = false;
|
||||
ui.add_enabled(false, egui::Checkbox::new(&mut value, label(text))).on_disabled_hover_text("This preference is not available yet.");
|
||||
ui.add_enabled(false, egui::Checkbox::new(&mut value, label(text)))
|
||||
.on_disabled_hover_text(crate::localization::text("This preference is not available yet."));
|
||||
}
|
||||
Control::Choice(text, value) | Control::ChoiceOptions(text, value, _) => {
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
craft_ui::ComboBox::new(id, label(text)).selected_text(value).show_ui(ui, |_| {});
|
||||
craft_ui::ComboBox::new(id, label(text)).selected_text(crate::localization::text(value)).show_ui(ui, |_| {});
|
||||
})
|
||||
.response
|
||||
.on_disabled_hover_text("This preference is not available yet.");
|
||||
.on_disabled_hover_text(crate::localization::text("This preference is not available yet."));
|
||||
}
|
||||
Control::Value(text, value) => {
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let caption = ui.label(label(text));
|
||||
let mut shown = value.to_string();
|
||||
let mut shown = crate::localization::text(value).to_string();
|
||||
ui.add(egui::TextEdit::singleline(&mut shown).desired_width(96.0)).labelled_by(caption.id);
|
||||
});
|
||||
})
|
||||
.response
|
||||
.on_disabled_hover_text("This preference is not available yet.");
|
||||
.on_disabled_hover_text(crate::localization::text("This preference is not available yet."));
|
||||
}
|
||||
Control::Button(text) => {
|
||||
ui.add_enabled(false, egui::Button::new(label(text))).on_disabled_hover_text("This preference is not available yet.");
|
||||
ui.add_enabled(false, egui::Button::new(label(text)))
|
||||
.on_disabled_hover_text(crate::localization::text("This preference is not available yet."));
|
||||
}
|
||||
Control::Radios(text, values) => {
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
@@ -981,12 +995,12 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
|
||||
let mut selected = 0usize;
|
||||
ui.indent(id, |ui| {
|
||||
for (value_index, value) in values.iter().enumerate() {
|
||||
ui.radio_value(&mut selected, value_index, *value);
|
||||
ui.radio_value(&mut selected, value_index, crate::localization::text(value));
|
||||
}
|
||||
});
|
||||
})
|
||||
.response
|
||||
.on_disabled_hover_text("This preference is not available yet.");
|
||||
.on_disabled_hover_text(crate::localization::text("This preference is not available yet."));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1015,12 +1029,19 @@ fn page_modifiers(modifiers: Modifiers, mac: bool) -> bool {
|
||||
|
||||
/// Reports whether a page title, section or control matches the search terms.
|
||||
fn page_matches(page: PreferencesPage, search: &str) -> bool {
|
||||
text_matches(page.label(), search)
|
||||
text_matches(&bilingual(page.label()), search)
|
||||
|| page.sections().iter().any(|section| {
|
||||
text_matches(section.title, search) || section.controls.iter().copied().any(|control| text_matches(&control.search_text(), search))
|
||||
text_matches(&bilingual(section.title), search)
|
||||
|| section.controls.iter().copied().any(|control| text_matches(&control.search_text(), search))
|
||||
})
|
||||
}
|
||||
|
||||
/// A source string followed by its translation, so a search finds either language.
|
||||
fn bilingual(source: &str) -> String {
|
||||
let translated = crate::localization::text(source);
|
||||
if translated == source { source.to_owned() } else { format!("{source} {translated}") }
|
||||
}
|
||||
|
||||
/// Performs a case-insensitive AND match over whitespace-separated search terms.
|
||||
fn text_matches(text: &str, search: &str) -> bool {
|
||||
let search = search.trim();
|
||||
@@ -1038,6 +1059,50 @@ mod tests {
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use soundcraft_engine::Engine;
|
||||
|
||||
/// Whether a preference value is a plain number or unit amount that needs no translation.
|
||||
fn is_numeric(value: &str) -> bool {
|
||||
value.chars().next().is_none_or(|c| c.is_ascii_digit() || matches!(c, '−' | '-' | '—' | '.' | ' ' | '|'))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preference_text_has_a_portuguese_translation() {
|
||||
let mut missing = Vec::new();
|
||||
let mut check = |text: &str| {
|
||||
if !is_numeric(text) && !crate::localization::has_pt_br_entry(text) {
|
||||
missing.push(text.to_owned());
|
||||
}
|
||||
};
|
||||
for page in PreferencesPage::ALL {
|
||||
check(page.label());
|
||||
for section in page.sections() {
|
||||
check(section.title);
|
||||
for control in section.controls {
|
||||
check(control.label());
|
||||
match *control {
|
||||
Control::Choice(_, value) | Control::Value(_, value) => check(value),
|
||||
Control::ChoiceOptions(_, value, values) => {
|
||||
check(value);
|
||||
values.iter().for_each(|v| check(v));
|
||||
}
|
||||
Control::Radios(_, values) => values.iter().for_each(|v| check(v)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Names that are the same in both languages are listed by the catalog as identity entries.
|
||||
assert!(missing.is_empty(), "preference texts without a pt-BR entry: {missing:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preference_search_matches_both_languages() {
|
||||
let _scope = crate::localization::enter(crate::localization::Language::PortugueseBrazil);
|
||||
let control = Control::Check("Auto Backup");
|
||||
assert!(text_matches(&control.search_text(), crate::localization::Language::PortugueseBrazil.text("Auto Backup")));
|
||||
assert!(text_matches(&control.search_text(), "auto backup"));
|
||||
assert!(!text_matches(&control.search_text(), "mixagem"));
|
||||
}
|
||||
|
||||
/// Creates a complete application harness with Preferences already open.
|
||||
fn preferences_harness(size: egui::Vec2) -> Harness<'static, SoundApp> {
|
||||
let mut app = SoundApp::new(Engine::default(), None, crate::Services::default());
|
||||
|
||||
@@ -150,6 +150,20 @@ fn fixed(app: &mut SoundApp, key: Key, m: Modifiers, mac: bool) -> bool {
|
||||
let _ = app.run("markers.add", json!({}));
|
||||
true
|
||||
}
|
||||
// Pro Tools' Delete (Backspace on a Mac laptop) is Clear, as Edit › Clear (Cmd+B) is. In the
|
||||
// Edit window only (the one actually drawn), and not while the MIDI editor has a valid target
|
||||
// with notes selected: it deletes those.
|
||||
Key::Delete | Key::Backspace if plain && (app.ui.mix_separate || app.ui.window == MainWindow::Edit) => {
|
||||
if crate::panels::midi_editor::target_clip(app).is_none() {
|
||||
// No MIDI target can consume the notes any more: drop the stale selection.
|
||||
app.midi.selected.clear();
|
||||
}
|
||||
if app.ui.show_midi_editor && !app.midi.selected.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let _ = app.run("edit.clear", json!({}));
|
||||
true
|
||||
}
|
||||
// Shift+=/- step the Grid value and Alt+Shift+=/- the Nudge value; macOS sends Alt+Shift+= as =, not +.
|
||||
Key::Plus | Key::Equals | Key::Minus if m.shift && !m.command && !m.ctrl && app.ui.window == MainWindow::Edit => {
|
||||
let step = if key == Key::Minus { -1 } else { 1 };
|
||||
@@ -475,6 +489,20 @@ pub fn shortcut_label(s: &str, mac: bool) -> String {
|
||||
s.split('+').map(|p| if p == "Cmd" { "Ctrl" } else { p }).collect::<Vec<_>>().join("+")
|
||||
}
|
||||
|
||||
/// The label shown for a shortcut: the key names are translated, so "Space" can read as the
|
||||
/// local name of that key.
|
||||
pub fn display_shortcut(s: &str, mac: bool) -> String {
|
||||
shortcut_label(s, mac)
|
||||
.split('+')
|
||||
.map(|part| {
|
||||
let key = format!("key:{part}");
|
||||
let translated = crate::localization::text(&key);
|
||||
if translated == key { part.to_owned() } else { translated.to_owned() }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("+")
|
||||
}
|
||||
|
||||
/// Mac Control chords that `fixed` also maps to Ctrl off macOS.
|
||||
const PC_CTRL_CHORDS: [&str; 4] = ["Ctrl+Up", "Ctrl+Down", "Ctrl+Shift+Up", "Ctrl+Shift+Down"];
|
||||
|
||||
|
||||
@@ -547,9 +547,12 @@ mod tests {
|
||||
fn dark_is_the_default() {
|
||||
assert_eq!(ThemeMode::default(), ThemeMode::Dark);
|
||||
assert_eq!(UiState::default().theme, ThemeMode::Dark);
|
||||
assert_eq!(UiState::default().language, crate::localization::Language::English);
|
||||
// Prefs saved before the setting existed load as Dark.
|
||||
let old: UiState = serde_json::from_value(json!({"show_tracks_list": true})).unwrap_or_default();
|
||||
let old: UiState = serde_json::from_value(json!({"show_tracks_list": false})).unwrap();
|
||||
assert_eq!(old.theme, ThemeMode::Dark);
|
||||
assert_eq!(old.language, crate::localization::Language::English);
|
||||
assert!(!old.show_tracks_list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -582,6 +585,32 @@ mod tests {
|
||||
assert!(crate::menus::UI_COMMANDS.iter().any(|c| c.0 == "ui.theme"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_command_sets_reports_and_validates_the_language() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
assert_eq!(app.run("ui.language", json!({})), Ok(json!({"language": "en"})));
|
||||
assert_eq!(app.run("ui.language", json!({"language": "pt-BR"})), Ok(json!({"language": "pt-BR"})));
|
||||
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
|
||||
assert!(app.run("ui.language", json!({"language": "fr"})).is_err());
|
||||
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
|
||||
assert!(crate::menus::UI_COMMANDS.iter().any(|command| command.0 == "ui.language"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_survives_state_round_trip_and_configuration_recall() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
let _ = app.run("ui.language", json!({"language": "pt-BR"}));
|
||||
let saved = serde_json::to_value(&app.ui).unwrap_or_default();
|
||||
assert_eq!(saved["language"], "pt-BR");
|
||||
let restored: crate::UiState = serde_json::from_value(saved.clone()).unwrap_or_default();
|
||||
assert_eq!(restored.language, crate::localization::Language::PortugueseBrazil);
|
||||
// Language is a global preference like the theme: a saved configuration never changes it.
|
||||
let mut snapshot = saved;
|
||||
snapshot["language"] = json!("en");
|
||||
assert_eq!(crate::panels::windows::recall_configuration(&mut app, &snapshot), Ok(()));
|
||||
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_frames_follow_system_appearance_and_preserve_manual_palettes() {
|
||||
// Mixer rendering tests also change the process-wide custom-painted palette.
|
||||
|
||||
@@ -51,10 +51,13 @@ struct ModeCellState {
|
||||
|
||||
fn edit_mode_tooltip(m: EditMode, locked: bool, cmd: &str, fkey: &str) -> String {
|
||||
match m {
|
||||
EditMode::Shuffle if locked => format!("Shuffle is locked ({cmd}-click to unlock)"),
|
||||
EditMode::Shuffle => format!("Shuffle mode ({fkey}); {cmd}-click locks it out"),
|
||||
EditMode::Grid => format!("Grid mode ({fkey}; again for Relative); Shift-click: Snap to Grid in the other modes"),
|
||||
_ => format!("{} mode ({fkey}); Shift-click adds Snap to Grid", if m == EditMode::Slip { "Slip" } else { "Spot" }),
|
||||
EditMode::Shuffle if locked => crate::localized_format!("Shuffle is locked ({cmd}-click to unlock)", cmd = cmd),
|
||||
EditMode::Shuffle => crate::localized_format!("Shuffle mode ({fkey}); {cmd}-click locks it out", fkey = fkey, cmd = cmd),
|
||||
EditMode::Grid => {
|
||||
crate::localized_format!("Grid mode ({fkey}; again for Relative); Shift-click: Snap to Grid in the other modes", fkey = fkey)
|
||||
}
|
||||
EditMode::Slip => crate::localized_format!("Slip mode ({fkey}); Shift-click adds Snap to Grid", fkey = fkey),
|
||||
_ => crate::localized_format!("Spot mode ({fkey}); Shift-click adds Snap to Grid", fkey = fkey),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +75,7 @@ fn draw_mode_cell(p: &egui::Painter, cell: Rect, resp: &egui::Response, t: &Toke
|
||||
icons::draw(p, Rect::from_center_size(cell.center(), vec2(15.0, 15.0)), "lock", fg);
|
||||
} else {
|
||||
let txt = if m == EditMode::Grid && state.cur == EditMode::GridRelative { "REL GRID" } else { label };
|
||||
p.text(cell.center(), Align2::CENTER_CENTER, txt, bold(10.5), fg);
|
||||
p.text(cell.center(), Align2::CENTER_CENTER, crate::localization::text(txt), bold(10.5), fg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,8 +91,12 @@ fn edit_modes(app: &mut SoundApp, ui: &mut Ui) {
|
||||
(EditMode::Slip, 0, 1, "SLIP", "F2"),
|
||||
(EditMode::Grid, 1, 1, "GRID", "F4"),
|
||||
];
|
||||
let widest =
|
||||
modes.iter().map(|m| m.3).chain(["REL GRID"]).map(|l| ui.painter().layout_no_wrap(l.into(), bold(10.5), t.text).size().x).fold(0.0, f32::max);
|
||||
let widest = modes
|
||||
.iter()
|
||||
.map(|m| m.3)
|
||||
.chain(["REL GRID"])
|
||||
.map(|l| ui.painter().layout_no_wrap(crate::localization::text(l).into(), bold(10.5), t.text).size().x)
|
||||
.fold(0.0, f32::max);
|
||||
group(ui, 2.0 * widest + 44.0, 52.0, |ui, r| {
|
||||
let inner = r.shrink(6.0);
|
||||
let cw = inner.width() / 2.0;
|
||||
@@ -156,7 +163,7 @@ fn zoom_group(app: &mut SoundApp, ui: &mut Ui) {
|
||||
&i.to_string(),
|
||||
false,
|
||||
Color32::GRAY,
|
||||
"Zoom preset (click to recall, Cmd-click to store)",
|
||||
crate::localization::text("Zoom preset (click to recall, Cmd-click to store)"),
|
||||
);
|
||||
if r.clicked() {
|
||||
let store = ui.input(|x| x.modifiers.command);
|
||||
@@ -189,7 +196,7 @@ fn tools(app: &mut SoundApp, ui: &mut Ui) {
|
||||
(Tool::Pencil, "pencil"),
|
||||
] {
|
||||
let smart_member = cur == Tool::Smart && matches!(tool, Tool::Trim | Tool::Selector | Tool::Grabber);
|
||||
let tip = format!("{}{}", tool.label(), tool.fkey().map(|k| format!(" ({k})")).unwrap_or_default());
|
||||
let tip = format!("{}{}", crate::localization::text(tool.label()), tool.fkey().map(|k| format!(" ({k})")).unwrap_or_default());
|
||||
if icon_button(ui, vec2(36.0, 26.0), icon, cur == tool || smart_member, &tip).clicked() {
|
||||
let _ = app.run("edit.tool", json!({"tool": tool.id()}));
|
||||
}
|
||||
@@ -202,7 +209,7 @@ fn tools(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let bracket = Rect::from_min_max(pos2(bx0 - 2.0, r.min.y + 1.0), pos2(bx1 + 2.0, r.min.y + 5.0));
|
||||
let resp = ui.interact(bracket.expand2(vec2(0.0, 2.0)), ui.scope_id().with("smart"), Sense::click());
|
||||
ui.painter().rect_filled(bracket, 1.0, if cur == Tool::Smart { t.accent } else { t.tool_bracket_off });
|
||||
if resp.on_hover_text("Smart Tool (F6+F7 / F7+F8)").clicked() {
|
||||
if resp.on_hover_text(crate::localization::text("Smart Tool (F6+F7 / F7+F8)")).clicked() {
|
||||
let _ = app.run("edit.tool", json!({"tool": "smart"}));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
@@ -214,7 +221,15 @@ fn tools(app: &mut SoundApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
let focus = e.keyboard_focus == "commands";
|
||||
if crate::widgets::text_toggle(ui, vec2(36.0, 18.0), "a-z", focus, t.accent, "Commands Keyboard Focus (single-key editing)").clicked()
|
||||
if crate::widgets::text_toggle(
|
||||
ui,
|
||||
vec2(36.0, 18.0),
|
||||
"a-z",
|
||||
focus,
|
||||
t.accent,
|
||||
crate::localization::text("Commands Keyboard Focus (single-key editing)"),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
let _ = app.run("options.keyboard_focus", json!({}));
|
||||
}
|
||||
@@ -265,13 +280,13 @@ fn counters(app: &mut SoundApp, ui: &mut Ui) {
|
||||
];
|
||||
for (i, (label, val)) in rows.iter().enumerate() {
|
||||
let y = r.min.y + 10.0 + i as f32 * 13.0;
|
||||
ui.painter().text(pos2(r.min.x + 214.0, y), Align2::RIGHT_CENTER, *label, regular(11.0), t.counter_label);
|
||||
ui.painter().text(pos2(r.min.x + 214.0, y), Align2::RIGHT_CENTER, crate::localization::text(label), regular(11.0), t.counter_label);
|
||||
ui.painter().text(pos2(r.max.x - 8.0, y), Align2::RIGHT_CENTER, val, mono(11.0), t.counter_text);
|
||||
}
|
||||
// Sub counter row.
|
||||
let y = r.max.y - 11.0;
|
||||
ui.painter().line_segment([pos2(r.min.x + 6.0, r.max.y - 21.0), pos2(r.max.x - 6.0, r.max.y - 21.0)], Stroke::new(1.0, t.counter_rule));
|
||||
ui.painter().text(pos2(r.min.x + 10.0, y), Align2::LEFT_CENTER, "Sub", regular(11.0), t.counter_label);
|
||||
ui.painter().text(pos2(r.min.x + 10.0, y), Align2::LEFT_CENTER, crate::localization::text("Sub"), regular(11.0), t.counter_label);
|
||||
ui.painter().text(pos2(r.min.x + 150.0, y), Align2::RIGHT_CENTER, fmt_pos(app, pos, sub_fmt), mono(11.0), t.counter_text);
|
||||
let sub_r = Rect::from_min_max(pos2(r.min.x + 6.0, r.max.y - 20.0), pos2(r.min.x + 164.0, r.max.y - 2.0));
|
||||
let sub_resp = ui.interact(sub_r, ui.scope_id().with("sub_counter"), Sense::click());
|
||||
@@ -279,7 +294,13 @@ fn counters(app: &mut SoundApp, ui: &mut Ui) {
|
||||
format_menu(app, &sub_resp, sub_fmt, "view.sub_counter");
|
||||
let st = if app.engine.is_dirty() { "modified" } else { "saved" };
|
||||
let dev = app.player.as_ref().map_or("no audio engine", |p| if p.silent { "silent clock" } else { "audio on" });
|
||||
ui.painter().text(pos2(r.max.x - 8.0, y), Align2::RIGHT_CENTER, format!("{st} · {dev}"), regular(10.0), t.text_dim);
|
||||
ui.painter().text(
|
||||
pos2(r.max.x - 8.0, y),
|
||||
Align2::RIGHT_CENTER,
|
||||
format!("{} · {}", crate::localization::text(st), crate::localization::text(dev)),
|
||||
regular(10.0),
|
||||
t.text_dim,
|
||||
);
|
||||
}
|
||||
|
||||
/// A counter's time-format menu: picking a format runs `command` (`view.main_counter` or
|
||||
@@ -287,7 +308,7 @@ fn counters(app: &mut SoundApp, ui: &mut Ui) {
|
||||
fn format_menu(app: &mut SoundApp, resp: &egui::Response, current: TimeFormat, command: &str) {
|
||||
egui::Popup::menu(resp).show(|ui| {
|
||||
for f in TimeFormat::ALL {
|
||||
if ui.selectable_label(current == f, f.label()).clicked() {
|
||||
if ui.selectable_label(current == f, crate::localization::text(f.label())).clicked() {
|
||||
let _ = app.run(command, json!({"format": f.id()}));
|
||||
}
|
||||
}
|
||||
@@ -306,8 +327,14 @@ fn grid_nudge(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let gl = Rect::from_min_size(pos2(r.min.x + 6.0, r.min.y + 8.0), vec2(48.0, 16.0));
|
||||
let resp = ui.interact(gl, ui.scope_id().with("grid_lines"), Sense::click());
|
||||
key(ui.painter(), gl, &resp, if lines { t.mode_on } else { t.counter_off });
|
||||
ui.painter().text(gl.center(), Align2::CENTER_CENTER, "Grid", bold(11.0), if lines { t.mode_on_text } else { t.mode_off_text });
|
||||
if resp.on_hover_text("Show grid lines").clicked() {
|
||||
ui.painter().text(
|
||||
gl.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
crate::localization::text("Grid"),
|
||||
bold(11.0),
|
||||
if lines { t.mode_on_text } else { t.mode_off_text },
|
||||
);
|
||||
if resp.on_hover_text(crate::localization::text("Show grid lines")).clicked() {
|
||||
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));
|
||||
@@ -315,10 +342,10 @@ fn grid_nudge(app: &mut SoundApp, ui: &mut Ui) {
|
||||
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);
|
||||
ui.painter().text(pos2(gr.max.x - 14.0, gr.center().y), Align2::RIGHT_CENTER, crate::localization::text(&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", 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);
|
||||
ui.painter().text(pos2(r.min.x + 10.0, r.min.y + 44.0), Align2::LEFT_CENTER, crate::localization::text("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));
|
||||
draw_compact_note_icon(ui.painter(), nr, nudge, t.counter_text);
|
||||
ui.painter().text(
|
||||
@@ -508,17 +535,17 @@ fn value_menu(app: &mut SoundApp, resp: &egui::Response, cmd: &str, current: Gri
|
||||
ui.separator();
|
||||
for scale in GridScale::TIME {
|
||||
let selected = !clips_markers && current.scale() == scale;
|
||||
if ui.selectable_label(selected, scale.label()).clicked() {
|
||||
if ui.selectable_label(selected, crate::localization::text(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() {
|
||||
if allow_clips && ui.selectable_label(clips_markers, crate::localization::text(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() {
|
||||
if ui.selectable_label(follow_main, crate::localization::text("Follow Main Time Scale")).clicked() {
|
||||
let _ = app.run(cmd, json!({"follow_main": !follow_main}));
|
||||
ui.close();
|
||||
}
|
||||
@@ -527,7 +554,7 @@ fn value_menu(app: &mut SoundApp, resp: &egui::Response, cmd: &str, current: Gri
|
||||
|
||||
/// 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() {
|
||||
if ui.selectable_label(selected, crate::localization::text(label)).clicked() {
|
||||
let _ = app.run(cmd, json!({"value": value}));
|
||||
ui.close();
|
||||
}
|
||||
@@ -567,20 +594,20 @@ fn transport(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(38.0, 28.0), Sense::click());
|
||||
key(ui.painter(), r, &resp, key_fill(&resp));
|
||||
icons::draw(ui.painter(), r.shrink(5.0), "stop", if playing { t.text } else { t.accent });
|
||||
if resp.on_hover_text("Stop (Space)").clicked() {
|
||||
if resp.on_hover_text(crate::localization::text("Stop (Space)")).clicked() {
|
||||
let _ = app.run("transport.stop", json!({}));
|
||||
}
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(38.0, 28.0), Sense::click());
|
||||
key(ui.painter(), r, &resp, if playing { Color32::from_rgb(40, 90, 50) } else { key_fill(&resp) });
|
||||
icons::draw(ui.painter(), r.shrink(5.0), "play", if playing { Color32::from_rgb(120, 255, 140) } else { t.counter_text });
|
||||
if resp.on_hover_text("Play (Space)").clicked() {
|
||||
if resp.on_hover_text(crate::localization::text("Play (Space)")).clicked() {
|
||||
let _ = app.run("transport.play", json!({}));
|
||||
}
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(38.0, 28.0), Sense::click());
|
||||
key(ui.painter(), r, &resp, if recording { Color32::from_rgb(110, 30, 30) } else { key_fill(&resp) });
|
||||
icons::draw(ui.painter(), r.shrink(5.0), "record", t.rec);
|
||||
// macOS gives Cmd+Space to Spotlight unless the user frees it, so name F12 first.
|
||||
let resp = resp.on_hover_text("Record (F12 or Cmd+Space)");
|
||||
let resp = resp.on_hover_text(crate::localization::text("Record (F12 or Cmd+Space)"));
|
||||
if let Some(why) = app.record_hint() {
|
||||
// Below the whole group, so the hint covers none of its buttons.
|
||||
let below = Rect::from_min_max(r.min, pos2(r.max.x, g.max.y));
|
||||
@@ -621,19 +648,31 @@ fn tempo_meter(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let co = Rect::from_min_size(pos2(r.min.x + 6.0, r.min.y + 6.0), vec2(64.0, 15.0));
|
||||
let resp = ui.interact(co, ui.scope_id().with("countoff"), Sense::click());
|
||||
key(ui.painter(), co, &resp, if countoff { t.mode_on } else { t.counter_off });
|
||||
ui.painter().text(co.center(), Align2::CENTER_CENTER, "Count Off", bold(10.0), if countoff { t.mode_on_text } else { t.mode_off_text });
|
||||
ui.painter().text(
|
||||
co.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
crate::localization::text("Count Off"),
|
||||
bold(10.0),
|
||||
if countoff { t.mode_on_text } else { t.mode_off_text },
|
||||
);
|
||||
if resp.clicked() {
|
||||
let _ = app.run("options.countoff", json!({}));
|
||||
}
|
||||
ui.painter().text(pos2(r.max.x - 8.0, co.center().y), Align2::RIGHT_CENTER, format!("{bars} bars"), mono(11.0), t.counter_text);
|
||||
ui.painter().text(pos2(r.min.x + 70.0, r.min.y + 32.0), Align2::RIGHT_CENTER, "Meter", regular(11.0), t.counter_label);
|
||||
ui.painter().text(
|
||||
pos2(r.max.x - 8.0, co.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
crate::localized_format!("{bars} bars", bars = bars),
|
||||
mono(11.0),
|
||||
t.counter_text,
|
||||
);
|
||||
ui.painter().text(pos2(r.min.x + 70.0, r.min.y + 32.0), Align2::RIGHT_CENTER, crate::localization::text("Meter"), regular(11.0), t.counter_label);
|
||||
ui.painter().text(pos2(r.max.x - 8.0, r.min.y + 32.0), Align2::RIGHT_CENTER, meter, mono(11.0), t.counter_text);
|
||||
ui.painter().text(pos2(r.min.x + 70.0, r.min.y + 48.0), Align2::RIGHT_CENTER, "Tempo", regular(11.0), t.counter_label);
|
||||
ui.painter().text(pos2(r.min.x + 70.0, r.min.y + 48.0), Align2::RIGHT_CENTER, crate::localization::text("Tempo"), regular(11.0), t.counter_label);
|
||||
icons::draw(ui.painter(), Rect::from_center_size(pos2(r.min.x + 82.0, r.min.y + 48.0), vec2(13.0, 13.0)), "note", t.counter_text);
|
||||
tempo_value(app, ui, r.max.x - 8.0, r.min.y + 48.0, bpm);
|
||||
let clk = Rect::from_min_size(pos2(r.min.x + 6.0, r.min.y + 40.0), vec2(18.0, 18.0));
|
||||
icons::draw(ui.painter(), clk, "click", if click { t.counter_text } else { t.text_dim });
|
||||
if ui.interact(clk, ui.scope_id().with("click"), Sense::click()).on_hover_text("Click").clicked() {
|
||||
if ui.interact(clk, ui.scope_id().with("click"), Sense::click()).on_hover_text(crate::localization::text("Click")).clicked() {
|
||||
let _ = app.run("options.click", json!({}));
|
||||
}
|
||||
}
|
||||
@@ -654,8 +693,9 @@ fn tempo_value(app: &mut SoundApp, ui: &mut Ui, right: f32, y: f32, bpm: f64) {
|
||||
}
|
||||
v.widgets.hovered.bg_stroke = Stroke::new(1.0, t.counter_border);
|
||||
let mut value = bpm;
|
||||
let resp =
|
||||
c.add_sized(rect.size(), egui::DragValue::new(&mut value).speed(0.1).range(5.0..=1000.0).fixed_decimals(4)).accessible_name("Tempo (BPM)");
|
||||
let resp = c
|
||||
.add_sized(rect.size(), egui::DragValue::new(&mut value).speed(0.1).range(5.0..=1000.0).fixed_decimals(4))
|
||||
.accessible_name(crate::localization::text("Tempo (BPM)"));
|
||||
if resp.changed() {
|
||||
let s = app.engine.session();
|
||||
let tick = s.tempo.samples_to_ticks(app.position(), s.sample_rate);
|
||||
@@ -666,7 +706,7 @@ fn tempo_value(app: &mut SoundApp, ui: &mut Ui, right: f32, y: f32, bpm: f64) {
|
||||
if resp.drag_stopped() || resp.lost_focus() {
|
||||
app.engine.end_merge();
|
||||
}
|
||||
resp.on_hover_text("Drag to change the tempo (Shift: fine steps), or click to type it");
|
||||
resp.on_hover_text(crate::localization::text("Drag to change the tempo (Shift: fine steps), or click to type it"));
|
||||
}
|
||||
|
||||
/// Draws the compact stereo main-output meter.
|
||||
|
||||
@@ -115,13 +115,14 @@ pub(crate) fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
if app.updates_rt.manual_window_open {
|
||||
let mut open = true;
|
||||
egui::Window::new("Check for Updates")
|
||||
egui::Window::new(crate::localization::text("Check for Updates"))
|
||||
.id(egui::Id::unique("Check for Updates"))
|
||||
.open(&mut open)
|
||||
.resizable(false)
|
||||
.collapsible(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
|
||||
.show(ctx, |ui| {
|
||||
ui.label("Update check is not supported in the web browser.");
|
||||
ui.label(crate::localization::text("Update check is not supported in the web browser."));
|
||||
});
|
||||
app.updates_rt.manual_window_open = open;
|
||||
}
|
||||
|
||||
@@ -452,20 +452,44 @@ pub fn draw_lane(app: &mut SoundApp, painter: &Painter, s: &Session, track: &Tra
|
||||
}
|
||||
let p = painter.with_clip_rect(vis);
|
||||
let Some(v) = s.video(source) else {
|
||||
p.text(vis.center(), egui::Align2::CENTER_CENTER, "movie missing from session", regular(10.0), Color32::from_rgb(220, 120, 120));
|
||||
p.text(
|
||||
vis.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
crate::localization::text("movie missing from session"),
|
||||
regular(10.0),
|
||||
Color32::from_rgb(220, 120, 120),
|
||||
);
|
||||
break 'thumbs;
|
||||
};
|
||||
if !on {
|
||||
p.text(vis.center(), egui::Align2::CENTER_CENTER, "Video Track Offline", regular(10.0), Color32::from_gray(170));
|
||||
p.text(
|
||||
vis.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
crate::localization::text("Video Track Offline"),
|
||||
regular(10.0),
|
||||
Color32::from_gray(170),
|
||||
);
|
||||
break 'thumbs;
|
||||
}
|
||||
if let Some(why) = &v.offline {
|
||||
p.text(vis.center(), egui::Align2::CENTER_CENTER, format!("media offline: {why}"), regular(10.0), Color32::from_rgb(220, 120, 120));
|
||||
p.text(
|
||||
vis.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
crate::localized_format!("media offline: {why}", why = crate::localization::text(why)),
|
||||
regular(10.0),
|
||||
Color32::from_rgb(220, 120, 120),
|
||||
);
|
||||
break 'thumbs;
|
||||
}
|
||||
let key = MovieKey::new(source, &v.path);
|
||||
if let Some(Err(e)) = app.video.info(key) {
|
||||
p.text(vis.center(), egui::Align2::CENTER_CENTER, format!("media offline: {e}"), regular(10.0), Color32::from_rgb(220, 120, 120));
|
||||
p.text(
|
||||
vis.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
crate::localized_format!("media offline: {e}", e = crate::localization::text(e)),
|
||||
regular(10.0),
|
||||
Color32::from_rgb(220, 120, 120),
|
||||
);
|
||||
break 'thumbs;
|
||||
}
|
||||
let aspect = app.video.info(key).and_then(|i| i.as_ref().ok()).map_or(v.aspect(), MovieInfo::display_aspect) as f32;
|
||||
|
||||
@@ -118,6 +118,7 @@ pub(crate) fn named_text_field(resp: egui::Response, name: &str) -> egui::Respon
|
||||
/// A toolbar button with an icon; `on` draws the blue selected state.
|
||||
pub fn icon_button(ui: &mut Ui, size: egui::Vec2, icon: &str, on: bool, tip: &str) -> Response {
|
||||
let t = Tokens::current();
|
||||
let tip = crate::localization::text(tip);
|
||||
let style = button_style(t.accent, t.text, 3);
|
||||
let resp = IconButton::new(tip, size, &style).selected(on).single_shape_frame().show(ui, |ui, r, tint| {
|
||||
key_light(ui.painter(), r.shrink(1.0));
|
||||
@@ -134,6 +135,7 @@ pub fn icon_button(ui: &mut Ui, size: egui::Vec2, icon: &str, on: bool, tip: &st
|
||||
/// the accessible name and the tooltip.
|
||||
pub fn close_button(ui: &mut Ui, label: &str) -> Response {
|
||||
let t = Tokens::current();
|
||||
let label = crate::localization::text(label);
|
||||
let size = Vec2::splat(ui.spacing().interact_size.y.max(14.0));
|
||||
let style = IconButtonStyle {
|
||||
normal: ButtonVisuals { fill: Color32::TRANSPARENT, stroke: Stroke::NONE, icon: t.text_dim },
|
||||
@@ -204,12 +206,15 @@ pub(crate) struct SelectorLabels<'a> {
|
||||
/// published separately in the accessibility tree.
|
||||
pub(crate) fn selector_box_named(ui: &mut Ui, width: f32, height: f32, text: &str, color: Color32, labels: SelectorLabels<'_>) -> Response {
|
||||
let t = Tokens::current();
|
||||
// `text` and `value` can be user-defined route or group names (a bus called "Read"), so they
|
||||
// are shown unchanged. Callers pass every label already translated.
|
||||
let SelectorLabels { name, value, tooltip } = labels;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click());
|
||||
// The compact visible text can be an abbreviation ("t/l"); the full meaning on hover is the
|
||||
// accessible name, not the tooltip. `current_text_value` tells a screen reader the selection.
|
||||
resp.widget_info(|| {
|
||||
let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), labels.name);
|
||||
info.current_text_value = Some(labels.value.to_string());
|
||||
let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), name);
|
||||
info.current_text_value = Some(value.to_string());
|
||||
info
|
||||
});
|
||||
key(ui.painter(), r, &resp, key_fill(&resp));
|
||||
@@ -223,7 +228,7 @@ pub(crate) fn selector_box_named(ui: &mut Ui, width: f32, height: f32, text: &st
|
||||
let galley = ui.painter().layout_job(job);
|
||||
let pos = text_rect.center() - galley.size() * 0.5;
|
||||
ui.painter().with_clip_rect(r.shrink(1.0)).galley(pos, galley, color);
|
||||
resp.on_hover_text(labels.tooltip)
|
||||
resp.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
/// Rotary knob for pan / send pan (-1..1). Drag vertically; double-click resets.
|
||||
@@ -675,7 +680,7 @@ pub fn surround_panner(ui: &mut Ui, size: f32, speakers: &[PannerSpeaker], puck:
|
||||
painter.circle(pp, 5.0 + div * half, Color32::from_rgba_unmultiplied(80, 160, 230, 28), Stroke::new(1.0, Color32::from_rgb(70, 130, 190)));
|
||||
}
|
||||
painter.circle(pp, 5.0, t.counter_text, Stroke::new(1.0, Color32::BLACK));
|
||||
let tip = "Surround pan: drag the puck · double-click: front centre · Alt-drag: divergence";
|
||||
let tip = crate::localization::text("Surround pan: drag the puck · double-click: front centre · Alt-drag: divergence");
|
||||
let _ = resp.on_hover_text(tip);
|
||||
// Sliders below: divergence, then elevation for height formats.
|
||||
let mut sliders: Vec<(&str, f32, u8)> = vec![("div", div, 0)];
|
||||
@@ -701,7 +706,8 @@ pub fn surround_panner(ui: &mut Ui, size: f32, speakers: &[PannerSpeaker], puck:
|
||||
if sresp.double_clicked() {
|
||||
edit = Some(if kind == 0 { PannerEdit::Divergence(0.0) } else { PannerEdit::Height(0.0) });
|
||||
}
|
||||
let _ = sresp.on_hover_text(if kind == 0 { "Divergence (0 = point source)" } else { "Elevation (height speakers)" });
|
||||
let _ =
|
||||
sresp.on_hover_text(crate::localization::text(if kind == 0 { "Divergence (0 = point source)" } else { "Elevation (height speakers)" }));
|
||||
}
|
||||
edit
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Delete and Backspace clear the edit selection, as Pro Tools' Delete key does (Edit › Clear is Cmd+B).
|
||||
|
||||
use egui::os::OperatingSystem;
|
||||
use egui::{Event, Key, Modifiers, RawInput, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, shortcuts};
|
||||
|
||||
fn press(ctx: &egui::Context, app: &mut SoundApp, key: Key, modifiers: Modifiers) {
|
||||
let presses = [true, false].map(|pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers });
|
||||
let events = [Event::ModifiersChanged(modifiers)].into_iter().chain(presses).collect();
|
||||
ctx.run_ui(RawInput { events, ..Default::default() }, |ui| shortcuts::handle(app, ui.ctx())).textures_delta.clear();
|
||||
}
|
||||
|
||||
fn rig(os: OperatingSystem) -> (egui::Context, SoundApp) {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_os(os);
|
||||
(ctx, SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default()))
|
||||
}
|
||||
|
||||
fn clips(app: &SoundApp, track: &str) -> usize {
|
||||
app.engine.session().track_by_name(track).and_then(|t| t.playlist()).map_or(0, |p| p.clips.len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_and_backspace_clear_the_edit_selection() {
|
||||
for os in [OperatingSystem::Mac, OperatingSystem::Windows, OperatingSystem::Nix] {
|
||||
for key in [Key::Delete, Key::Backspace] {
|
||||
let (ctx, mut app) = rig(os);
|
||||
let before = clips(&app, "Kick");
|
||||
assert!(before > 0);
|
||||
let end: i64 = 48_000 * 600;
|
||||
app.run("edit.select", json!({"tracks": ["Kick"], "start": 0, "end": end})).unwrap();
|
||||
press(&ctx, &mut app, key, Modifiers::NONE);
|
||||
assert_eq!(clips(&app, "Kick"), 0, "{os:?} {key:?}");
|
||||
// One Undo brings it back, like the menu item.
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(clips(&app, "Kick"), before, "{os:?} {key:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_with_nothing_selected_or_in_the_mix_window_changes_nothing() {
|
||||
let (ctx, mut app) = rig(OperatingSystem::Nix);
|
||||
let before = app.engine.session().clone();
|
||||
press(&ctx, &mut app, Key::Delete, Modifiers::NONE);
|
||||
assert!(*app.engine.session() == before, "no selection");
|
||||
let end: i64 = 48_000 * 600;
|
||||
app.run("edit.select", json!({"tracks": ["Kick"], "start": 0, "end": end})).unwrap();
|
||||
app.run("window.toggle_mix_edit", json!({})).unwrap();
|
||||
let selected = app.engine.session().clone();
|
||||
press(&ctx, &mut app, Key::Delete, Modifiers::NONE);
|
||||
assert!(*app.engine.session() == selected, "the Mix window leaves the edit selection alone");
|
||||
// Modified Delete is not Clear.
|
||||
app.run("window.toggle_mix_edit", json!({})).unwrap();
|
||||
press(&ctx, &mut app, Key::Delete, Modifiers::SHIFT);
|
||||
assert!(*app.engine.session() == selected, "Shift+Delete");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_midi_editor_keeps_the_key_for_its_selected_notes() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
app.ui.show_midi_editor = true;
|
||||
let end: i64 = 48_000 * 600;
|
||||
app.run("edit.select", json!({"tracks": ["Keys"], "start": 0, "end": end})).unwrap();
|
||||
let clips_before = clips(&app, "Keys");
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..3 {
|
||||
h.step();
|
||||
}
|
||||
h.state_mut().midi.selected = vec![0, 1];
|
||||
h.input_mut().events.push(Event::Key { key: Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
assert!(h.state().midi.selected.is_empty(), "the notes were deleted");
|
||||
assert_eq!(clips(h.state(), "Keys"), clips_before, "and the clip was not cleared with them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_and_backspace_clear_after_midi_notes_then_an_audio_range_is_selected() {
|
||||
for key in [Key::Delete, Key::Backspace] {
|
||||
let (ctx, mut app) = rig(OperatingSystem::Nix);
|
||||
app.ui.show_midi_editor = true;
|
||||
let end: i64 = 48_000 * 600;
|
||||
app.run("edit.select", json!({"tracks": ["Keys"], "start": 0, "end": end})).unwrap();
|
||||
app.midi.selected = vec![0, 1];
|
||||
app.run("edit.select", json!({"tracks": ["Kick"], "start": 0, "end": end})).unwrap();
|
||||
assert!(clips(&app, "Kick") > 0);
|
||||
press(&ctx, &mut app, key, Modifiers::NONE);
|
||||
assert_eq!(clips(&app, "Kick"), 0, "{key:?}");
|
||||
assert!(app.midi.selected.is_empty(), "{key:?} drops the stale note selection");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_and_backspace_clear_in_the_edit_window_drawn_beside_a_separate_mix_window() {
|
||||
for key in [Key::Delete, Key::Backspace] {
|
||||
let (ctx, mut app) = rig(OperatingSystem::Nix);
|
||||
app.ui.mix_separate = true;
|
||||
app.ui.window = soundcraft_ui_egui::MainWindow::Mix;
|
||||
let end: i64 = 48_000 * 600;
|
||||
app.run("edit.select", json!({"tracks": ["Kick"], "start": 0, "end": end})).unwrap();
|
||||
press(&ctx, &mut app, key, Modifiers::NONE);
|
||||
assert_eq!(clips(&app, "Kick"), 0, "{key:?}");
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ fn harness(track: &str, height: &str, view: &str) -> (Harness<'static, SoundApp>
|
||||
|
||||
#[test]
|
||||
fn header_keys_freeze_silence_and_show_automation() {
|
||||
let (mut h, _, row) = harness("Kick", "medium", "view.edit_io");
|
||||
let (mut h, kick_id, row) = harness("Kick", "medium", "view.edit_io");
|
||||
let at = |x: f32, y: f32| pos2(row[0] + x, row[1] + y);
|
||||
|
||||
click(&mut h, at(23.5, 65.5));
|
||||
@@ -83,8 +83,10 @@ fn header_keys_freeze_silence_and_show_automation() {
|
||||
click(&mut h, at(7.5, row[3] - row[1] - 7.5));
|
||||
assert_eq!(kick(&h).view, "volume");
|
||||
|
||||
// The fader button beside the Output selector opens Kick's Output window (#1392).
|
||||
click(&mut h, at(HEADER_W + 81.5, 29.5));
|
||||
assert_eq!(h.state().ui.window, MainWindow::Mix);
|
||||
assert_eq!(h.state().ui.output_window, Some(kick_id));
|
||||
assert_eq!(h.state().ui.window, MainWindow::Edit);
|
||||
}
|
||||
|
||||
/// From the Edit window's insert column, clicking a plugin opens it, Cmd-click bypasses it, right-click changes or
|
||||
|
||||
@@ -18,7 +18,6 @@ craft-media.workspace = true
|
||||
craft-video.workspace = true
|
||||
thiserror.workspace = true
|
||||
serde.workspace = true
|
||||
image = { workspace = true, features = ["jpeg"] }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest.workspace = true
|
||||
|
||||
+29
-14
@@ -418,20 +418,14 @@ impl Movie {
|
||||
Ok(Frame { width: f.width, height: f.height, rgba, index, time })
|
||||
}
|
||||
Codec::Jpeg => {
|
||||
// The frame's own size, from its header, before a pixel is decoded: a frame may differ from
|
||||
// the track's size (as before), but not exceed `MAX_PIXELS`.
|
||||
let reader = image::ImageReader::with_format(std::io::Cursor::new(&data), image::ImageFormat::Jpeg);
|
||||
let (w, h) = reader.into_dimensions().map_err(|e| VideoError::Decode(e.to_string()))?;
|
||||
if u64::from(w) * u64::from(h) > MAX_PIXELS {
|
||||
return Err(VideoError::Decode("picture too large".into()));
|
||||
}
|
||||
let img = image::load_from_memory_with_format(&data, image::ImageFormat::Jpeg).map_err(|e| VideoError::Decode(e.to_string()))?;
|
||||
let rgba = img.to_rgba8();
|
||||
let (width, height) = rgba.dimensions();
|
||||
if u64::from(width) * u64::from(height) > MAX_PIXELS {
|
||||
return Err(VideoError::Decode("picture too large".into()));
|
||||
}
|
||||
Ok(Frame { width, height, rgba: rgba.into_raw(), index, time })
|
||||
// The frame's own size is checked from its header before a pixel is decoded: a frame may
|
||||
// differ from the track's size (as before), but not exceed `MAX_PIXELS`.
|
||||
let decoded = craft_video::mjpeg::Decoder::new().max_pixels(MAX_PIXELS).decode(&data).map_err(|e| match e {
|
||||
craft_video::mjpeg::Error::Limit(_) => VideoError::Decode("picture too large".into()),
|
||||
e => VideoError::Decode(e.to_string()),
|
||||
})?;
|
||||
let rgba = mjpeg_rgba(&decoded)?;
|
||||
Ok(Frame { width: decoded.width, height: decoded.height, rgba, index, time })
|
||||
}
|
||||
_ => Err(VideoError::Unsupported("not an intra-frame codec".into())),
|
||||
}
|
||||
@@ -563,3 +557,24 @@ impl Movie {
|
||||
Err(VideoError::Decode(last_err.unwrap_or_else(|| format!("frame {index} was not produced"))))
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoded Motion JPEG picture as RGBA8: grey is spread over R, G and B, and 12-bit samples
|
||||
/// (scaled to 16 bits by the decoder) keep their top 8 bits.
|
||||
pub(crate) fn mjpeg_rgba(frame: &craft_video::mjpeg::Frame) -> Result<Vec<u8>> {
|
||||
let channels = usize::from(frame.channels);
|
||||
if channels != 1 && channels != 3 {
|
||||
return Err(VideoError::Decode(format!("{channels}-channel Motion JPEG picture")));
|
||||
}
|
||||
let samples: Vec<u8> = match &frame.samples {
|
||||
craft_video::mjpeg::Samples::U8(p) => p.clone(),
|
||||
craft_video::mjpeg::Samples::U16(p) => p.iter().map(|&v| (v >> 8) as u8).collect(),
|
||||
};
|
||||
Ok(samples
|
||||
.chunks_exact(channels)
|
||||
.flat_map(|px| match *px {
|
||||
[g] => [g, g, g, 255],
|
||||
[r, g, b] => [r, g, b, 255],
|
||||
_ => [0, 0, 0, 255],
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Tiny synthetic movies, generated in code (for tests, demos and screenshots; nothing binary is
|
||||
//! committed). H.264 pictures are made of I_PCM macroblocks, so their decoded samples are known
|
||||
//! exactly; ProRes comes from the bundled encoder and Motion JPEG from the `image` encoder. All
|
||||
//! exactly; ProRes comes from the bundled encoder and Motion JPEG from craft-video's `mjpeg` encoder. All
|
||||
//! are muxed with the bundled MP4/MOV writer.
|
||||
|
||||
use crate::bitstream::{BitWriter, escape_rbsp};
|
||||
@@ -174,10 +174,10 @@ pub fn mjpeg_mov(n: usize) -> Result<Vec<u8>> {
|
||||
let (w, h) = (32u32, 24u32);
|
||||
let mut mw = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).map_err(err)?;
|
||||
let t = mw.add_track(TrackConfig::new(SampleEntry::jpeg(w as u16, h as u16), 10)).map_err(err)?;
|
||||
let encoder = craft_video::mjpeg::Encoder::new(craft_video::mjpeg::EncoderConfig { quality: 95, ..Default::default() }).map_err(err)?;
|
||||
for i in 0..n.min(10_000) {
|
||||
let img = image::RgbImage::from_pixel(w, h, image::Rgb([(30 * (i % 9)) as u8; 3]));
|
||||
let mut jpg = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95).encode_image(&img).map_err(err)?;
|
||||
let pixels = vec![(30 * (i % 9)) as u8; (w * h * 3) as usize];
|
||||
let jpg = encoder.encode(w, h, 3, &pixels).map_err(err)?;
|
||||
mw.write_sample(t, WriteSample { data: &jpg, duration: 1, composition_offset: 0, is_sync: true }).map_err(err)?;
|
||||
}
|
||||
Ok(mw.finish().map_err(err)?.into_inner())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Movie tests on fixtures generated in process (no binary fixtures): H.264 made of I_PCM
|
||||
//! macroblocks (exact, known colours), ProRes from the bundled encoder and Motion JPEG from the
|
||||
//! `image` encoder, muxed with the bundled MP4/MOV writer. When `ffmpeg` with libx264 is on PATH,
|
||||
//! macroblocks (exact, known colours), ProRes from the bundled encoder and Motion JPEG from craft-video's
|
||||
//! `mjpeg` encoder, muxed with the bundled MP4/MOV writer. When `ffmpeg` with libx264 is on PATH,
|
||||
//! real High-profile streams with B-frames are checked too (skipped otherwise).
|
||||
|
||||
use crate::isobmff::{Brand, ByteSource, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
|
||||
@@ -345,3 +345,26 @@ fn test_pattern_moves() {
|
||||
let f17 = m.frame_at(17.5 / 24.0).unwrap();
|
||||
assert_eq!(white_x(&f17), Some(17));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mjpeg_grey_twelve_bit_and_odd_channel_pictures_map_to_rgba() {
|
||||
use craft_video::mjpeg::{Frame as Jpeg, Samples};
|
||||
let grey = Jpeg { width: 2, height: 1, channels: 1, samples: Samples::U8(vec![7, 200]), damaged: false };
|
||||
assert_eq!(crate::movie::mjpeg_rgba(&grey).unwrap(), [7, 7, 7, 255, 200, 200, 200, 255]);
|
||||
// 12-bit samples arrive scaled to 16 bits; the top 8 bits are kept.
|
||||
let deep = Jpeg { width: 1, height: 1, channels: 3, samples: Samples::U16(vec![0xFFFF, 0x8000, 0x00FF]), damaged: false };
|
||||
assert_eq!(crate::movie::mjpeg_rgba(&deep).unwrap(), [255, 128, 0, 255]);
|
||||
let odd = Jpeg { width: 1, height: 1, channels: 2, samples: Samples::U8(vec![1, 2]), damaged: false };
|
||||
assert!(matches!(crate::movie::mjpeg_rgba(&odd), Err(VideoError::Decode(e)) if e.contains("2-channel")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grey_mjpeg_packets_decode_through_the_shared_decoder() {
|
||||
// A one-channel packet, as some cameras write, decodes to equal R, G and B.
|
||||
let enc = craft_video::mjpeg::Encoder::new(craft_video::mjpeg::EncoderConfig { quality: 95, ..Default::default() }).unwrap();
|
||||
let packet = enc.encode(16, 8, 1, &[90; 16 * 8]).unwrap();
|
||||
let frame = craft_video::mjpeg::Decoder::new().decode(&packet).unwrap();
|
||||
let rgba = crate::movie::mjpeg_rgba(&frame).unwrap();
|
||||
assert_eq!(rgba.len(), 16 * 8 * 4);
|
||||
assert!(rgba.as_chunks::<4>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2] && p[0].abs_diff(90) <= 2 && p[3] == 255));
|
||||
}
|
||||
|
||||
@@ -27,6 +27,12 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
# The X11 editor host window on Linux and the BSDs (a top-level window the plugin view embeds
|
||||
# into) and the view's run loop (polling the descriptors plugins register).
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
x11rb = "0.13"
|
||||
libc = "0.2"
|
||||
|
||||
[[test]]
|
||||
name = "editor_main_thread"
|
||||
harness = false
|
||||
|
||||
@@ -36,6 +36,12 @@ mod host;
|
||||
mod instance;
|
||||
mod module;
|
||||
mod process;
|
||||
/// The `Linux::IRunLoop` a view gets through its frame. X11 plugin editors have no event loop of
|
||||
/// their own: they register their display connection's file descriptor and their repaint timers
|
||||
/// here, and the host calls them back on the main thread. SoundCraft drives this from the editor
|
||||
/// link's `idle`, once per UI frame (the UI repaints at least every 30 ms while an editor is open).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod run_loop;
|
||||
|
||||
pub(crate) use editor::EditorLink;
|
||||
pub(crate) use host::HostContext;
|
||||
@@ -116,8 +122,17 @@ mod window;
|
||||
#[path = "ffi/window/windows.rs"]
|
||||
mod window;
|
||||
|
||||
/// The X11 host window (Linux and the BSDs): a top-level window on our own connection to the X
|
||||
/// server (XWayland on Wayland desktops) whose id the plugin view embeds its window into. The
|
||||
/// close button only hides it (`WM_DELETE_WINDOW`); the editor link notices in `idle`, detaches
|
||||
/// the view, then destroys the window. Our connection's events are read whenever a window's
|
||||
/// visibility is asked, which the UI does every frame while an editor is open.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[path = "ffi/window/x11.rs"]
|
||||
mod window;
|
||||
|
||||
/// Other platforms: no editor windows yet (opening reports "unsupported").
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
#[cfg(not(any(target_os = "macos", windows, unix)))]
|
||||
#[path = "ffi/window/other.rs"]
|
||||
mod window;
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user