Compare commits

...
Author SHA1 Message Date
NetterSilver 248f0e4e25 Edit window: the Delete and Backspace keys clear the selection (#404) (#480)
- Edit window: the Delete and Backspace keys clear the selection (#404)
- Docs: update the progress docs for this change
- Docs: put the new sentence in the Status column
- fix: Delete/Backspace follow the drawn Edit window and a valid MIDI target
2026-11-18 16:36:33 +07:00
FredApps dc21f5ee10 Merge pull request #1472 from ljkx/feat/output-window
Edit window: the Output fader button opens a floating Output window (#1392)
2026-11-18 16:36:13 +07:00
FredApps 0c85e784d2 Merge pull request #533 from ayozetr/linux-plugin-editors
Plugin editor windows on Linux (VST3 and embedded CLAP, X11)
2026-11-18 16:36:01 +07:00
lucasegen 8ee63dc695 Let a soloed VCA solo its members (#800)
Use the effective solo state of active VCA members consistently in the mixer and implied-mute display. Preserve aux/output and send-return routing, empty-VCA behavior, Solo Safe and inactive-track semantics. Add VCA member, empty-master, aux-output, send-return and inactive-source regressions.
2026-11-17 22:13:46 -06:00
Dylan M. Taylor b47a58653c Merge pull request #1607 from storytold/chore/score-merged-pin
chore(score): pin writers to merged shared revision
2026-11-17 03:19:04 -05:00
Dylan M. Taylor 19acf6f21a chore(score): pin writers to merged shared revision 2026-11-17 02:19:12 -05:00
Dylan M. Taylor 16bd7327f3 docs: prefer craft-libs for reusable formats, codecs, protocols and UI (#1592) 2026-11-16 21:59:50 -05:00
Dylan M. Taylor 9676d492db refactor(score): use shared MusicXML and SVG writers with contributor tie fixes (#1598) 2026-11-16 21:59:45 -05:00
Ayoze Torres 63dfe72b1f Merge remote-tracking branch 'upstream/main' into linux-plugin-editors
# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
#	docs/roadmap.md
2026-11-17 02:30:21 +00:00
ljkx aba1cdcdfc Merge remote-tracking branch 'origin/main' into feat/output-window
The Edit window's output fader button now goes through main's UI localization: its
"Output window" tooltip uses crate::localization::text, with a pt-BR catalog entry.
2026-11-16 03:22:47 +01:00
Ayoze Torres 244dcd7767 Merge upstream main into linux-plugin-editors 2026-11-14 12:00:04 +00:00
ljkx cd743a8d59 Merge remote-tracking branch 'origin/main' into feat/output-window
Conflicts: mix_window.rs keeps main's surround_panned (the same check as this branch's surround_out), which the Output window now calls; edit_window/header.rs imports both Gesture (main) and StrokeKind (this branch).
2026-11-13 11:17:58 +01:00
ljkx 33917ea79a Output window: Close Window and Hide All Floating Windows close it
The shared window.close / window.hide_floating path clears it along with
the other floating windows.
2026-11-13 05:36:04 +01:00
ljkx 8a5647ab49 Output window: opening another session closes it and drops its draft
document_replaced now closes the Output window: a track of the new session
can have the id of the old one's track, and the window would show it. The
volume and pan readouts' ids also name the document, so a value typed for
the old session's track is not reused for a track of the new one.
2026-11-13 05:36:03 +01:00
Ayoze Torres 8ddda478fd Merge upstream main into linux-plugin-editors 2026-11-13 02:38:13 +00:00
ljkx 35cc20c457 ui: strip_scan_running returns the cfg'd value directly
Newer clippy rejects an if guard that returns a bool literal and is
followed by another (crates/ui-egui/src/dialogs.rs:118), which fails
the gate on current stable for every branch based on main.
2026-11-13 01:04:58 +01:00
ljkx ae5ec2ee54 Merge remote-tracking branch 'upstream/main' into feat/output-window 2026-11-13 01:04:11 +01:00
Ayoze Torres 7236035284 Merge upstream main into linux-plugin-editors 2026-11-12 21:47:05 +00:00
ljkx 3cc12a0758 Output window: the volume and pan readouts' ids include the track (#1392)
The window's id is the same for every track, so the readouts' ids were too.
A value being typed for one track stayed open when the window switched to
another track, and Enter then set that track instead. The ids now include
the track's id, as the Send window's per-slot ids do.

New test: a value typed into Kick's volume readout is not carried over when
the window shows Snare, and Enter there leaves Snare's volume alone. It
fails without the fix (Snare goes to -20 dB).
2026-11-12 20:15:22 +01:00
ljkx 976ea150b7 Output window: typed volume and pan join the strip's merge keys; update the header test (#1392)
A typed value in the Output window went through app.run, so during an
automation pass it became its own undo step. It now uses the strip's
merge keys (fader:<id>, pan:<id>:<i>), as a drag does.

header_keys_freeze_silence_and_show_automation clicked the Output fader
button and expected the Mix window; it now expects Kick's Output window.
2026-11-09 15:24:23 +01:00
ljkx 9506ad6039 Edit window: the Output fader button opens a floating Output window (#1392)
The fader button beside a track's Output selector selected the track and
switched to the Mix window. As in Pro Tools, it now opens a floating
Output window for that track, modelled on the Send window: the output
destination, Solo and Mute, the pan knobs, the volume fader and an
editable dB readout, running the strip's own commands and merge keys.
Clicking the button again, Escape, the close button or deleting the track
closes it.
2026-11-09 15:03:04 +01:00
ayozetr 2a45435254 Merge main into linux-plugin-editors 2026-11-03 22:14:41 +00:00
ayozetr cca413bd32 Merge main into linux-plugin-editors
# Conflicts:
#	ROADMAP.md
2026-11-01 17:39:04 +00:00
Ayoze Torres 60fbbcb4e5 Run-loop tests: take t0 before registering the timers
A timer's first tick is set at registration, so taking the reference
time afterwards made the "not due yet" check depend on the test thread
not stalling for a timer period (1 ms in the CLAP test). Same pattern
fixed in the VST3 test.
2026-10-30 01:57:25 +00:00
Ayoze Torres c3f51a6030 docs: plugin editors on Linux
plugin-parity: VST3 editors are hosted on every desktop platform, and
embedded CLAP editors on Windows and Linux/X11. gaps: G-05 shrinks to
the macOS work (AU views, embedded CLAP, the entitlement), 10-15 h.
roadmap and ROADMAP: the same estimate, the mix row's VST3 windows, and
a progress log entry.
2026-10-30 01:57:25 +00:00
Ayoze Torres d06bd91ff6 clap-host: host embedded plugin editors on Linux (X11)
CLAP plugins that only offer an embedded editor now get a host window on
Linux and the BSDs too (ffi/hostwin/x11.rs): create(x11, false),
get_size, set_parent with a top-level X11 window of ours (XWayland on
Wayland desktops), show. request_resize is applied by the editor's idle
as on Windows, and closing the window destroys the GUI, then the window.
Host windows now hand over their own clap_window_handle; the X11 id goes
in as a c_ulong, which is 32 bits on 32-bit Unix.

X11 editors rely on the host's event loop, so the host now offers
clap.timer-support and clap.posix-fd-support there (ffi/run_loop.rs).
Registrations are kept per instance and serviced by the editor's idle on
the main thread (ready descriptors, then due timers; a late frame fires
each timer once). They are dropped when the instance goes. Floating X11
editors benefit from them as well.

New Linux/BSD-only dependencies: x11rb and libc, as in vst3-host.
2026-10-30 01:57:25 +00:00
Ayoze Torres d3331784ee vst3-host: host plugin editors on Linux (X11)
VST3 editors now open on Linux and the BSDs. The view is embedded
(kPlatformTypeX11EmbedWindowID) into a top-level X11 window on our own
connection to the X server (ffi/window/x11.rs), which is XWayland on
Wayland desktops. It is sized from getSize, resized on
IPlugFrame::resizeView, and the close button only hides it; the editor
link's idle then detaches the view and destroys the window, as on macOS
and Windows.

X11 editors have no event loop of their own, so the frame is also the
view's Linux::IRunLoop (ffi/run_loop.rs): plugins register their display
connection's descriptor and their repaint timers, and the editor link's
idle (once per UI frame) calls back the ready descriptors and due
timers. Without it JUCE editors open but never repaint. Registrations
are dropped on teardown and when attaching fails, and removed handlers
are released after the run loop's lock, since a plugin destructor may
call back into it.

New Linux/BSD-only dependencies: x11rb (pure Rust, already in the
lockfile through winit) and libc for the zero-timeout poll.
2026-10-30 01:57:25 +00:00
43 changed files with 1923 additions and 469 deletions
+4
View File
@@ -150,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
+24 -1
View File
@@ -1245,6 +1245,14 @@ dependencies = [
"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"
@@ -1328,6 +1336,16 @@ dependencies = [
"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"
@@ -4804,12 +4822,14 @@ name = "soundcraft-clap-host"
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]]
@@ -4847,8 +4867,9 @@ version = "0.20.1"
dependencies = [
"craft-audio",
"craft-docpath",
"craft-score",
"craft-scraft-format",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
"log",
"proptest",
"serde",
@@ -4966,6 +4987,7 @@ dependencies = [
name = "soundcraft-vst3-host"
version = "0.20.1"
dependencies = [
"libc",
"libloading 0.9.0",
"log",
"objc2 0.6.5",
@@ -4976,6 +4998,7 @@ dependencies = [
"thiserror 2.0.21",
"vst3",
"windows-sys 0.61.2",
"x11rb",
]
[[package]]
+1
View File
@@ -11,6 +11,7 @@ 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
+6 -2
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
> **Last reviewed:** 2026-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-10-27 · **Change:** trivial (plugin editors on Linux/X11; previously 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
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
@@ -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,7 @@ mutated and truncated movies. Field reports from the first public week are track
## Progress log
- **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.
@@ -181,6 +182,7 @@ mutated and truncated movies. Field reports from the first public week are track
| Date | Change | Summary |
|---|---|---|
| 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 |
@@ -204,6 +206,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) |
+6
View File
@@ -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
+23 -2
View File
@@ -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;
+15 -1
View File
@@ -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)
+46 -4
View File
@@ -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) };
}
}
}
}
}
+75 -1
View File
@@ -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))
}
+3 -2
View File
@@ -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.
+170
View File
@@ -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();
}
+192
View File
@@ -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]);
}
}
}
+5 -3
View File
@@ -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`.
+1
View File
@@ -8,6 +8,7 @@ rust-version.workspace = true
repository.workspace = true
[dependencies]
craft-score.workspace = true
craft-xml.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
+175 -416
View File
@@ -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,354 +267,120 @@ 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 {
// Keep the score export's existing literal whitespace and quote spelling. The
// shared attribute writer owns XML legality/escaping; only its generated
// whitespace references are restored (input ampersands were escaped first).
craft_xml::esc_attr(s).replace("&#9;", "\t").replace("&#10;", "\n").replace("&#13;", "\r")
}
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)], &notes);
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 shared_xml_escaping_preserves_score_bytes() {
let input = "<&>\"'\t\n\r\0\u{1f}\u{fffe}\u{ffff}é𝄞&#9;&#10;&#13;";
assert_eq!(xml_escape(input), "&lt;&amp;&gt;&quot;'\t\n\ré𝄞&amp;#9;&amp;#10;&amp;#13;");
assert_eq!(xml_escape(""), "");
assert_eq!(xml_escape("Already &amp; escaped"), "Already &amp;amp; escaped");
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)], &notes);
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]
@@ -623,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.
@@ -642,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]
@@ -661,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]
+3 -2
View File
@@ -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);
+27 -1
View File
@@ -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)]
+2 -2
View File
@@ -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);
+96
View File
@@ -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);
+1
View File
@@ -178,6 +178,7 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
"Original Time Stamp" => "Registro de data e hora original",
"Output" => "Saída",
"Output device" => "Dispositivo de saída",
"Output window" => "Janela de saída",
"OK" => "OK",
"Outputs" => "Saídas",
"Pan" => "Panorama",
+3
View File
@@ -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
+13 -6
View File
@@ -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,
@@ -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),
@@ -603,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);
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);
if fresp.on_hover_text(crate::localization::text("Show in the Mix window")).clicked() {
let _ = app.run("edit.select", json!({"tracks": [id.0]}));
let _ = app.run("window.mix", json!({}));
// 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))) {
+4
View File
@@ -103,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,
@@ -180,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,
+1
View File
@@ -757,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!({})
}
+2
View File
@@ -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)]
+325
View File
@@ -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");
}
}
}
+1
View File
@@ -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);
}
+14
View File
@@ -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 };
+113
View File
@@ -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
+6
View File
@@ -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
+16 -1
View File
@@ -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;
+207 -3
View File
@@ -1,4 +1,6 @@
use super::instance::Instance;
#[cfg(all(unix, not(target_os = "macos")))]
use super::run_loop;
use super::{
Class, ComPtr, ComWrapper, IComponentTrait, IEditControllerTrait, IPlugFrameTrait, IPlugViewTrait, Mutex, Ordering, PoisonError, STATE_MAGIC,
c_void, ok, read_c16, sb, sv, window,
@@ -6,16 +8,69 @@ use super::{
// ---- editor (IPlugView) --------------------------------------------------------------------
/// The `IPlugFrame` handed to a plugin view: `resizeView` resizes our host window.
/// The `IPlugFrame` handed to a plugin view: `resizeView` resizes our host window. On X11 it is
/// also the view's `Linux::IRunLoop` (plugins query the frame for it).
pub(crate) struct PlugFrame {
/// The host window (an `NSWindow*` on macOS), not owned; null when there is none.
/// The host window (an `NSWindow*` on macOS, the X11 window id on Linux), not owned; null
/// when there is none.
window: std::sync::atomic::AtomicPtr<c_void>,
#[cfg(all(unix, not(target_os = "macos")))]
run_loop: run_loop::RunLoop,
}
impl PlugFrame {
fn new(window: *mut c_void) -> PlugFrame {
PlugFrame {
window: std::sync::atomic::AtomicPtr::new(window),
#[cfg(all(unix, not(target_os = "macos")))]
run_loop: run_loop::RunLoop::default(),
}
}
/// Services the view's run loop (X11 only): ready file descriptors and due timers.
fn dispatch(&self) {
#[cfg(all(unix, not(target_os = "macos")))]
self.run_loop.dispatch(std::time::Instant::now());
}
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
impl Class for PlugFrame {
type Interfaces = (sb::IPlugFrame,);
}
#[cfg(all(unix, not(target_os = "macos")))]
impl Class for PlugFrame {
type Interfaces = (sb::IPlugFrame, sb::Linux::IRunLoop);
}
#[cfg(all(unix, not(target_os = "macos")))]
impl sb::Linux::IRunLoopTrait for PlugFrame {
unsafe fn registerEventHandler(&self, handler: *mut sb::Linux::IEventHandler, fd: sb::Linux::FileDescriptor) -> sb::tresult {
// SAFETY: in-pointer from the plugin (or null, handled); we take our own reference.
match unsafe { vst3::ComRef::from_raw(handler) } {
Some(h) if self.run_loop.add_fd(h.to_com_ptr(), fd) => sb::kResultOk,
_ => sb::kInvalidArgument,
}
}
unsafe fn unregisterEventHandler(&self, handler: *mut sb::Linux::IEventHandler) -> sb::tresult {
if self.run_loop.remove_fd(handler) { sb::kResultOk } else { sb::kInvalidArgument }
}
unsafe fn registerTimer(&self, handler: *mut sb::Linux::ITimerHandler, milliseconds: sb::Linux::TimerInterval) -> sb::tresult {
// SAFETY: as in `registerEventHandler`.
match unsafe { vst3::ComRef::from_raw(handler) } {
Some(h) if self.run_loop.add_timer(h.to_com_ptr(), milliseconds) => sb::kResultOk,
_ => sb::kInvalidArgument,
}
}
unsafe fn unregisterTimer(&self, handler: *mut sb::Linux::ITimerHandler) -> sb::tresult {
if self.run_loop.remove_timer(handler) { sb::kResultOk } else { sb::kInvalidArgument }
}
}
impl IPlugFrameTrait for PlugFrame {
unsafe fn resizeView(&self, view: *mut sb::IPlugView, new_size: *mut sb::ViewRect) -> sb::tresult {
// SAFETY: in-pointer from the plugin (or null, handled).
@@ -121,7 +176,7 @@ impl EditorLink {
unsafe { view.getSize(&mut r) };
let (w, h) = rect_size(&r);
let win = window::HostWindow::new(title, w, h)?;
let frame = ComWrapper::new(PlugFrame { window: std::sync::atomic::AtomicPtr::new(win.raw()) });
let frame = ComWrapper::new(PlugFrame::new(win.raw()));
if let Some(f) = frame.as_com_ref::<sb::IPlugFrame>() {
// SAFETY: valid view; the frame outlives the view's attachment (kept in `g.frame`
// and detached in `teardown`).
@@ -131,6 +186,9 @@ impl EditorLink {
if !ok(unsafe { view.attached(win.parent(), platform) }) {
// SAFETY: valid view; detach our frame again.
unsafe { view.setFrame(std::ptr::null_mut()) };
// Release anything it registered while attaching, as `teardown` does.
#[cfg(all(unix, not(target_os = "macos")))]
frame.run_loop.clear();
win.close();
return Err("the editor could not attach to its window".into());
}
@@ -150,6 +208,11 @@ impl EditorLink {
view.setFrame(std::ptr::null_mut());
}
}
// Release the view's run-loop handlers even if the plugin still holds the frame.
#[cfg(all(unix, not(target_os = "macos")))]
if let Some(f) = &g.frame {
f.run_loop.clear();
}
g.frame = None;
if let Some(w) = g.window.take() {
w.close();
@@ -215,6 +278,8 @@ impl EditorLink {
let mut g = self.lock();
if g.window.as_ref().is_some_and(|w| !w.is_visible()) {
EditorLink::teardown(&mut g);
} else if let Some(f) = &g.frame {
f.dispatch();
}
}
@@ -292,3 +357,142 @@ impl EditorLink {
leaked
}
}
/// The run loop is X11-only, and so are its tests.
#[cfg(all(test, unix, not(target_os = "macos")))]
mod tests {
use super::*;
/// A plugin-side handler for the run-loop test: counts its callbacks.
#[derive(Default)]
struct Ticks {
timer: std::sync::atomic::AtomicU32,
fd: std::sync::atomic::AtomicU32,
}
impl Class for Ticks {
type Interfaces = (sb::Linux::ITimerHandler, sb::Linux::IEventHandler);
}
impl sb::Linux::ITimerHandlerTrait for Ticks {
unsafe fn onTimer(&self) {
self.timer.fetch_add(1, Ordering::Relaxed);
}
}
impl sb::Linux::IEventHandlerTrait for Ticks {
unsafe fn onFDIsSet(&self, _fd: sb::Linux::FileDescriptor) {
self.fd.fetch_add(1, Ordering::Relaxed);
}
}
#[test]
fn the_run_loop_fires_due_timers_and_ready_descriptors() {
use sb::Linux::IRunLoopTrait;
use std::time::{Duration, Instant};
let frame = ComWrapper::new(PlugFrame::new(std::ptr::null_mut()));
let rl = frame.as_com_ref::<sb::Linux::IRunLoop>().expect("the frame is the view's run loop");
let ticks = ComWrapper::new(Ticks::default());
let timer = ticks.as_com_ref::<sb::Linux::ITimerHandler>().unwrap().as_ptr();
let handler = ticks.as_com_ref::<sb::Linux::IEventHandler>().unwrap().as_ptr();
// Before registering: every timer's first tick is then later than `t0`.
let t0 = Instant::now();
let mut fds = [0; 2];
// SAFETY: `fds` holds the two descriptors `pipe` writes.
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
// SAFETY: test calls through our own implementation with live handler objects.
unsafe {
assert_eq!(rl.registerTimer(timer, 10), sb::kResultOk);
assert_eq!(rl.registerEventHandler(handler, fds[0]), sb::kResultOk);
assert_ne!(rl.registerEventHandler(handler, -1), sb::kResultOk);
assert_ne!(rl.registerTimer(std::ptr::null_mut(), 10), sb::kResultOk);
}
frame.run_loop.dispatch(t0);
assert_eq!(ticks.timer.load(Ordering::Relaxed), 0, "not due yet");
assert_eq!(ticks.fd.load(Ordering::Relaxed), 0, "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);
frame.run_loop.dispatch(t0 + Duration::from_secs(1));
assert_eq!(ticks.timer.load(Ordering::Relaxed), 1, "a late frame fires once, not once per missed period");
assert_eq!(ticks.fd.load(Ordering::Relaxed), 1);
// SAFETY: as above.
unsafe {
assert_eq!(rl.unregisterTimer(timer), sb::kResultOk);
assert_ne!(rl.unregisterTimer(timer), sb::kResultOk, "already gone");
assert_eq!(rl.unregisterEventHandler(handler), sb::kResultOk);
}
frame.run_loop.dispatch(t0 + Duration::from_secs(2));
assert_eq!((ticks.timer.load(Ordering::Relaxed), ticks.fd.load(Ordering::Relaxed)), (1, 1), "unregistered handlers stay quiet");
// SAFETY: as above.
unsafe { assert_eq!(rl.registerTimer(timer, 10), sb::kResultOk) };
frame.run_loop.clear();
frame.run_loop.dispatch(t0 + Duration::from_secs(3));
assert_eq!(ticks.timer.load(Ordering::Relaxed), 1, "cleared on teardown");
// SAFETY: closing the pipe we opened.
unsafe {
libc::close(fds[0]);
libc::close(fds[1]);
}
}
/// A plugin-side handler that calls back into the run loop from its destructor, as a plugin's
/// handler may when its last reference is released.
struct Reentrant {
run_loop: ComPtr<sb::Linux::IRunLoop>,
}
impl Class for Reentrant {
type Interfaces = (sb::Linux::ITimerHandler, sb::Linux::IEventHandler);
}
impl sb::Linux::ITimerHandlerTrait for Reentrant {
unsafe fn onTimer(&self) {}
}
impl sb::Linux::IEventHandlerTrait for Reentrant {
unsafe fn onFDIsSet(&self, _fd: sb::Linux::FileDescriptor) {}
}
impl Drop for Reentrant {
fn drop(&mut self) {
use sb::Linux::IRunLoopTrait;
// SAFETY: a call through our own run loop, which the handler keeps alive.
unsafe { self.run_loop.unregisterTimer(std::ptr::null_mut()) };
}
}
/// Unregistering or clearing releases the plugin's handler after the run loop's lock, so a
/// handler whose destructor calls back into the run loop does not deadlock.
#[test]
fn releasing_a_handler_may_call_back_into_the_run_loop() {
use sb::Linux::IRunLoopTrait;
let frame = ComWrapper::new(PlugFrame::new(std::ptr::null_mut()));
let rl = frame.to_com_ptr::<sb::Linux::IRunLoop>().expect("the frame is the view's run loop");
for case in 0..3 {
let handler = ComWrapper::new(Reentrant { run_loop: rl.clone() });
let timer = handler.as_com_ref::<sb::Linux::ITimerHandler>().unwrap().as_ptr();
let events = handler.as_com_ref::<sb::Linux::IEventHandler>().unwrap().as_ptr();
// SAFETY: test calls through our own implementation with a live handler object.
unsafe {
assert_eq!(rl.registerTimer(timer, 10), sb::kResultOk);
assert_eq!(rl.registerEventHandler(events, 0), sb::kResultOk);
}
// From here on the run loop holds the only references.
drop(handler);
// SAFETY: as above; the handler stays alive until the run loop lets it go.
unsafe {
match case {
0 => {
assert_eq!(rl.unregisterTimer(timer), sb::kResultOk);
assert_eq!(rl.unregisterEventHandler(events), sb::kResultOk);
}
1 => {
assert_eq!(rl.unregisterEventHandler(events), sb::kResultOk);
assert_eq!(rl.unregisterTimer(timer), sb::kResultOk);
}
_ => frame.run_loop.clear(),
}
}
}
}
}
+138
View File
@@ -0,0 +1,138 @@
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
use vst3::ComPtr;
use vst3::Steinberg::Linux::{FileDescriptor, IEventHandler, IEventHandlerTrait, ITimerHandler, ITimerHandlerTrait, TimerInterval};
/// Registrations kept per view; a plugin needs a handful.
const MAX_ENTRIES: usize = 256;
/// Longest timer period accepted (one hour).
const MAX_INTERVAL_MS: TimerInterval = 3_600_000;
struct Timer {
handler: ComPtr<ITimerHandler>,
every: Duration,
next: Instant,
}
#[derive(Default)]
struct Entries {
fds: Vec<(ComPtr<IEventHandler>, FileDescriptor)>,
timers: Vec<Timer>,
}
#[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_fd(&self, handler: ComPtr<IEventHandler>, fd: FileDescriptor) -> bool {
let mut e = self.lock();
if fd < 0 || e.fds.len() >= MAX_ENTRIES {
return false;
}
e.fds.push((handler, fd));
log::debug!("vst3: run loop: watching fd {fd}");
true
}
/// Removes every descriptor registered with this handler. The removed references are released
/// after the lock is: a plugin destructor may call back into the run loop.
pub fn remove_fd(&self, handler: *mut IEventHandler) -> bool {
let gone: Vec<_> = {
let mut e = self.lock();
let (keep, gone) = std::mem::take(&mut e.fds).into_iter().partition(|(h, _)| h.as_ptr() != handler);
e.fds = keep;
gone
};
!gone.is_empty()
}
pub fn add_timer(&self, handler: ComPtr<ITimerHandler>, milliseconds: TimerInterval) -> bool {
let mut e = self.lock();
if e.timers.len() >= MAX_ENTRIES {
return false;
}
let every = Duration::from_millis(milliseconds.clamp(1, MAX_INTERVAL_MS));
e.timers.push(Timer { handler, every, next: Instant::now() + every });
log::debug!("vst3: run loop: timer every {} ms", every.as_millis());
true
}
/// Removes the timer registered with this handler (released after the lock, as above).
pub fn remove_timer(&self, handler: *mut ITimerHandler) -> bool {
let gone: Vec<_> = {
let mut e = self.lock();
let (keep, gone) = std::mem::take(&mut e.timers).into_iter().partition(|t| t.handler.as_ptr() != handler);
e.timers = keep;
gone
};
!gone.is_empty()
}
/// Drops every registration; the references are released after the lock, as above.
pub fn clear(&self) {
let old = std::mem::take(&mut *self.lock());
drop(old);
}
fn has_fd(&self, handler: *mut IEventHandler, fd: FileDescriptor) -> bool {
self.lock().fds.iter().any(|(h, f)| h.as_ptr() == handler && *f == fd)
}
fn has_timer(&self, handler: *mut ITimerHandler) -> bool {
self.lock().timers.iter().any(|t| t.handler.as_ptr() == handler)
}
/// Calls the handlers whose descriptor is readable and the timers that are due (at most
/// once each per call: a late UI frame does not replay missed ticks). Handlers may
/// (un)register from inside their callback, so none is called with the lock held, and
/// one removed earlier in the same pass is skipped.
pub fn dispatch(&self, now: Instant) {
let (fds, due) = {
let mut e = self.lock();
let fds = e.fds.clone();
let mut due = Vec::new();
for t in e.timers.iter_mut().filter(|t| t.next <= now) {
t.next = now + t.every;
due.push(t.handler.clone());
}
(fds, due)
};
for (h, fd) in ready(&fds) {
if self.has_fd(h.as_ptr(), fd) {
// SAFETY: a live handler we hold a reference to; main thread (the caller's).
unsafe { h.onFDIsSet(fd) };
}
}
for h in due {
if self.has_timer(h.as_ptr()) {
// SAFETY: as above.
unsafe { h.onTimer() };
}
}
}
}
/// The registrations whose descriptor has something to read (or hung up), without waiting.
fn ready(fds: &[(ComPtr<IEventHandler>, FileDescriptor)]) -> Vec<(ComPtr<IEventHandler>, FileDescriptor)> {
if fds.is_empty() {
return Vec::new();
}
let mut polled: Vec<libc::pollfd> = fds.iter().map(|&(_, fd)| libc::pollfd { fd, events: libc::POLLIN, revents: 0 }).collect();
// SAFETY: `polled` is a valid, writable array of `polled.len()` entries; a zero timeout
// never blocks.
let n = unsafe { libc::poll(polled.as_mut_ptr(), polled.len() as libc::nfds_t, 0) };
if n <= 0 {
return Vec::new();
}
fds.iter()
.zip(&polled)
.filter(|(_, p)| p.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0)
.map(|((h, fd), _)| (h.clone(), *fd))
.collect()
}
+170
View File
@@ -0,0 +1,170 @@
use std::collections::HashSet;
use std::ffi::{c_char, 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 PLATFORM_TYPE: Option<*const c_char> = Some(vst3::Steinberg::kPlatformTypeX11EmbedWindowID);
/// Rust names the process's first thread "main"; the app runs its UI (and event loop) there.
pub 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!("vst3: 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 frame).
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("not 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)
// embeds into 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 the plug frame's resizes).
pub fn raw(&self) -> *mut c_void {
self.id as usize as *mut c_void
}
/// The X11 window id the plugin view embeds into (`kPlatformTypeX11EmbedWindowID`).
pub fn parent(&self) -> *mut c_void {
self.raw()
}
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();
}
+5 -3
View File
@@ -27,13 +27,15 @@
//! Plugin editors (`IPlugView`): on macOS the view is attached to the content `NSView` of a host
//! `NSWindow` (titled and closable, floating above the app, resized on `IPlugFrame::resizeView`);
//! on Windows it is attached to a host `HWND` owned by the app's window (no taskbar button,
//! closing it hides it until the link tears it down).
//! closing it hides it until the link tears it down); on Linux and the BSDs it is embedded into
//! an X11 window of ours (`kPlatformTypeX11EmbedWindowID`, through XWayland on Wayland desktops),
//! and the frame is also the view's `Linux::IRunLoop`, whose descriptors and timers the handle's
//! `idle` services.
//! [`Plugin::open_editor`] opens it directly; [`Plugin::editor`] returns a handle usable on the
//! main thread while the instance processes on the audio thread (VST3's own threading model:
//! the controller and its views live on the UI thread). Parameter edits made in the editor
//! (`IComponentHandler::performEdit`) are reported by the handle's `idle` so the host can write
//! them into the session. Linux (X11) editor windows are not hosted yet: opening reports
//! "unsupported".
//! them into the session.
//!
//! Not hosted yet: `IMessage`/`IAttributeList` creation through the host (plugins that need it
//! for processor ↔ controller messaging may lose those messages), sidechain (aux buses are kept
+2 -2
View File
@@ -14,8 +14,8 @@ fn main() {
let dir = common::fixture_dir();
let gain = soundcraft_vst3_host::scan_paths(&[dir.to_path_buf()]).into_iter().find(|d| d.name == "Fixture Gain").expect("fixture").id;
let mut p = soundcraft_vst3_host::instantiate_plugin(&gain).expect("instantiate");
// Editor windows are hosted on macOS and Windows; elsewhere the probe reports "unsupported".
if cfg!(any(target_os = "macos", windows)) {
// Editor windows are hosted on macOS, Windows and X11 (Linux, BSDs); elsewhere the probe reports "unsupported".
if cfg!(any(target_os = "macos", windows, unix)) {
assert_eq!(p.editor_size(), Ok((320, 240)));
} else {
assert!(p.editor_size().is_err());
+4 -4
View File
@@ -64,7 +64,7 @@ fn identity_mapped_param_text_is_read_on_the_main_thread_only() {
assert_eq!((level.min, level.max, level.unit), (0.0, 1.0, Unit::Db));
let mut p = soundcraft_vst3_host::instantiate_plugin(&id).unwrap();
let mut ed = soundcraft_dsp::Plugin::editor(&mut p).expect("editor handle");
if cfg!(any(target_os = "macos", windows)) {
if cfg!(any(target_os = "macos", windows, unix)) {
assert_eq!(ed.value_text("13", 0.375), None, "test threads are not the main thread");
} else {
assert_eq!(ed.value_text("13", 0.375).as_deref(), Some("\u{2212}6.0 dB"));
@@ -359,8 +359,8 @@ fn many_buses_like_multi_out_instruments_are_activated() {
fn editor_view_is_probed_and_edits_come_back_as_plain_values() {
let id = id_of("Fixture Gain");
let mut p = soundcraft_vst3_host::instantiate_plugin(&id).unwrap();
// Editor windows are hosted on macOS and Windows; elsewhere the probe reports "unsupported".
if cfg!(any(target_os = "macos", windows)) {
// Editor windows are hosted on macOS, Windows and X11 (Linux, BSDs); elsewhere the probe reports "unsupported".
if cfg!(any(target_os = "macos", windows, unix)) {
assert_eq!(p.editor_size(), Ok((320, 240)));
} else {
assert!(p.editor_size().is_err());
@@ -369,7 +369,7 @@ fn editor_view_is_probed_and_edits_come_back_as_plain_values() {
// The fixture "edits" Gain to 0.9 (normalized) when it gets the component handler.
assert_eq!(ed.idle(), vec![("7".to_string(), 1.8)]);
assert!(ed.idle().is_empty());
if cfg!(any(target_os = "macos", windows)) {
if cfg!(any(target_os = "macos", windows, unix)) {
assert!(ed.open().unwrap_err().contains("main thread"), "test threads are not the main thread");
} else {
assert!(ed.open().is_err(), "unsupported elsewhere");
+5 -4
View File
@@ -1,6 +1,6 @@
# Where SoundCraft falls short of Pro Tools
> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-11-13 · **Change:** trivial (G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; previously trivial: G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-11-13 · **Change:** minor (G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing
real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker**
@@ -19,7 +19,7 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t
| G-02 | **Alpha blocker.** No MIDI device input or output | Hardware / MIDI | [hardware-parity.md](hardware-parity.md) | 20–35 |
| G-03 | **Alpha blocker.** Cannot exchange sessions with Pro Tools (no AAF/OMF, no `.ptx`) | File formats | [file-format-parity.md](file-format-parity.md) | 50–90 |
| G-04 | Open correctness bugs in features counted as done (~25 issues) | Stability | this file | 25–40 |
| G-05 | (Entitlement part: alpha blocker for the mix row) Third-party VST3s blocked in the signed macOS build; AU editors missing | Ecosystem | [plugin-parity.md](plugin-parity.md) | 15–25 |
| G-05 | (Entitlement part: alpha blocker for the mix row) Third-party VST3s blocked in the signed macOS build; AU editors missing | Ecosystem | [plugin-parity.md](plugin-parity.md) | 10–15 |
| G-06 | (Record-to-disk part: alpha blocker for the tracking row) Sources decoded whole into RAM; recording into RAM | Performance | [hardware-parity.md](hardware-parity.md) | 15–25 |
| G-07 | Nothing is compared against Pro Tools' output (no fidelity harness) | Features | this file | 20–30 |
| G-08 | Built-in plugin catalogue thin and unverified | Features | [plugin-parity.md](plugin-parity.md) | 80–120 |
@@ -126,8 +126,8 @@ launch #142; Linux #45, #107.
- **Missing:** the `com.apple.security.cs.disable-library-validation` entitlement in the signed
build, so hardened runtime refuses third-party VST3 bundles (#153, #149). AU editor views
(`crates/au-host/src/lib.rs` header: "Not hosted yet: Audio Unit editor views"). Embedded CLAP
GUIs; VST3 editors on Windows/Linux.
- **Estimate:** ≈ 15–25 h (entitlement ≈ 1 h; AU Cocoa views and VST3 HWND/X11 views most of it).
GUIs on macOS (#485). VST3 and embedded CLAP editors are hosted on Windows and Linux/X11.
- **Estimate:** ≈ 10–15 h (entitlement ≈ 1 h; AU Cocoa views and embedded CLAP on macOS most of it).
### G-06. Memory-bound media
@@ -240,6 +240,7 @@ missing. Out of scope unless the owner decides otherwise.
|---|---|---|
| 2026-11-13 | trivial | G-09: the pt-BR catalog now covers tooltips localized inside buttons and toggles, the Edit-window status bar, the remove-session question, the send help text and engine errors shown in the status line; estimates unchanged |
| 2026-11-04 | trivial | G-04: track and master volume automation read at every sample, so breakpoints act on their own sample in any block size (#1354); estimates unchanged |
| 2026-10-30 | minor | G-05: VST3 and embedded CLAP editors on Linux/X11 (#527) |
| 2026-10-25 | trivial | G-04: Clip Looping (#1030) lacks the loop crossfade option, and Number of Loops stops at 512 while length and fill make up to 1000 loops |
| 2026-10-25 | trivial | G-01: `setup.playback_engine` and `setup.hardware` apply the device and buffer in the desktop app; headless returns `applied: false` |
| 2026-10-24 | trivial | G-08: 27 processors + 3 instruments, as the plugin registry holds; G-20: the sampler shipped (#108), so it is no longer listed as missing |
+4 -3
View File
@@ -1,6 +1,6 @@
# Plugin parity: built-in processors and plugin hosting
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** trivial (Auto Pan stereo balance; previously minor: AudioSuite speed ramps (speed_ramp); Auto Pan; Subharmonic; previously minor: Ring Modulator; VST3 host messages: IMessage and IAttributeList; previously trivial: Sampler ping-pong loop phase (#463); previously trivial: mix.instrument sets built-in instrument parameters in params (#265); previously minor: plugin editors on Windows) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (editors: VST3 and embedded CLAP editors on Linux/X11; previously trivial: Auto Pan stereo balance) · **Target:** Avid Pro Tools Ultimate 2026.4.1
Pro Tools users live in plugins: the bundled set covers everyday mixing, and third-party plugins
cover the rest. This doc tracks both. Our plugins have our own names and are written from
@@ -44,8 +44,8 @@ User report #152: a saved instrument level does not reach the bounce.
| Notes / MIDI to instruments | ✅ | ✅ | But no live MIDI input (G-02) |
| State saved in sessions, presets | ✅ | ✅ | |
| Create/destroy off the audio thread | ✅ | ✅ | |
| Editors: CLAP | — | 🟡 floating windows; embedded editors on Windows | Embedded on macOS/Linux missing |
| Editors: VST3 | — | 🟡 macOS (verified with a commercial pitch editor) and Windows (verified with a free JUCE compressor) | Linux views missing |
| Editors: CLAP | — | 🟡 floating windows; embedded editors on Windows and Linux/X11 (verified with Graillon and Surge XT Effects) | Embedded on macOS missing (#485) |
| Editors: VST3 | — | ✅ macOS (verified with a commercial pitch editor), Windows (verified with a free JUCE compressor) and Linux/X11 through XWayland on Wayland (verified with Graillon and Surge XT Effects) | |
| Editors: AU | — | ❌ | Cocoa view hosting missing |
| Multiple editor pages | ✅ | 🟡 | #6 |
| macOS hardened-runtime entitlement for third-party code | ✅ | ❌ | #153, #149 — signed builds refuse third-party VST3 |
@@ -58,6 +58,7 @@ User report #152: a saved instrument level does not reach the bounce.
| Date | Change | Summary |
|---|---|---|
| 2026-10-27 | minor | Editors: VST3 and embedded CLAP editors on Linux/X11, with the host run loop (VST3 `IRunLoop`, CLAP timer and fd support) (#527) |
| 2026-10-25 | trivial | Auto Pan: constant-power balance of the left and right channels; stereo passes unchanged at the center |
| 2026-10-24 | minor | AudioSuite speed ramps (`speed_ramp`): down to a stop and up from one, Fit To or Extend, fades on or off |
| 2026-10-24 | minor | Auto Pan: LFO and envelope panning of stereo tracks; built-in count 27 processors + 3 instruments |
+4 -3
View File
@@ -1,6 +1,6 @@
# SoundCraft roadmap: milestones and what's next
> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-05 · **Change:** trivial (M15: partial pt-BR catalog in PR #1346) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-05 · **Change:** trivial (G-05 estimate after Linux/X11 plugin editors; previously trivial: M15: partial pt-BR catalog in PR #1346) · **Target:** Avid Pro Tools Ultimate 2026.4.1
Forward-looking plan. Status and numbers: [`../ROADMAP.md`](../ROADMAP.md) and
[`target-app-parity.md`](target-app-parity.md); the ranked work list: [`gaps.md`](gaps.md).
@@ -12,7 +12,7 @@ Hours are Opus 5.5 agent-hours.
correctness backlog (G-04). ≈ 15–25 h.
2. **Audio interface basics** (G-01): device selection, buffer size, duplex stream, ASIO. ≈ 25–40 h.
3. **MIDI devices** (G-02): input to armed tracks and instruments, output, thru, clock. ≈ 20–35 h.
4. **macOS plugin hosting** (G-05): library-validation entitlement now (#153), then AU editors. ≈ 15–25 h.
4. **macOS plugin hosting** (G-05): library-validation entitlement now (#153), then AU editors and embedded CLAP editors on macOS. ≈ 10–15 h.
5. **A PR CI that runs `cargo xtask ci`** on Linux, macOS and Windows (G-14). ≈ 5–10 h.
## Alpha gate
@@ -25,7 +25,7 @@ main platform). Any **no** keeps SoundCraft **pre-alpha**, and those rows are th
| Record audio from a chosen interface at a chosen buffer size, monitor, punch, keep the takes | **no** | Device, rate and buffer are chosen in the Playback Engine window and, in the desktop app, by `setup.playback_engine` (headless returns `applied: false`). The mix still runs in fixed 512-sample blocks. Separate input and output streams. Takes held in RAM until stop (PR #84). | 35–55 |
| Record MIDI from a controller and play it back through an instrument | **no** | Playback of drawn and imported MIDI works. No MIDI device layer at all, so nothing can be recorded and instruments can't be played live (G-02). | 20–35 |
| Edit: select, trim, fade, comp playlists, Slip/Shuffle/Grid | yes (rough) | Every Edit menu command; property-tested with undo; open bugs #3, #5, #140 don't block the workflow | — |
| Mix with built-in and third-party plugins, sends, busses, automation | partial (passes on CLAP/AU) | 27 built-in processors; CLAP and AU host on the signed macOS build, but its missing entitlement blocks third-party VST3 (#153). No AU plugin windows yet; VST3 windows on macOS only | 1–2 (entitlement) |
| Mix with built-in and third-party plugins, sends, busses, automation | partial (passes on CLAP/AU) | 27 built-in processors; CLAP and AU host on the signed macOS build, but its missing entitlement blocks third-party VST3 (#153). No AU plugin windows yet; VST3 windows on macOS, Windows and Linux/X11 | 1–2 (entitlement) |
| Bounce mix and stems; save and reopen the session | yes (rough) | WAV/BWF/AIFF/FLAC bounce, stems, `.scraft` save/reopen with plugin state; bugs #59, #103 in bus bounce and aux latency (PRs open) | — |
| Exchange a session with Pro Tools or a picture editor | **no** | No `.ptx`, AAF or OMF import or export (#40, G-03) | 50–90 |
@@ -89,6 +89,7 @@ There is no `cargo xtask scorecard` in this repo; the measured number is `cargo
| Date | Change | Summary |
|---|---|---|
| 2026-11-05 | trivial | M15: a pt-BR catalog covers menus and `text`/`localized_format!` strings; remains native review, CJK/RTL and the other languages. Estimates unchanged |
| 2026-10-30 | trivial | G-05 down to 10–15 h and the mix row's VST3 windows updated: VST3 and embedded CLAP editors are hosted on Linux/X11 (#527) |
| 2026-10-25 | trivial | Record-workflow evidence: `setup.playback_engine` applies the device and buffer in the desktop app; headless returns `applied: false` |
| 2026-10-24 | trivial | 27 built-in processors, as the plugin registry holds; the sampler (#108) is no longer listed under plugin essentials |
| 2026-10-14 | trivial | M8: reject oversized MCP batches before execution (#460) |
+2 -1
View File
@@ -30,7 +30,7 @@ Legend: ✅ matches · 🟡 partial · ❌ missing.
| Feature | Status | Notes |
|---|---|---|
| Default shortcuts | 🟡 146 bound (measured: distinct `Some("…")` shortcuts in the registry) | Pro Tools' default set is several hundred incl. numeric keypad and focus keys. Collisions: Mix/Edit toggle vs zoom (#144), Heal (#140), Export (#7) |
| Default shortcuts | 🟡 146 bound (measured: distinct `Some("…")` shortcuts in the registry) Delete and Backspace clear the edit selection in the Edit window like Edit › Clear (#404). | Pro Tools' default set is several hundred incl. numeric keypad and focus keys. Collisions: Mix/Edit toggle vs zoom (#144), Heal (#140), Export (#7) |
| Ctrl as Cmd on Windows/Linux | ✅ since #15, #41 still open in some builds | #62 shows Ctrl in labels |
| Numeric keypad transport and memory-location recall | 🟡 | Classic / Transport / Shuttle modes not all present |
| Modifier gestures (Alt for all tracks, Shift-Alt for selected, Cmd-click fine faders, Ctrl-click defaults) | 🟡 | Main ones on faders and pan; not across every control |
@@ -80,6 +80,7 @@ Legend: ✅ matches · 🟡 partial · ❌ missing.
| 2026-10-19 | minor | Preferences opens from Setup with nine searchable pages, compact grouped controls, staged apply/cancel, platform tab shortcuts and disabled placeholders for unavailable settings |
| 2026-10-16 | minor | Track name menu: Scroll Into View brings the track to the top of the Edit window and the left of the Mix. Readiness estimate unchanged |
| 2026-10-13 | minor | A plugin opens when it's inserted (#486) |
| 2026-10-13 | trivial | Delete / Backspace clear the edit selection (#404) |
| 2026-10-13 | minor | Drag across checkboxes (#399) |
| 2026-10-13 | minor | Waveforms and fade curves share temporary envelopes during drag, without rebuilding media or editing the document before release. Readiness estimate unchanged |
| 2026-10-13 | minor | Fade curves use bounded physical-pixel sampling; midpoint handles stay visible and inside the clip, with repeat-drag coverage after extreme bends. Readiness estimate unchanged |