Compare commits

...
Author SHA1 Message Date
skylar taylor-barrick 81766eebb6 test(clap): use portable descriptor readiness fixture (#1795) 2026-11-26 08:44:29 -06:00
FredApps f07dc9e221 Merge pull request #1581 from gmrmad1/fix/markers-add-kind
markers: reject an unknown marker kind in markers.add
2026-11-26 13:35:43 +01:00
FredApps 580ba762b0 Merge branch 'main' into fix/markers-add-kind 2026-11-26 13:27:43 +01:00
FredApps 2b21bf0853 Merge pull request #1579 from gmrmad1/fix/import-audio-track-kind
io: refuse a non-audio target track for audio import
2026-11-26 13:25:08 +01:00
FredApps 441a356994 Merge branch 'main' into fix/import-audio-track-kind 2026-11-26 13:15:30 +01:00
FredApps dd70599e24 Merge pull request #1578 from gmrmad1/fix/clip-loop-count-cap
clip: allow up to 1000 loops in Clip Looping
2026-11-26 10:07:54 +01:00
FredApps c65ae92001 Merge pull request #1682 from istefp/feat/failed-plugin-retry
mix: a plugin failed twice stays failed — one reset retry per slot (#919)
2026-11-26 10:07:24 +01:00
FredApps a92536f992 Merge pull request #1692 from MMexicann/patch-4
Reject invalid target playlist indexes before changing tracks
2026-11-26 10:05:28 +01:00
skylar taylor-barrick 417a326b90 Nightly: stop blocking a refused launch on macOS (#1803)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list where that applied, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2).
2026-11-26 00:47:18 -06:00
aiongg af9f2109ff Merge pull request #1738 from aiongg/minimal-port-next
SoundCraft: move to craft-libs next (minimal port)
2026-11-25 23:08:34 -05:00
aiongg de4c997d6e Docking test: the MIDI editor's tab adds 28 points in the default layout 2026-11-25 21:07:34 +00:00
aiongg fcc4b98745 The MIDI editor keeps its body's height under the 28-point tab strip 2026-11-25 20:44:58 +00:00
aiongg 481b7e6a68 Floating windows carry the running channel's app id 2026-11-25 20:08:38 +00:00
aiongg 0321122ad4 The send menu stays on the side it opened on 2026-11-25 20:08:38 +00:00
aiongg a587aadec5 Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:24 +00:00
aiongg cb0c7395d8 A press in the focused session view asks for no focus again 2026-11-25 15:50:03 +00:00
aiongg 6338349f88 Repin craft-libs to storytold next aa401985d 2026-11-25 15:50:03 +00:00
aiongg e652100a53 The Mix window's Tab test lists both windows in each input, as eframe does 2026-11-25 14:35:27 +00:00
aiongg 528c245e6f The session view: no Tab trap in the Mix window, focus back after dialogs, held Tab stays 2026-11-25 14:09:08 +00:00
aiongg 84e07209a6 The canvas is one real Tab stop and takes the keyboard when pressed
The session view (the Edit window's tracks and timeline, the Mix window's strips) is declared as the host canvas with the
id of its own widget, so egui keeps the focus Tab gives it. A press in it and a view that opens or shows another document
give it the focus; a text field, a dialog or a menu keeps it. The focused view keeps Tab only while edit.tab has a stop
ahead, and leaves the keyboard to the shortcuts.
2026-11-25 13:57:53 +00:00
aiongg 5e0b41d291 Allow egui::ComboBox: craft-libs next has no drop-in craft_ui::ComboBox 2026-11-25 13:55:03 +00:00
aiongg d0c27acc5d Repin craft-libs to storytold d1bdf8e5da (craft-libs#3505 head); egui stays at storytold b15ffe9bfc 2026-11-25 13:43:14 +00:00
aiongg 30afd14075 Repin craft-libs to storytold next 980669cdce and egui to storytold b15ffe9bfc 2026-11-25 13:42:40 +00:00
aiongg 92894ee20a Merge main into minimal-port-next
Conflicts: Cargo.toml (kept the port's craft-libs dependency lines, craft-update feature ui and the host crates; main's rev bumps dropped), Cargo.lock (took the branch's).
2026-11-25 13:41:14 +00:00
aiongg 8f513c84c2 Repin craft-libs to 2f8d73e7cf; pass the app icon to the host; unbind the runtime's Quit for app.quit 2026-11-24 15:59:30 +00:00
aiongg f892550c91 Round 5: craft-libs 48e798653c; pane-key overrides by NavCommand id, so F6 reaches the Trim tool
SoundCraft unbound "window.nextPane"/"window.previousPane", but the commands' ids are
window.next_pane/window.previous_pane. The keymap skips an override key it cannot resolve, so
F6 stayed the pane move and the key stage took it out of egui's events. The overrides now use
NavCommand::NextPane.id() and NavCommand::PreviousPane.id().

The trackpad rig gets frame(events), and a test presses F6 from the keyboard and through the
control channel's ui.key and expects the Trim tool. cargo fmt on control.rs and fonts.rs.
2026-11-24 00:47:23 +00:00
aiongg 005150eb6d Round 4: semibold family in fonts::install, ui.key acknowledged by the runtime's injected-input idle signal 2026-11-24 00:09:16 +00:00
aiongg 8ebbad7c32 Trackpad test rig hands the runtime SoundCraft's frame input, as the shells do 2026-11-23 23:31:07 +00:00
aiongg 6fbaec65e8 Round 2 on craft-libs next-host-input: host canvas claims Alt+1-4, host_body panels, no Ctrl+wheel pinch 2026-11-23 23:25:30 +00:00
aiongg 404d49e0a9 Test round 1: app style for the dock's views, pinch-folded Ctrl+wheel acknowledged, font-load discard pass in the gate test, Id::unique 2026-11-23 22:41:38 +00:00
aiongg 5f0fe9bfb2 Root window handed to the runtime as a shared reference 2026-11-23 22:29:07 +00:00
aiongg 77c125f564 rustfmt the ported files 2026-11-23 22:28:20 +00:00
aiongg 55078b0f23 Tests on next: runtime installed in the UI harnesses, dock tests on commands and the model, renderer gesture tests removed 2026-11-23 22:26:48 +00:00
aiongg a86949df15 Minimal port to craft-libs next: runtime host, DockArea dock, app-local icon buttons, capture slot and send menu, update dialogs on the DialogHost 2026-11-23 22:22:14 +00:00
aiongg 4f7bb6796d probe: Node::Dock side is DockEdge 2026-11-23 21:46:16 +00:00
aiongg 72b061f31e probe: mechanical codemod for next 2026-11-23 21:41:44 +00:00
aiongg fbf3bcd7a4 probe: repin craft-libs to next 2026-11-23 21:41:19 +00:00
FredApps b34b86fd7e Resolve clip looping conflicts with main 2026-11-23 10:20:05 +01:00
Mex 733a17ffa6 Reject invalid target playlist indexes before changing tracks 2026-11-21 18:56:46 +01:00
Stefan Pantic 1b2c087f29 mix: a re-failed plugin stays failed, one reset retry per slot (#919) 2026-11-20 19:09:34 -05:00
gmrmad1 2d8931da1d review: reject a non-string markers.add kind instead of treating it as omitted (coderabbitai/non-string-kind) 2026-11-16 19:52:45 +05:30
Madhav Agarwal d516f2c1d1 markers: reject an unknown marker kind in markers.add 2026-11-15 19:14:42 +05:30
Madhav Agarwal c582bcb4d2 io: refuse a non-audio target track for audio import 2026-11-15 17:44:33 +05:30
Madhav Agarwal 27b0373761 clip: allow up to 1000 loops in Clip Looping (#G-04) 2026-11-15 15:54:30 +05:30
117 changed files with 3797 additions and 1196 deletions
Generated
+1292 -82
View File
File diff suppressed because it is too large Load Diff
+35 -28
View File
@@ -11,9 +11,9 @@ rust-version = "1.95"
repository = "https://github.com/storytold/soundcraft"
[workspace.dependencies]
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# internal
soundcraft-interchange = { path = "crates/interchange" }
soundcraft-time = { path = "crates/time" }
@@ -61,27 +61,34 @@ cpal = "0.18"
midir = "=0.11.1"
# Which file paths stored in a session may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Video containers and bitstreams, shared with the other craft apps.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# H.264 and ProRes codecs shared with the other Craft apps.
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
# Audio file formats, codecs and waveform overviews, shared with the other craft apps. It shares
# types with craft-media, so both stay on one rev.
# Standard MIDI Files and the note/controller model, shared with the other craft apps.
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# AAF property-stream framing, shared with the other craft apps.
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["egui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode
# the framework's components draw in (craft-libs).
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
egui = { version = "0.37" }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -124,18 +131,18 @@ debug = 0
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+3
View File
@@ -49,6 +49,7 @@ pub fn start() {
if let Some(rs) = &cc.wgpu_render_state {
log::info!("soundcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
}
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
let app = SoundApp::new(engine, Some(player), Services::default());
@@ -224,12 +225,14 @@ impl eframe::App for WebShell {
self.app.logic(ctx);
// A prompt opened during this frame becomes a picker on the next one.
self.take_path_prompt(ctx);
self.app.close_path(ctx);
}
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
/// shell.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+8 -2
View File
@@ -183,10 +183,16 @@ mod config_tests {
app.ui = load_ui(&path).unwrap().unwrap();
assert_eq!(app.ui.theme, soundcraft_ui_egui::theme::ThemeMode::Light);
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), edit);
assert_eq!(app.ui.mix_docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [140.0, 150.0, 280.0, 420.0]);
assert_eq!(
app.ui.mix_docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
egui::Rect::from_min_size(egui::pos2(140.0, 150.0), egui::vec2(280.0, 420.0))
);
app.ui.window = MainWindow::Edit;
app.run("ui.dock", serde_json::json!({"operation":"open","panel":"tracks"})).unwrap();
assert_eq!(app.ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [80.0, 90.0, 260.0, 400.0]);
assert_eq!(
app.ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
egui::Rect::from_min_size(egui::pos2(80.0, 90.0), egui::vec2(260.0, 400.0))
);
let mut invalid_mix = app.ui.clone();
invalid_mix.mix_docking = soundcraft_ui_egui::docking::edit_default();
let invalid_bytes = serde_json::to_vec(&invalid_mix).unwrap();
+38 -8
View File
@@ -71,8 +71,6 @@ impl eframe::App for App {
}
if self.0.quit_requested {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else if ctx.input(|i| i.viewport().close_requested()) && dialogs::ask_to_save(&mut self.0, "app.quit", &serde_json::json!({})) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
soundcraft_ui_egui::fit_window_to_screen(ctx);
let (inner, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().maximized.unwrap_or(false)));
@@ -96,13 +94,17 @@ impl eframe::App for App {
soundcraft_ui_egui::os_title(app_name, Some(document.0))
};
set_title(ctx, title);
// Last: the runtime's close path, which asks about unsaved changes before the window closes.
self.0.close_path(ctx);
}
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
/// shell.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.0.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
soundcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.0.guarded(|app| app.ui(ui));
}
fn on_exit(&mut self) {
@@ -213,14 +215,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
)
}
/// Report a refused launch profile on standard error, and in a dialog on a desktop session: a
/// Nightly build started from a file manager has no console to read.
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Report a refused launch profile on standard error, and in a dialog on a Windows or X11/Wayland
/// desktop session: a Nightly build started from a file manager has no console to read. macOS keeps
/// the console line, because a modal before its event loop never appears.
fn report_launch_profile_error(error: &str) {
eprintln!("SoundCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("SoundCraft launch profile: {error}");
return;
@@ -331,11 +342,15 @@ fn main() -> eframe::Result {
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
#[cfg(target_os = "windows")]
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
#[cfg(all(unix, not(target_os = "macos")))]
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; SOUNDCRAFT_WAYLAND=1
// keeps the native Wayland backend.
if env.use_xwayland(std::env::var_os("DISPLAY").as_ref()) {
#[cfg(all(unix, not(target_os = "macos")))]
let forced_x11 = env.use_xwayland(std::env::var_os("DISPLAY").as_ref());
#[cfg(not(all(unix, not(target_os = "macos"))))]
let forced_x11 = false;
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
@@ -369,6 +384,7 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
soundcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11)?;
let player =
if no_audio { None } else { Some(soundcraft_playback::Player::with_config(Arc::new(engine.session().clone()), &prefs.audio)) };
let mut app = SoundApp::new(engine, player, services());
@@ -449,3 +465,17 @@ mod tests {
assert_eq!(titles("Song * — SoundCraft"), 1);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
-4
View File
@@ -2,8 +2,4 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+15 -16
View File
@@ -153,6 +153,9 @@ impl RunLoop {
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
#[test]
fn timers_and_descriptors_follow_registration() {
@@ -168,25 +171,21 @@ mod tests {
assert_eq!(due, vec![a, b], "a late frame fires each timer once");
assert!(rl.remove_timer(a) && !rl.remove_timer(a));
assert_eq!(rl.due(t0 + Duration::from_secs(2)), vec![b]);
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");
// A connected stream has defined read and write readiness on both Linux and BSD.
let (stream, mut peer) = UnixStream::pair().unwrap();
let fd = stream.as_raw_fd();
assert!(rl.add_fd(fd, CLAP_POSIX_FD_READ));
assert!(!rl.add_fd(fd, CLAP_POSIX_FD_READ), "registered once");
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]));
peer.write_all(b"x").unwrap();
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_READ)]);
// The unread byte is still there, so reporting read as well would be a stale interest.
assert!(rl.modify_fd(fd, CLAP_POSIX_FD_WRITE));
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_WRITE)]);
assert!(rl.remove_fd(fd) && !rl.has_fd(fd));
assert!(rl.ready().is_empty(), "no callbacks for an unregistered descriptor");
rl.clear();
assert!(!rl.has_timer(b));
// SAFETY: closing the pipe we opened.
unsafe {
libc::close(fds[0]);
libc::close(fds[1]);
}
}
}
+1
View File
@@ -66,6 +66,7 @@ pub use file::bounce_job;
pub(crate) use edit::remember_selection;
pub use strip_silence::strip_silence_scan;
pub use tab::tab_stop_ahead;
pub type Run = fn(&mut Engine, &Value) -> Result<Value>;
/// `Err(reason)` = disabled.
+1 -1
View File
@@ -301,7 +301,7 @@ const MAX_LOOPS: i64 = 1000;
fn loop_clips(e: &mut Engine, p: &Value) -> Result<Value> {
let ids = clip_ids_param(e, p);
let count = i64_or(p, "count", 4).clamp(1, 512);
let count = i64_or(p, "count", 4).clamp(1, MAX_LOOPS);
let total = position_param(e, "clip.loop", p, "length")?;
let fill = p.get("fill").and_then(Value::as_bool).unwrap_or(false);
let s = e.session_mut();
+7
View File
@@ -469,6 +469,13 @@ mod tests {
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "length": 100_100})).unwrap()["loops"], 1000);
}
#[test]
fn loop_count_accepts_up_to_the_documented_thousand() {
let (mut e, t, ids) = engine_with(&[(0, 100, 0)]);
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "count": 600})).unwrap()["loops"], 599);
assert_eq!(e.session().track(t).unwrap().clips().len(), 600);
}
#[test]
fn regroup_reuses_group() {
let (mut e, _, ids) = engine_with(&[(0, 100, 0), (500, 100, 0), (900, 100, 0)]);
+34 -4
View File
@@ -313,10 +313,16 @@ fn add_marker(e: &mut Engine, p: &Value) -> Result<Value> {
let at = position_param(e, "markers.add", p, "at")?;
let st = position_param(e, "markers.add", p, "start")?;
let en = position_param(e, "markers.add", p, "end")?;
let kind = match str_param(p, "kind") {
Some("selection") => MarkerKind::Selection,
Some("none") => MarkerKind::None,
_ => MarkerKind::Marker,
let kind = match p.get("kind") {
None | Some(Value::Null) => MarkerKind::Marker,
Some(v) => match v.as_str() {
Some("marker") => MarkerKind::Marker,
Some("selection") => MarkerKind::Selection,
Some("none") => MarkerKind::None,
Some(other) => return Err(bad("markers.add", format!("unknown kind `{other}`"))),
// A present non-string is neither a documented kind nor an omitted one.
None => return Err(bad("markers.add", "kind must be a string")),
},
};
let (a, b) = match (at, st, en) {
(Some(a), _, _) => (a, a),
@@ -580,6 +586,30 @@ mod tests {
}
}
/// `markers.add` rejects an unknown or non-string `kind` instead of silently adding a plain
/// marker; an absent or null one still means a plain marker.
#[test]
fn markers_add_rejects_an_unknown_kind() {
let mut e = crate::Engine::default();
let err = e.execute("markers.add", &json!({"name": "x", "kind": "garbage"})).unwrap_err();
assert!(err.to_string().contains("kind"), "unexpected error: {err}");
assert!(e.session().markers.is_empty());
for bad in [json!(123), json!(true), json!(["marker"]), json!({"kind": "marker"}), json!(1.5)] {
let err = e.execute("markers.add", &json!({"name": "x", "kind": bad})).unwrap_err();
assert!(err.to_string().contains("kind"), "{bad}: unexpected error: {err}");
assert!(e.session().markers.is_empty(), "{bad}: a marker was added");
}
let plain = e.execute("markers.add", &json!({"name": "Plain", "kind": null, "at": 500})).unwrap();
assert_eq!(e.session().markers.len(), 1, "null is still an omitted kind");
let verse = e.execute("markers.add", &json!({"name": "Verse", "kind": "marker", "at": 1000})).unwrap();
let pre = e.execute("markers.add", &json!({"name": "Pre", "kind": "none", "at": 2000})).unwrap();
let kind_of =
|e: &crate::Engine, r: &serde_json::Value| e.session().markers.iter().find(|m| Some(m.id.0) == r["id"].as_u64()).map(|m| m.kind);
assert_eq!(kind_of(&e, &plain), Some(soundcraft_model::MarkerKind::Marker));
assert_eq!(kind_of(&e, &verse), Some(soundcraft_model::MarkerKind::Marker));
assert_eq!(kind_of(&e, &pre), Some(soundcraft_model::MarkerKind::None));
}
/// Constant replaces the tempo over [start, end) only; the tempo at the old end tick carries on after it.
#[test]
fn tempo_constant_is_bounded_by_its_range() {
+17
View File
@@ -52,6 +52,23 @@ fn import_audio_places_audio_offered_by_a_worker() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn import_audio_refuses_a_non_audio_target() {
let dir = std::env::temp_dir().join(format!("sc-import-non-audio-target-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let wav = tone_wav(&dir, "tone.wav");
let mut e = Engine::default();
e.execute("track.new", &json!({"kind": "instrument", "name": "Keys"})).unwrap();
let err = e.execute("file.import_audio", &json!({"path": wav, "track": "Keys"})).unwrap_err();
assert!(err.to_string().contains("audio track"), "{err}");
assert_eq!(e.session().tracks.len(), 1);
assert!(e.session().sources.is_empty());
assert!(e.session().tracks[0].clips().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn export_session_text_needs_replace_to_overwrite() {
let dir = std::env::temp_dir().join(format!("sc-export-text-replace-{}", std::process::id()));
+7
View File
@@ -58,6 +58,13 @@ fn tab(e: &mut Engine, p: &Value) -> Result<Value> {
Ok(json!({"selection": r}))
}
/// Whether Tab has a stop after the insertion point or the selection's start. Every stop of a clip lies at or before
/// its end, which is a stop itself.
pub fn tab_stop_ahead(s: &Session) -> bool {
let from = s.edit.selection.start;
s.tracks.iter().filter(|t| s.edit.selected_tracks.contains(&t.id)).flat_map(|t| t.clips()).any(|c| c.start.max(c.end()) > from)
}
/// The nearest stop after `from` (before it when `back`) on the selected tracks.
fn stop(s: &Session, from: Samples, back: bool) -> Option<Samples> {
let nearer = |x: Samples, best: Option<Samples>| {
+19 -4
View File
@@ -502,15 +502,22 @@ fn coalesce_vca(e: &mut Engine, p: &Value) -> Result<Value> {
}
fn designate_target(e: &mut Engine, p: &Value) -> Result<Value> {
let tracks = tracks_required(e, "track.designate_target_playlist", p)?;
let idx = p.get("index").and_then(Value::as_u64);
let id = "track.designate_target_playlist";
let tracks = tracks_required(e, id, p)?;
let index = match p.get("index") {
None | Some(Value::Null) => None,
Some(value) => {
let index = value.as_u64().ok_or_else(|| bad(id, "`index` must be a nonnegative integer"))?;
Some(usize::try_from(index).map_err(|_| bad(id, "no such playlist"))?)
}
};
let s = e.session_mut();
let mut out = Vec::new();
for t in &tracks {
let Some(tr) = s.track(*t) else { continue };
let i = idx.map_or(tr.active_playlist, |x| usize::try_from(x).unwrap_or(usize::MAX));
let i = index.unwrap_or(tr.active_playlist);
if i >= tr.playlists.len() {
return Err(bad("track.designate_target_playlist", "no such playlist"));
return Err(bad(id, "no such playlist"));
}
s.edit.values.insert(format!("playlist.target.{}", t.0), i as f64);
out.push(json!({"track": t, "target": i}));
@@ -726,11 +733,19 @@ mod tests {
e.execute("track.playlist_new", &json!({})).unwrap();
e.execute("track.designate_target_playlist", &json!({})).unwrap();
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
let kick = e.session().track_by_name("Kick").unwrap().id;
for index in [json!(-1), json!("1"), json!(1.5), json!(u64::MAX)] {
assert!(e.execute("track.designate_target_playlist", &json!({"index": index})).is_err(), "{index}");
assert_eq!(target_playlist(e.session(), kick), Some(1), "{index} must leave the target unchanged");
}
e.execute("track.show_target_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 0);
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
e.execute("track.designate_target_playlist", &json!({"index": null})).unwrap();
assert_eq!(target_playlist(e.session(), kick), Some(0));
}
}
+7
View File
@@ -176,6 +176,13 @@ fn place_import(
let file_rate = info.sample_rate;
let s = e.session_mut();
let session_rate = s.sample_rate.hz();
// An explicit non-audio target cannot play the clip: refuse it before registering
// the source, like `clip.place_source` does.
if let Some(t) = target
&& !s.track(t).is_some_and(|tr| tr.kind == TrackKind::Audio)
{
return Err(EngineError::BadParams("file.import_audio".into(), "audio files go on audio tracks".into()));
}
let src = add_source_audio(s, name, audio, path, FileFormat::of(info));
if let (Some(bwf), Some(sx)) = (info.bwf.as_ref(), s.sources.last_mut()) {
sx.time_reference = stamp_at_rate(bwf.time_reference, file_rate, session_rate);
+8 -2
View File
@@ -263,12 +263,18 @@ impl MixEngine {
for s in self.strips.values_mut() {
for p in s.plugins.iter_mut().flatten() {
p.plugin.reset();
p.failed = false;
if p.failed && !p.retried {
p.failed = false;
p.retried = true;
}
}
if let Some(i) = &mut s.instrument {
i.plugin.all_notes_off();
i.plugin.reset();
i.failed = false;
if i.failed && !i.retried {
i.failed = false;
i.retried = true;
}
}
s.held.clear();
s.chase = true;
+6 -2
View File
@@ -29,6 +29,10 @@ pub(crate) struct PluginSlot {
/// so the audio thread reuses its allocation.
lanes: Vec<usize>,
pub(crate) failed: bool,
/// A failed plugin is retried once on the next reset; a second failure keeps it out for the
/// rest of the session, so a plugin that always fails stops oscillating the track's latency
/// (and the compensation reallocations that go with it) on every stop or seek (#919).
pub(crate) retried: bool,
}
pub(crate) struct Strip {
@@ -203,7 +207,7 @@ impl SlotCtx<'_> {
let state = if third { ins.state_bytes() } else { None };
create_instance_for(&ins.plugin, state.as_deref(), self.sr, self.mb, ch, self.offline).map(|n| n.plugin)
}?;
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false })
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false })
}
}
@@ -624,7 +628,7 @@ mod apply_params_tests {
fn recorder() -> (PluginSlot, Arc<Mutex<Vec<(String, f32)>>>) {
let sets = Arc::new(Mutex::new(Vec::new()));
let plugin = Box::new(Recorder { inner: soundcraft_dsp::create("gain").unwrap(), sets: Arc::clone(&sets) });
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false }, sets)
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }, sets)
}
fn lane(slot: u8, param: &str, point: Option<f32>) -> AutomationLane {
+25
View File
@@ -698,6 +698,31 @@ fn an_insert_that_puts_out_nan_is_taken_out_until_the_next_reset() {
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
}
/// A plugin that fails again after its one reset retry stays failed for the session, instead of
/// oscillating the track's latency (and its delay-line reallocations) on every stop/seek (#919).
#[test]
fn a_repeatedly_failing_insert_gets_only_one_reset_retry() {
let (mut s, a) = session_with_dc(0.5, 48_000);
let _b = add_dc_track(&mut s, 0.5, 48_000);
s.track_mut(a).unwrap().mixer.inserts[2] = Some(Insert::new("clap:test.nan"));
let mut eng = MixEngine::new(48_000.0, 512);
eng.set_external_instances(true);
let both = render_block(&mut eng, &s, 0);
eng.adopt(nan(a, 2, 1));
let only_b = render_block(&mut eng, &s, 512);
assert!((only_b - both / 2.0).abs() < 1e-6, "{only_b} vs {both}");
// While failed it passes the track's audio through, dry.
assert_eq!(render_block(&mut eng, &s, 1024), both);
// The first reset grants the single retry; it fails again.
eng.reset();
assert_eq!(render_block(&mut eng, &s, 1536), only_b);
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
// A later reset does not retry it again: the block stays dry and the count does not move.
eng.reset();
assert_eq!(render_block(&mut eng, &s, 2048), both);
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
}
#[test]
fn nan_from_an_instrument_or_a_master_insert_is_contained() {
let mut s = synth_session(-6.0);
+5
View File
@@ -10,6 +10,11 @@ repository.workspace = true
[dependencies]
craft-mime.workspace = true
craft-ui.workspace = true
craft-behavior.workspace = true
craft-host.workspace = true
craft-keymap.workspace = true
craft-theme.workspace = true
craft-window.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
soundcraft-midi.workspace = true
+1 -1
View File
@@ -176,7 +176,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let current=state.compositions.iter().find(|(_,id)|*id==state.composition).map_or("Choose one…".to_string(),|(n,_)|n.clone());
// Locked while analyzing, so a finished analysis always matches the selection.
ui.add_enabled_ui(state.busy.is_none(),|ui|{
craft_ui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
egui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
for (name,id) in &state.compositions {
if ui.selectable_label(state.composition==*id,format!("{name} ({id})")).clicked() { state.composition=id.clone(); state.preview=None; }
}
+9 -2
View File
@@ -81,6 +81,7 @@ impl SoundApp {
synthetic_batch: None,
synthetic_pointer_active: false,
cancel_synthetic_pointer: false,
injected_acks: VecDeque::new(),
cancel_synthetic_keys: false,
cancel_synthetic_scroll: false,
input_before_scroll: None,
@@ -111,6 +112,9 @@ impl SoundApp {
system_fonts: true,
theme_applied: None,
docking_context: None,
docks: crate::docking::LiveDocks::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: crate::framework::host(),
sim: None,
record_hint: None,
quit_requested: false,
@@ -182,7 +186,7 @@ impl SoundApp {
// Frame pacing and the transport simulation use a monotonic host clock instead.
let dt = self.tick_dt();
self.last_frame = Some(self.uptime);
crate::control::expire_gestures(self);
crate::control::expire_gestures(self, ctx);
crate::control::drain(self, ctx);
self.note_recent_session();
self.apply_editor_edits();
@@ -315,7 +319,7 @@ impl SoundApp {
// Input preparation: remember this pass's real pointer/keyboard state, which `logic` (run
// before `ui` in each pass and alone on hidden ticks) uses for gestures and automation.
self.pointer_down = ctx.input(|i| i.pointer.any_down());
self.wants_keyboard = ctx.egui_wants_keyboard_input();
self.wants_keyboard = crate::framework::widget_has_keyboard(&ctx);
// The integration creates this Ui before logic resolves the current frame's palette.
ui.set_style(ctx.global_style());
if !self.fonts_ready {
@@ -356,8 +360,11 @@ impl SoundApp {
dialogs::show(self, &ctx);
aaf_import::show(self, &ctx);
updates_ui::show(self, &ctx);
self.run_framework_dialogs(ui);
// The sampler's drop rects are current now, so route any captured drop in this pass.
self.route_dropped_files();
// A scripted key (`ui.key`) is acknowledged by the framework's idle signal, not by egui's event list.
crate::control::injected_settled(self, &ctx);
// The pass that actually received the injected events has already dispatched their widget
// side effects, even when it then asks for another layout pass. `received_synthetic` was
// captured before menus and widgets, so a widget that consumed the event from InputState
+1 -1
View File
@@ -8,7 +8,7 @@ impl SoundApp {
self.note_host_geometry(ctx, raw);
// Expire before injecting: a gesture that can no longer reach a UI pass must not put one
// last copy of its events into this pass after its request was already canceled.
crate::control::expire_gestures(self);
crate::control::expire_gestures(self, ctx);
// A host that could not run a UI pass retains the input this hook mutated (eframe's
// `pending_raw_input`, the web runner's `input.raw`) and hands it back next tick. Strip the
// copy appended last time before appending the still-pending batch again: otherwise a
+1 -1
View File
@@ -70,7 +70,7 @@ fn slice() -> impl FnMut() -> bool {
/// Shows how far the running bounce got, with Cancel (or Esc).
pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let Some(job) = &app.bounce else { return };
let mut cancel = ctx.input(|i| i.key_pressed(egui::Key::Escape));
let mut cancel = crate::framework::escape_pressed(ctx);
egui::Modal::new(egui::Id::unique("bounce_progress")).show(ctx, |ui| {
ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);
ui.set_width(320.0);
+211
View File
@@ -0,0 +1,211 @@
//! One-shot completion slots for `ui.screenshot` captures.
//!
//! The app keeps request ids, paths, deadlines, settling and budgets in its request record
//! (`control::PendingShot`). A slot only correlates one capture with one record, checks the image against
//! a per-image byte bound, and wakes the owning viewport.
//!
//! [`CaptureSlot::new`] sends nothing: send its callback with [`egui::ViewportCommand::Screenshot`]
//! when the capture is due. The callback holds only a weak reference to the slot, so dropping the
//! slot releases its image and makes a late result inert. Every retry needs a
//! fresh slot and callback.
//!
//! The slot holds a strong [`egui::Context`]: keep it in the app's request record, never in
//! `Context`-owned data, which would form a cycle.
use std::mem::size_of;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use egui::{Color32, ColorImage, Context, ScreenshotCallback, ViewportId};
/// Why a completed screenshot was rejected and released.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CaptureError {
/// The checked pixel count, or its byte count, overflowed `usize`.
DimensionsOverflow { width: usize, height: usize },
/// The pixel buffer does not match the dimensions, or the image has no area.
MalformedImage { width: usize, height: usize, pixels: usize },
/// The image is larger than the slot's per-image byte bound.
ImageTooLarge { bytes: usize, max_bytes: usize },
}
impl core::fmt::Display for CaptureError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::DimensionsOverflow { width, height } => {
write!(f, "screenshot dimensions {width}×{height} overflow the checked pixel or byte count")
}
Self::MalformedImage { width, height, pixels } => write!(f, "screenshot has {pixels} pixels for its {width}×{height} dimensions"),
Self::ImageTooLarge { bytes, max_bytes } => write!(f, "screenshot uses {bytes} bytes, over the {max_bytes}-byte per-image limit"),
}
}
}
impl std::error::Error for CaptureError {}
enum SlotState {
Pending,
Ready(Result<Arc<ColorImage>, CaptureError>),
Taken,
Cancelled,
}
struct Shared {
state: Mutex<SlotState>,
/// The live request owns the strong context; the callback only upgrades it briefly to wake.
context: Context,
viewport: ViewportId,
max_image_bytes: usize,
}
/// The live request side of a capture. Dropping it cancels the completion and releases any
/// retained image.
#[must_use = "the slot must be kept alive to receive and take the screenshot"]
pub(crate) struct CaptureSlot {
shared: Arc<Shared>,
}
impl CaptureSlot {
/// A completion slot for a capture of `viewport` and its one-shot callback. `max_image_bytes`
/// bounds this one image; the app reserves its aggregate budget itself.
pub(crate) fn new(context: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback) {
let shared = Arc::new(Shared { state: Mutex::new(SlotState::Pending), context: context.clone(), viewport, max_image_bytes });
let weak = Arc::downgrade(&shared);
let callback = ScreenshotCallback::new(move |image| complete(&weak, image));
(Self { shared }, callback)
}
/// The completed result, at most once; `None` while pending and after an
/// earlier take. The request record knows which.
pub(crate) fn take(&self) -> Option<Result<Arc<ColorImage>, CaptureError>> {
let mut state = lock(&self.shared.state);
if !matches!(&*state, SlotState::Ready(_)) {
return None;
}
match core::mem::replace(&mut *state, SlotState::Taken) {
SlotState::Ready(result) => Some(result),
_ => None,
}
}
}
impl Drop for CaptureSlot {
fn drop(&mut self) {
close(&self.shared);
}
}
impl core::fmt::Debug for CaptureSlot {
/// The viewport only: logging never holds or dumps screenshot contents.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CaptureSlot").field("viewport", &self.shared.viewport).finish_non_exhaustive()
}
}
/// Locks the slot state, recovering from poisoning. Release the guard before calling into the
/// context: a repaint observer may take or cancel re-entrantly.
fn lock(state: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Marks the slot closed; the retained image drops after the mutex is released.
fn close(shared: &Shared) {
let previous = {
let mut state = lock(&shared.state);
core::mem::replace(&mut *state, SlotState::Cancelled)
};
drop(previous);
}
/// Checks and stores a completed image, then wakes the owning viewport, with the slot lock
/// released. A cancelled, taken or dropped slot stores nothing and does not wake.
fn complete(weak: &Weak<Shared>, image: Arc<ColorImage>) {
let Some(shared) = weak.upgrade() else { return };
let result = checked_image(image, shared.max_image_bytes);
let wake = {
let mut state = lock(&shared.state);
if matches!(&*state, SlotState::Pending) {
*state = SlotState::Ready(result);
true
} else {
false
}
};
if wake {
shared.context.request_repaint_of(shared.viewport);
}
}
/// `image` when it has area, its buffer matches its size, and its byte count (checked) is within
/// `max_image_bytes`.
fn checked_image(image: Arc<ColorImage>, max_image_bytes: usize) -> Result<Arc<ColorImage>, CaptureError> {
let [width, height] = image.size;
if width == 0 || height == 0 {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
let pixels = width.checked_mul(height).ok_or(CaptureError::DimensionsOverflow { width, height })?;
let bytes = pixels.checked_mul(size_of::<Color32>()).ok_or(CaptureError::DimensionsOverflow { width, height })?;
if image.pixels.len() != pixels {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
if bytes > max_image_bytes {
return Err(CaptureError::ImageTooLarge { bytes, max_bytes: max_image_bytes });
}
Ok(image)
}
#[cfg(test)]
mod tests {
use super::*;
fn image(size: [usize; 2]) -> Arc<ColorImage> {
Arc::new(ColorImage::filled(size, Color32::RED))
}
fn observe_repaints(ctx: &Context) -> Arc<Mutex<Vec<ViewportId>>> {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = requests.clone();
ctx.set_repaint_observer(move |info| observed.lock().unwrap().push(info.viewport_id));
requests
}
#[test]
fn a_completion_wakes_its_viewport_and_is_taken_once() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("window");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
assert!(slot.take().is_none(), "pending");
let shot = image([2, 1]);
callback.complete(shot.clone());
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &shot));
assert!(slot.take().is_none(), "taken once");
assert_eq!(*requests.lock().unwrap(), [viewport]);
}
#[test]
fn a_dropped_slot_releases_a_late_image_without_waking() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
drop(slot);
let late = image([2, 2]);
let weak = Arc::downgrade(&late);
callback.complete(late);
assert!(weak.upgrade().is_none());
assert!(requests.lock().unwrap().is_empty());
}
#[test]
fn oversized_malformed_and_overflowing_images_are_errors() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
callback.complete(image([3, 3]));
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![Color32::RED; 3] }));
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [usize::MAX, 2], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { .. }))));
}
}
+46 -10
View File
@@ -17,7 +17,8 @@
//! inspect, command or screenshot after the gesture it follows.
use crate::SoundApp;
use craft_ui::capture::CaptureSlot;
use crate::capture::CaptureSlot;
use craft_ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use std::sync::mpsc::{Receiver, Sender, channel};
use web_time::Instant;
@@ -36,7 +37,7 @@ impl ControlRequest {
}
/// One admitted `ui.screenshot` request. The app owns the strong completion slot; the callback the
/// renderer receives holds only a weak reference to it (see `craft_ui::capture`).
/// renderer receives holds only a weak reference to it (see `crate::capture`).
pub(crate) struct PendingShot {
token: u64,
/// Taken once the single reply (success, timeout, cancellation or failure) was sent.
@@ -278,9 +279,32 @@ pub(crate) struct GestureAck {
response: Value,
}
/// A `ui.key` request whose reply waits for the framework's injected input to run: the runtime owns the key's path
/// (it takes keys such as Escape out of egui's event list), so only its own idle signal says the key was delivered.
pub(crate) struct InjectedAck {
deadline: Instant,
reply: Option<Sender<Value>>,
response: Value,
}
/// True while a scripted gesture has events waiting or an applied batch still needs acknowledging.
pub(crate) fn gesture_pending(app: &SoundApp) -> bool {
!app.gesture_acks.is_empty() || !app.synthetic.is_empty() || app.synthetic_batch.is_some()
!app.gesture_acks.is_empty() || !app.synthetic.is_empty() || app.synthetic_batch.is_some() || !app.injected_acks.is_empty()
}
/// Reply to every queued `ui.key` once the framework's injected input has run, asked at the end of the pass that ran
/// the key (a pass egui repeats does not count).
pub(crate) fn injected_settled(app: &mut SoundApp, ctx: &egui::Context) {
if app.injected_acks.is_empty() || !WindowHost::of(ctx).injected_idle_at_pass_end() {
return;
}
for mut ack in std::mem::take(&mut app.injected_acks) {
if let Some(tx) = ack.reply.take() {
let _ = tx.send(ack.response);
}
}
// The next request queued behind this key needs a logic tick to be drained now that the barrier is gone.
ctx.request_repaint();
}
/// Count one delivered batch against the front gesture. Batches never straddle requests (a key
@@ -307,8 +331,16 @@ pub(crate) fn synthetic_delivered(app: &mut SoundApp, delivered: usize) {
/// A gesture that cannot reach a UI pass (a host that never paints) must not wedge every later
/// control request. Cancel the whole pending gesture chain: FIFO means no later request can run
/// while an earlier undelivered click is still waiting.
pub(crate) fn expire_gestures(app: &mut SoundApp) {
pub(crate) fn expire_gestures(app: &mut SoundApp, ctx: &egui::Context) {
let now = app.clock_now();
if app.injected_acks.iter().any(|ack| now >= ack.deadline) {
WindowHost::of(ctx).withdraw_injected(egui::ViewportId::ROOT);
for mut ack in std::mem::take(&mut app.injected_acks) {
if let Some(tx) = ack.reply.take() {
let _ = tx.send(err("synthetic input was not delivered"));
}
}
}
if !app.gesture_acks.iter().any(|ack| now >= ack.deadline) {
return;
}
@@ -544,12 +576,16 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
"ui.key" => {
let name = p.get("key").and_then(Value::as_str).unwrap_or("");
let Some(key) = key_from(name) else { return Some(err(format!("unknown key `{name}`"))) };
let m = mods(p);
let events = vec![
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m },
egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: m },
];
return queue_reply(app, req, events, json!({}));
let Some(key) = craft_keymap::Key::from_egui(key) else { return Some(err(format!("key `{name}` has no keymap key"))) };
let mods = craft_keymap::Mods::from_egui(&mods(p), craft_keymap::egui::platform(ctx));
// The framework's injected input carries the key through its own stages and says when it has run.
WindowHost::of(ctx).inject_key(egui::ViewportId::ROOT, key, mods, false);
app.injected_acks.push_back(InjectedAck {
deadline: app.clock_now() + GESTURE_TIMEOUT,
reply: Some(req.reply.clone()),
response: ok(json!({})),
});
return None;
}
"ui.text" => {
let t = p.get("text").and_then(Value::as_str).unwrap_or("");
+43 -29
View File
@@ -93,6 +93,7 @@ fn tmp(name: &str) -> PathBuf {
#[test]
fn a_screenshot_completes_once_and_writes_one_file() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("success");
let _ = std::fs::remove_file(&path);
@@ -114,6 +115,7 @@ fn a_screenshot_completes_once_and_writes_one_file() {
#[test]
fn a_callback_after_the_deadline_times_out_without_writing() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("late");
let reply = request(&mut a, Some(&path));
@@ -132,6 +134,7 @@ fn a_callback_after_the_deadline_times_out_without_writing() {
#[test]
fn a_session_change_cancels_the_request_and_releases_its_pixels() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("document");
let reply = request(&mut a, Some(&path));
@@ -150,6 +153,7 @@ fn a_session_change_cancels_the_request_and_releases_its_pixels() {
#[test]
fn admission_rejects_more_than_eight_pending_requests() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
for i in 0..MAX_PENDING_SHOTS {
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
@@ -165,6 +169,7 @@ fn admission_rejects_more_than_eight_pending_requests() {
#[test]
fn admission_rejects_an_image_over_the_per_image_and_aggregate_budgets() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
let mut big = raw_input(5000.0, 5000.0, 8192);
a.raw_input_hook(&ctx, &mut big);
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
@@ -190,6 +195,7 @@ fn admission_rejects_an_image_over_the_per_image_and_aggregate_budgets() {
#[test]
fn a_changed_window_retries_once_instead_of_writing_stale_pixels() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = tmp("retry");
let reply = request(&mut a, Some(&path));
@@ -248,6 +254,7 @@ fn a_missing_max_texture_side_uses_the_last_known_limit() {
#[test]
fn a_window_without_geometry_reports_no_capturable_size() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.host_geometry = Some(CaptureGeometry { points: egui::Vec2::ZERO, pixels_per_point: 1.0, max_texture_side: 8192, focused: true });
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({}));
let e = admit(&mut a, &ctx, &req).expect_err("no capturable size");
@@ -259,6 +266,7 @@ fn a_window_without_geometry_reports_no_capturable_size() {
#[test]
fn a_document_replaced_outside_run_cancels_a_pending_capture() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let reply = request(&mut a, None);
let out = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
@@ -278,6 +286,7 @@ fn a_document_replaced_outside_run_cancels_a_pending_capture() {
#[test]
fn a_queued_click_is_applied_before_a_following_inspect_and_screenshot() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let kick = a.engine.session().track_by_name("Kick").expect("demo has Kick").id;
assert!(!a.engine.session().track(kick).expect("kick").mixer.mute);
@@ -338,6 +347,7 @@ fn a_queued_click_is_applied_before_a_following_inspect_and_screenshot() {
#[test]
fn a_capture_slot_is_bounded_by_its_own_reservation() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let (tx, rx) = channel();
let (req, first) = ControlRequest::new("ui.screenshot", json!({}));
@@ -379,6 +389,7 @@ fn png_bytes_checks_its_dimensions_and_allocation() {
#[test]
fn control_input_queues_and_text_are_bounded() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.synthetic = (0..MAX_SYNTHETIC_EVENTS).map(|_| egui::Event::PointerMoved(egui::pos2(0.0, 0.0))).collect();
let (req, _reply) = ControlRequest::new("ui.move", json!({"x": 1.0, "y": 2.0}));
let v = handle(&mut a, &ctx, &req).expect("the refusal replies immediately");
@@ -405,6 +416,7 @@ fn control_input_queues_and_text_are_bounded() {
#[test]
fn a_very_long_screenshot_path_is_refused_before_it_is_retained() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let path = "x".repeat(MAX_SHOT_PATH_BYTES + 1);
let (req, _reply) = ControlRequest::new("ui.screenshot", json!({"path": path}));
@@ -418,10 +430,11 @@ fn a_very_long_screenshot_path_is_refused_before_it_is_retained() {
#[test]
fn an_undelivered_gesture_is_canceled_without_wedging_the_next_request() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
let (req, reply) = ControlRequest::new("ui.click", json!({"x": 10.0, "y": 10.0}));
assert!(handle(&mut a, &ctx, &req).is_none(), "the click waits for a UI pass");
a.advance_test_clock(Duration::from_secs(16));
expire_gestures(&mut a);
expire_gestures(&mut a, &ctx);
let v = reply.try_recv().expect("the canceled gesture has exactly one reply");
assert_eq!(v["ok"], false, "{v}");
assert!(v["error"].as_str().unwrap_or_default().contains("not delivered"), "{v}");
@@ -440,6 +453,7 @@ fn an_undelivered_gesture_is_canceled_without_wedging_the_next_request() {
fn a_timed_out_consumed_press_cancels_without_clicking_and_the_next_click_works() {
for expires_after_hook in [false, true] {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let kick = a.engine.session().track_by_name("Kick").unwrap().id;
@@ -489,48 +503,28 @@ fn a_timed_out_consumed_press_cancels_without_clicking_and_the_next_click_works(
/// An expired scripted shortcut never reaches widgets or end-of-pass handling, while a simultaneous host shortcut
/// still runs and a later script succeeds.
#[test]
fn a_timed_out_scripted_key_after_the_hook_does_not_run_and_the_next_key_works() {
fn a_timed_out_scripted_key_does_not_run_and_the_next_key_works() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 1, "format": "stereo"})).unwrap();
let depth = a.engine.undo_history().len();
assert!(depth > 0, "the test needs an undoable edit");
let applied = a.synthetic_applied_batches;
let quickpunch = a.engine.session().edit.quickpunch;
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "z", "cmd": true}));
assert!(handle(&mut a, &ctx, &req).is_none());
let mut raw = raw_input(800.0, 600.0, 8192);
// A real, unrelated shortcut in the same pass must still be dispatched after the expired
// scripted batch is removed.
let command_shift = egui::Modifiers { command: true, shift: true, ..egui::Modifiers::NONE };
raw.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: command_shift });
raw.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: false, repeat: false, modifiers: command_shift });
a.raw_input_hook(&ctx, &mut raw);
assert!(a.synthetic_batch.is_some(), "the key batch waits for a UI pass");
assert!(gesture_pending(&a), "the key waits for the framework to run it");
// The deadline crosses after the hook handed the key to egui but before logic and widgets.
// The deadline crosses before any pass ran the key.
a.advance_test_clock(Duration::from_secs(16));
let mut out = ctx.run_ui(raw, |ui| {
a.logic(ui.ctx());
a.ui(ui);
});
out.textures_delta.clear();
let _ = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
let canceled = reply.try_recv().expect("one cancellation reply");
assert_eq!(canceled["ok"], false, "{canceled}");
assert!(a.synthetic_batch.is_none(), "the expired batch is dropped");
assert_eq!(a.synthetic_applied_batches, applied, "an expired batch is not delivered");
assert_eq!(a.engine.undo_history().len(), depth, "the expired key must not run its shortcut");
assert_eq!(a.engine.session().edit.quickpunch, !quickpunch, "a simultaneous host shortcut still runs");
assert!(!a.cancel_synthetic_keys);
assert!(
ctx.input(|i| !i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Z, .. }))),
"the expired key is gone from the pass, not left for widgets or end-of-pass shortcuts"
);
assert!(!gesture_pending(&a));
let _ = frame(&mut a, &ctx, raw_input(800.0, 600.0, 8192));
assert_eq!(a.engine.undo_history().len(), depth, "a later frame must not replay it");
assert_eq!(a.engine.undo_history().len(), depth, "the expired key must not run its shortcut, now or later");
// A fresh gesture after the timeout still works and runs exactly once.
// A fresh key after the timeout still works and runs exactly once.
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "z", "cmd": true}));
assert!(handle(&mut a, &ctx, &req).is_none());
deliver_gestures(&mut a, &ctx);
@@ -538,6 +532,19 @@ fn a_timed_out_scripted_key_after_the_hook_does_not_run_and_the_next_key_works()
assert_eq!(a.engine.undo_history().len(), depth - 1, "a completed key still undoes exactly once");
}
/// The framework takes Escape out of egui's event list; the key is still acknowledged.
#[test]
fn a_scripted_escape_is_acknowledged() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Escape"}));
assert!(handle(&mut a, &ctx, &req).is_none());
deliver_gestures(&mut a, &ctx);
assert_eq!(reply.try_recv().expect("an acknowledgement")["ok"], true);
}
/// Current timeline zoom, horizontal scroll and vertical scroll, compared before and after a gesture.
fn view(a: &SoundApp) -> (f64, i64, f32) {
let zoom = a.engine.session().edit.zoom;
@@ -573,6 +580,7 @@ fn host_line_wheel(dy: f32) -> egui::Event {
#[test]
fn a_timed_out_scripted_scroll_after_the_hook_does_not_scroll_or_keep_smoothing() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
// Make the track area overflow so a real wheel would actually move the view.
@@ -649,6 +657,7 @@ fn a_timed_out_scripted_scroll_after_the_hook_does_not_scroll_or_keep_smoothing(
#[test]
fn a_timed_out_scripted_zoom_after_the_hook_does_not_zoom_and_the_next_zoom_works_once() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let at = timeline_center(&a);
@@ -710,6 +719,7 @@ fn a_timed_out_scripted_zoom_after_the_hook_does_not_zoom_and_the_next_zoom_work
#[test]
fn a_fresh_identical_host_wheel_after_a_drawn_expiry_is_not_swallowed() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 20, "format": "stereo"})).unwrap();
@@ -749,6 +759,7 @@ fn a_fresh_identical_host_wheel_after_a_drawn_expiry_is_not_swallowed() {
#[test]
fn a_host_key_held_across_passes_survives_a_replayed_scroll_cancel() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 20, "format": "stereo"})).unwrap();
@@ -790,6 +801,7 @@ fn a_host_key_held_across_passes_survives_a_replayed_scroll_cancel() {
#[test]
fn an_expiry_in_a_discarded_pass_does_not_replay_host_events() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
a.run("track.new", json!({"count": 1, "format": "stereo"})).unwrap();
@@ -842,6 +854,7 @@ fn an_expiry_in_a_discarded_pass_does_not_replay_host_events() {
#[test]
fn a_timed_out_track_drag_cancels_without_dropping_and_the_next_drag_works() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
a.advance_test_clock(Duration::ZERO);
warm(&mut a, &ctx);
let before: Vec<_> = a.engine.session().tracks.iter().map(|track| track.id).collect();
@@ -882,6 +895,7 @@ fn a_timed_out_track_drag_cancels_without_dropping_and_the_next_drag_works() {
#[test]
fn scroll_reports_the_wheel_and_trackpad_sources_after_delivery() {
let (mut a, ctx) = (app(), egui::Context::default());
crate::framework::install_headless(&ctx);
warm(&mut a, &ctx);
let (req, reply) = ControlRequest::new("ui.scroll", json!({"x": 10.0, "y": 10.0, "dy": -30.0, "unit": "line", "steps": 2}));
assert!(handle(&mut a, &ctx, &req).is_none(), "the reply waits for delivery");
+1 -1
View File
@@ -221,7 +221,7 @@ fn contributors_toolbar(ui: &mut egui::Ui, v: &mut View) {
}
ui.separator();
let sort = ui.label(crate::localization::text("Sort"));
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
let combo = egui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, crate::localization::text(k.label().0)).clicked() {
v.key = k;
+8 -8
View File
@@ -512,8 +512,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
// button only when no widget has the keyboard focus or a text field has it. A held Enter's repeats do not press it.
let fresh_enter =
|i: &egui::InputState| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }));
let enter = !first_frame && ctx.input(fresh_enter) && (ctx.memory(|m| m.focused().is_none()) || ctx.text_edit_focused());
let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape));
let enter = !first_frame && ctx.input(fresh_enter) && (!crate::framework::widget_has_keyboard(ctx) || ctx.text_edit_focused());
let esc = crate::framework::escape_pressed(ctx);
egui::Window::new(egui::RichText::new(crate::localization::text(&title)).font(bold(13.0)))
.id(egui::Id::unique(&title))
.collapsible(false)
@@ -536,7 +536,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
ui.label(crate::localization::text("Name"));
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
});
craft_ui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
for r in soundcraft_time::SampleRate::COMMON {
ui.selectable_value(sample_rate, r, format!("{r} Hz"));
}
@@ -552,12 +552,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::Bounce { path, format, bit_depth, normalize, dither } => {
bounce_file_row(app, ui, path, format);
ui.horizontal(|ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
for &f in EncodeFormat::ALL {
ui.selectable_value(format, f, f.container().name());
}
});
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
for b in ["16", "24", "32f"] {
ui.selectable_value(bit_depth, b.to_string(), crate::localized_format!("{b}-bit", b = b));
}
@@ -701,12 +701,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
}
Dialog::Session { frame_rate, bit_depth } => {
craft_ui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
for r in soundcraft_time::FrameRate::ALL {
ui.selectable_value(frame_rate, r.label().to_string(), crate::localization::text(r.label()));
}
});
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
for b in ["16", "24", "32f"] {
ui.selectable_value(bit_depth, b.to_string(), crate::localization::text(b));
}
@@ -719,7 +719,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let s = app.engine.session();
ui.horizontal(|ui| {
let count_label = ui.radio_value(by, LoopBy::Count, crate::localization::text("Number of Loops"));
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=512)).labelled_by(count_label.id);
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=1000)).labelled_by(count_label.id);
});
ui.horizontal(|ui| {
let length_label = ui.radio_value(by, LoopBy::Length, crate::localization::text("Loop Length"));
+4 -4
View File
@@ -183,7 +183,7 @@ impl NewTracks {
ui.label(crate::localization::text("new"));
let format = if has_format(&row.kind) {
Some(
craft_ui::ComboBox::from_id_salt("nt_fmt")
egui::ComboBox::from_id_salt("nt_fmt")
.width(widths.format)
.selected_text(crate::localization::text(&row.format))
.show_ui(ui, |ui| {
@@ -198,7 +198,7 @@ impl NewTracks {
ui.allocate_space(vec2(widths.format, ui.spacing().interact_size.y));
None
};
let kind = craft_ui::ComboBox::from_id_salt("nt_kind")
let kind = egui::ComboBox::from_id_salt("nt_kind")
.width(widths.kind)
.selected_text(crate::localization::text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label())))
.show_ui(ui, |ui| {
@@ -213,7 +213,7 @@ impl NewTracks {
let timebase = if has_timebase(&row.kind) {
ui.label(crate::localization::text("in"));
Some(
craft_ui::ComboBox::from_id_salt("nt_tb")
egui::ComboBox::from_id_salt("nt_tb")
.width(widths.timebase)
.selected_text(crate::localization::text(if row.timebase == "ticks" { "Ticks" } else { "Samples" }))
.show_ui(ui, |ui| {
@@ -360,7 +360,7 @@ mod tests {
fn harness() -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
assert!(app.dialogs.open_for_command(&app.engine, "track.new"));
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
app.ui(ui);
+17 -14
View File
@@ -162,13 +162,14 @@ fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) {
.open(&mut open)
.default_size(vec2(360.0, 200.0))
.show(ctx, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Curve"))
.selected_text(crate::localization::text(&app.ops.tempo_curve))
.show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Curve")).selected_text(crate::localization::text(&app.ops.tempo_curve)).show_ui(
ui,
|ui| {
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), crate::localization::text(c));
}
});
},
);
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix(crate::localization::text("start bpm ")))
.accessible_name(crate::localization::text("Start tempo (BPM)"));
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix(crate::localization::text("end bpm ")))
@@ -200,20 +201,21 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) {
.open(&mut open)
.default_size(vec2(360.0, 200.0))
.show(ctx, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
.selected_text(crate::localization::text(&app.ops.time_op))
.show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Operation")).selected_text(crate::localization::text(&app.ops.time_op)).show_ui(
ui,
|ui| {
for c in ["insert", "cut", "change meter", "move song start"] {
ui.selectable_value(&mut app.ops.time_op, c.to_string(), crate::localization::text(c));
}
});
},
);
match app.ops.time_op.as_str() {
"change meter" => {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64))
.accessible_name(crate::localization::text("Meter numerator"));
ui.label(crate::localization::text("/"));
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
let den = egui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
for d in [2u32, 4, 8, 16] {
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
}
@@ -253,16 +255,17 @@ fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) {
.open(&mut open)
.default_size(vec2(360.0, 220.0))
.show(ctx, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
.selected_text(crate::localization::text(&app.ops.midi_op))
.show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Operation")).selected_text(crate::localization::text(&app.ops.midi_op)).show_ui(
ui,
|ui| {
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), crate::localization::text(c));
}
});
},
);
match app.ops.midi_op.as_str() {
"quantize" => {
craft_ui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
}
+5 -6
View File
@@ -155,12 +155,11 @@ fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples)
pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
egui::Grid::new("spot").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
let scale = ui.label(crate::localization::text("Time Scale"));
let time_scale =
craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
for f in TimeFormat::ALL {
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
}
});
let time_scale = egui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
for f in TimeFormat::ALL {
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
}
});
time_scale.response.labelled_by(scale.id);
ui.end_row();
for (i, label) in FIELDS.into_iter().enumerate() {
+447 -174
View File
@@ -1,11 +1,21 @@
//! Application panel identities and persistence around the shared docking renderer.
//! Document contents remain owned by their existing view implementations.
//! Application panel identities and persistence around craft-ui's `DockArea`. Document contents remain owned by
//! their existing view implementations.
//!
//! `UiState::docking` and `UiState::mix_docking` are the saved workspaces and the source of truth. The dock shows an
//! `Arc` of each ([`LiveDocks`]), kept while the saved workspace is unchanged; every change the dock reports goes
//! through [`command_for`] like a `ui.dock` command.
use craft_ui::docking::{
Action, Column, DockArea, DockCommand, DockError, DockOperation, DockStyle, FloatSpace, Floating, Group, Layout, Location, Node, PanelLimits,
Permissions, Placement, Side, Target, UiDock, Zone, ZoneName,
use std::sync::Arc;
use craft_behavior::DockSide;
use craft_behavior::dock::{
Action, Column, DockEdge, DockError, DockPlacement, Floating, Group, Layout, Location, Node, Permissions, SplitSize, Target,
};
use craft_ui::layout::{SplitAxis, SplitSize};
use craft_behavior::flow::Axis;
use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use egui::{Rect, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -42,48 +52,41 @@ pub const CLIPS_WIDTH: f32 = 230.0;
pub const MIDI_HEIGHT: f32 = 320.0;
/// An Edit or Mix panel arrangement, saved with the UI preferences.
pub type Workspace = craft_ui::docking::Workspace<Panel>;
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
const MIDI_TAB_HEIGHT: f32 = 26.0;
/// The height the MIDI editor's tab adds above its body in the default layout.
const MIDI_TAB_HEIGHT: f32 = 28.0;
/// The document view stays docked and open, and panels open in splits beside it.
fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Canvas { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
if *panel == Panel::Canvas { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
}
fn tabs(panel: Panel) -> Node<Panel> {
Node::Tabs { panels: vec![panel], active: 0 }
Node::tabs(vec![panel], 0)
}
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
}
/// The dock area that draws the Edit or Mix workspace.
/// The id the Edit or Mix dock area is drawn under.
pub fn area_id(window: crate::MainWindow) -> egui::Id {
egui::Id::unique(("soundcraft-docking", window == crate::MainWindow::Edit))
}
fn area(edit: bool) -> egui::Id {
area_id(if edit { crate::MainWindow::Edit } else { crate::MainWindow::Mix })
}
/// A dock on `side` with one column holding `panel`.
fn dock(side: Side, panel: Panel, width: f32) -> Node<Panel> {
Node::Dock { side, columns: vec![Column::new(vec![Group::new(vec![panel], 0)], width)] }
fn dock(side: DockEdge, panel: Panel, width: f32) -> Node<Panel> {
Node::dock(side, vec![Column::new(vec![Group::new(vec![panel], 0)]).with_width(width)])
}
const MEMORY_RECT: [f32; 4] = [160.0, 120.0, 480.0, 280.0];
const HISTORY_RECT: [f32; 4] = [680.0, 120.0, 260.0, 300.0];
const MEMORY_RECT: Rect = Rect::from_min_max(pos2(160.0, 120.0), pos2(640.0, 400.0));
const HISTORY_RECT: Rect = Rect::from_min_max(pos2(680.0, 120.0), pos2(940.0, 420.0));
/// The floating windows both windows start with. Fixed ids: the default is rebuilt every frame
/// and must stay the same windows.
fn default_floating() -> Vec<Floating<Panel>> {
vec![Floating::single(vec![Panel::Memory], 0, MEMORY_RECT).with_id(1), Floating::single(vec![Panel::History], 0, HISTORY_RECT).with_id(2)]
vec![Floating::single(1, vec![Panel::Memory], 0, MEMORY_RECT), Floating::single(2, vec![Panel::History], 0, HISTORY_RECT)]
}
/// Where a panel that floats in the default layouts floats.
fn default_float(panel: Panel) -> Option<[f32; 4]> {
fn default_float(panel: Panel) -> Option<Rect> {
match panel {
Panel::Memory => Some(MEMORY_RECT),
Panel::History => Some(HISTORY_RECT),
@@ -92,10 +95,10 @@ fn default_float(panel: Panel) -> Option<[f32; 4]> {
}
/// The dock side and column width a panel opens in when it has no recorded place.
fn default_dock(panel: Panel) -> Option<(Side, f32)> {
fn default_dock(panel: Panel) -> Option<(DockEdge, f32)> {
match panel {
Panel::Tracks => Some((Side::Start, TRACKS_WIDTH)),
Panel::Clips => Some((Side::End, CLIPS_WIDTH)),
Panel::Tracks => Some((DockEdge::Start, TRACKS_WIDTH)),
Panel::Clips => Some((DockEdge::End, CLIPS_WIDTH)),
_ => None,
}
}
@@ -103,30 +106,21 @@ fn default_dock(panel: Panel) -> Option<(Side, f32)> {
/// The Edit window's built-in arrangement: Tracks and Groups in a full-height start dock,
/// Clips in a full-height end dock, and the MIDI editor under the session view between them.
pub fn edit_default() -> Workspace {
let session = split(SplitAxis::Vertical, SplitSize::FixedSecond(MIDI_HEIGHT + MIDI_TAB_HEIGHT), tabs(Panel::Canvas), tabs(Panel::Midi));
Workspace::new(Layout {
root: Some(split(
SplitAxis::Horizontal,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
split(SplitAxis::Horizontal, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(Side::End, Panel::Clips, CLIPS_WIDTH)),
)),
floating: default_floating(),
})
let session = Node::split(Axis::Y, SplitSize::FixedSecond(MIDI_HEIGHT + MIDI_TAB_HEIGHT), tabs(Panel::Canvas), tabs(Panel::Midi));
let root = Node::split(
Axis::X,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH),
Node::split(Axis::X, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(DockEdge::End, Panel::Clips, CLIPS_WIDTH)),
);
Workspace::new(Layout::new(Some(root), default_floating()))
}
/// The Mix window's built-in arrangement: Tracks and Groups in a start dock beside the mixer.
/// The timeline-only Clips and MIDI panels stay in Edit.
pub fn mix_default() -> Workspace {
Workspace::new(Layout {
root: Some(split(
SplitAxis::Horizontal,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
tabs(Panel::Canvas),
)),
floating: default_floating(),
})
let root = Node::split(Axis::X, SplitSize::FixedFirst(TRACKS_WIDTH), dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH), tabs(Panel::Canvas));
Workspace::new(Layout::new(Some(root), default_floating()))
}
/// The version of the saved panel layouts, kept in [`crate::UiState::docking_version`]. Version 1
@@ -154,7 +148,7 @@ fn canvas_placement(node: &Node<Panel>) -> Option<Result<(), &'static str>> {
Node::Tabs { panels, .. } if panels.contains(&Panel::Canvas) => {
Some(if panels.len() == 1 { Ok(()) } else { Err("The document view cannot share a tab group") })
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => Some(Err("The document view cannot be collapsed")),
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => Some(Err("The document view cannot be collapsed")),
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Canvas)) => {
Some(Err("The document view cannot join a dock column"))
}
@@ -162,23 +156,24 @@ fn canvas_placement(node: &Node<Panel>) -> Option<Result<(), &'static str>> {
}
}
/// Check a workspace against craft-ui's rules and SoundCraft's own: saved settings cannot
/// Check a workspace against craft-behavior's rules and SoundCraft's own: saved settings cannot
/// float, hide, collapse or share the protected document view.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = &workspace.layout;
if !layout.contains(&Panel::Canvas) || workspace.hidden.len() > Panel::ALL.len() {
let layout = workspace.layout();
if !layout.contains(&Panel::Canvas) || workspace.hidden().len() > Panel::ALL.len() {
return Err("The panel layout must contain its document view and bounded hidden panels".into());
}
if layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
return Err("The document view cannot float".into());
}
layout.root.as_ref().and_then(canvas_placement).unwrap_or(Err("The document view cannot float"))?;
for (panel, location) in &workspace.hidden {
for (panel, location) in workspace.hidden() {
if *panel == Panel::Canvas {
return Err("A hidden panel has an invalid or duplicate identity".into());
}
if location.anchor == Some(Panel::Canvas) && matches!(location.placement, Placement::Tab { .. } | Placement::Split(Zone::Center)) {
if location.anchor == Some(Panel::Canvas) && matches!(location.placement, DockPlacement::Tab { .. } | DockPlacement::Split(DockSide::Center))
{
return Err("A hidden panel cannot restore over the document view".into());
}
let mut probe = layout.clone();
@@ -194,7 +189,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
/// [`validate`] plus the Mix window's rule: Clips and MIDI stay in Edit.
pub fn validate_mix(workspace: &Workspace) -> Result<(), String> {
validate(workspace)?;
if workspace.layout.contains(&Panel::Clips) || workspace.layout.contains(&Panel::Midi) {
if workspace.layout().contains(&Panel::Clips) || workspace.layout().contains(&Panel::Midi) {
return Err("Clips and MIDI panels belong to the Edit window".into());
}
Ok(())
@@ -211,17 +206,17 @@ fn checked(workspace: &mut Workspace, change: impl FnOnce(&mut Workspace) -> Res
}
fn apply(workspace: &mut Workspace, action: Action<Panel>) -> Result<(), String> {
checked(workspace, |next| next.apply(action, permissions).map(drop))
checked(workspace, |next| next.apply(action, false, permissions).map(drop))
}
/// Whether [`Workspace::set_visible`] can actually put `panel` back at its recorded place.
/// It follows the recorded location and the chain of hidden anchors; when none of that
/// restores, craft-ui falls back to an unanchored open, which since craft-ui 650b1c0b chooses
/// a dock group or right edge instead of reporting the missing anchor. Probe each chain
/// location with the public [`Layout::restore`] on a clone, so a deleted anchor is recognized
/// before calling in; craft-ui still performs the restore and rewrites the chain itself.
/// restores, craft-behavior falls back to an unanchored open, which chooses a dock group or
/// right edge instead of reporting the missing anchor. Probe each chain location with the
/// public [`Layout::restore`] on a clone, so a deleted anchor is recognized before calling in;
/// craft-behavior still performs the restore and rewrites the chain itself.
fn restores(workspace: &Workspace, panel: Panel) -> bool {
let recorded = |p: &Panel| workspace.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location.clone());
let recorded = |p: &Panel| workspace.hidden().iter().find(|(q, _)| q == p).map(|(_, location)| location.clone());
let mut chain: Vec<Location<Panel>> = Vec::new();
let mut seen = vec![panel];
let mut current = panel;
@@ -234,13 +229,14 @@ fn restores(workspace: &Workspace, panel: Panel) -> bool {
}
// Like the chain itself, the panel's own group/column state applies to every attempt.
let group = chain.first().and_then(|location| location.group.clone());
// Revisit this eligibility probe when updating the pinned craft-ui restore algorithm.
// Revisit this eligibility probe when updating the pinned craft-behavior restore algorithm.
chain
.iter()
.rev()
.find_map(|location| {
let location = Location { group: group.clone().or_else(|| location.group.clone()), ..location.clone() };
let mut probe = workspace.layout.clone();
let mut location = location.clone();
location.group = group.clone().or(location.group);
let mut probe = workspace.layout().clone();
match probe.restore(panel, &location) {
Err(DockError::MissingTarget) => None,
result => Some(result.is_ok()),
@@ -250,10 +246,10 @@ fn restores(workspace: &Workspace, panel: Panel) -> bool {
}
/// The first panel of the dock on `side`, when that dock is shown.
fn dock_panel(node: &Node<Panel>, side: Side) -> Option<Panel> {
fn dock_panel(node: &Node<Panel>, side: DockEdge) -> Option<Panel> {
match node {
Node::Split { first, second, .. } => dock_panel(first, side).or_else(|| dock_panel(second, side)),
Node::Dock { side: found, columns } if *found == side => {
Node::Dock { side: found, columns, .. } if *found == side => {
columns.iter().flat_map(|column| &column.groups).find_map(|group| group.panels.first().copied())
}
_ => None,
@@ -264,47 +260,187 @@ fn dock_panel(node: &Node<Panel>, side: Side) -> Option<Panel> {
/// in their docks (joining the dock's first group when the dock is shown, else making the dock
/// again), the MIDI editor under the session view and the others floating.
fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result<(), String> {
if workspace.layout.contains(&panel) == visible {
if workspace.layout().contains(&panel) == visible {
return Ok(());
}
checked(workspace, |next| {
if !visible {
return next.apply(Action::Close { panel }, permissions).map(drop);
return next.apply(Action::close(panel), false, permissions).map(drop);
}
let dock = default_dock(panel);
if let Some((side, _)) = dock
&& let Some(anchor) = next.layout.root.as_ref().and_then(|root| dock_panel(root, side))
&& let Some(anchor) = next.layout().root.as_ref().and_then(|root| dock_panel(root, side))
{
return next.set_visible(panel, true, Some(anchor), permissions);
return next.set_visible(panel, true, Some(anchor), false, permissions);
}
// Without an anchor, craft-ui would open a panel it has no record of, or whose record no
// Without an anchor, craft-behavior would open a panel it has no record of, or whose record no
// longer restores, in some other panel's group, so the default place is applied here.
if next.hidden.iter().any(|(hidden, _)| *hidden == panel) && restores(next, panel) && next.set_visible(panel, true, None, permissions).is_ok()
if next.hidden().iter().any(|(hidden, _)| *hidden == panel)
&& restores(next, panel)
&& next.set_visible(panel, true, None, false, permissions).is_ok()
{
return Ok(());
}
let open = Action::Open { panel, anchor: None };
let open = Action::open(panel, None);
let actions = match (dock, default_float(panel)) {
(Some((side, width)), _) => vec![open, Action::MovePanel { panel, to: Target::NewDock { side } }, Action::ResizeColumn { panel, width }],
(None, Some(rect)) => vec![open, Action::Float { panel, rect }],
(None, None) => vec![Action::OpenAt { panel, anchor: Panel::Canvas, placement: Placement::Split(Zone::Bottom) }],
(Some((side, width)), _) => vec![open, Action::move_panel(panel, Target::new_dock(side)), Action::resize_column(panel, width)],
(None, Some(rect)) => vec![open, Action::float(panel, rect)],
(None, None) => vec![Action::open_at(panel, Panel::Canvas, DockPlacement::Split(DockSide::Bottom))],
};
next.apply_all(actions, permissions)?;
next.apply(Action::Activate { panel }, permissions).map(drop)
next.apply_all(actions, false, permissions)?;
next.apply(Action::activate(panel), false, permissions).map(drop)
})
}
/// Run a shared docking command. A hidden panel that is opened or activated comes back with
/// [`set_visible`], so it gets SoundCraft's default place when it has no recorded one.
fn run(workspace: &mut Workspace, command: &DockCommand<Panel>) -> Result<(), String> {
if let DockCommand::Activate { panel } | DockCommand::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) =
command
&& !workspace.layout.contains(panel)
{
return set_visible(workspace, *panel, true);
/// A drop zone by name, as `ui.dock` writes it. PascalCase names also parse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ZoneName {
Tab,
#[serde(alias = "Center")]
Center,
#[serde(alias = "Left")]
Left,
#[serde(alias = "Right")]
Right,
#[serde(alias = "Top")]
Top,
#[serde(alias = "Bottom")]
Bottom,
Above,
Below,
}
/// A present field, `null` included: `Some(None)` for `null`, `None` when absent.
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
/// A required field that may be `null`.
fn required<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> {
T::deserialize(deserializer)
}
/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone`
/// (default `center`) and `before`, which only applies to a center move. Rects are `[x, y, width, height]`.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "operation", rename_all = "camelCase")]
enum DockOperation {
/// Show a panel at its last location and select it.
Open {
panel: Panel,
},
Close {
panel: Panel,
},
Activate {
panel: Panel,
},
Float {
panel: Panel,
rect: [f32; 4],
},
MoveFloating {
panel: Panel,
rect: [f32; 4],
},
Move {
panel: Panel,
target: Panel,
#[serde(default)]
zone: Option<ZoneName>,
#[serde(default, deserialize_with = "present")]
before: Option<Option<Panel>>,
},
SetStackOpen {
panel: Panel,
open: bool,
},
/// `height` is required; `null` clears it.
ResizeStack {
panel: Panel,
#[serde(deserialize_with = "required")]
height: Option<f32>,
},
ResizeSplit {
path: Vec<bool>,
size: SplitSize,
},
}
/// What `ui.dock` and `ui.dock.reset` ask of the front window's workspace, and the changes the dock reports.
#[derive(Clone, Debug, PartialEq)]
enum DockCommand {
/// A raw layout action: `ui.dock` with `{action}`, or a change made in the dock.
Layout(Action<Panel>),
/// `ui.dock` with `{operation, …}`.
Operation(DockOperation),
/// `ui.dock.reset`: the built-in arrangement.
Reset,
}
/// `[x, y, width, height]` as a rect.
fn rect_of([x, y, width, height]: [f32; 4]) -> Rect {
Rect::from_min_size(pos2(x, y), vec2(width, height))
}
/// Where a `move` puts the panel relative to `anchor`: `zone` (default `center`) and `before`,
/// with side zones mapped onto the anchor's container by [`DockPlacement::for_zone`].
fn placement(
layout: &Layout<Panel>,
anchor: &Panel,
zone: Option<ZoneName>,
before: Option<Option<Panel>>,
) -> Result<DockPlacement<Panel>, DockError> {
let side = |side| DockPlacement::for_zone(layout, anchor, side);
Ok(match (zone.unwrap_or(ZoneName::Center), before) {
(ZoneName::Tab | ZoneName::Center, Some(before)) => DockPlacement::tab(before),
(ZoneName::Tab, None) => DockPlacement::tab(None),
(ZoneName::Center, None) => DockPlacement::Split(DockSide::Center),
(_, Some(_)) => return Err(DockError::InvalidPlacement),
(ZoneName::Left, None) => side(DockSide::Start)?,
(ZoneName::Right, None) => side(DockSide::End)?,
(ZoneName::Top, None) => side(DockSide::Top)?,
(ZoneName::Bottom, None) => side(DockSide::Bottom)?,
(ZoneName::Above, None) => DockPlacement::group(false, None),
(ZoneName::Below, None) => DockPlacement::group(true, None),
})
}
impl DockOperation {
/// The layout action this operation makes on `layout`. A panel that is not shown is
/// [`DockError::MissingPanel`] for Open and Activate, which show it first ([`run`]).
fn action(&self, layout: &Layout<Panel>) -> Result<Action<Panel>, DockError> {
Ok(match self {
Self::Open { panel } | Self::Activate { panel } => {
if !layout.contains(panel) {
return Err(DockError::MissingPanel);
}
Action::activate(*panel)
}
Self::Close { panel } => Action::close(*panel),
Self::Float { panel, rect } => Action::float(*panel, rect_of(*rect)),
Self::MoveFloating { panel, rect } => Action::move_floating(*panel, rect_of(*rect)),
Self::Move { panel, target, zone, before } => Action::move_beside(*panel, *target, placement(layout, target, *zone, *before)?),
Self::SetStackOpen { panel, open } => Action::set_stack_open(*panel, *open),
Self::ResizeStack { panel, height } => Action::resize_stack(*panel, *height),
Self::ResizeSplit { path, size } => Action::resize_split(path.clone(), *size),
})
}
// Only `window.panel.float` reads the float space, and SoundCraft does not register it.
checked(workspace, |next| command.apply(next, false, &FloatSpace::new(egui::Rect::NOTHING), permissions).map(drop))
}
/// Run a docking command. A hidden panel that is opened or activated comes back with
/// [`set_visible`], so it gets SoundCraft's default place when it has no recorded one.
fn run(workspace: &mut Workspace, command: &DockCommand) -> Result<(), String> {
let action = match command {
DockCommand::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel }) if !workspace.layout().contains(panel) => {
return set_visible(workspace, *panel, true);
}
DockCommand::Operation(operation) => operation.action(workspace.layout()).map_err(|error| error.to_string())?,
DockCommand::Layout(action) => action.clone(),
DockCommand::Reset => return Err("Reset is applied by the window, not the layout".into()),
};
apply(workspace, action)
}
fn sync(workspace: &mut Workspace, app: &crate::SoundApp, edit: bool) -> Result<(), String> {
@@ -319,12 +455,13 @@ fn sync(workspace: &mut Workspace, app: &crate::SoundApp, edit: bool) -> Result<
}
fn publish_visibility(app: &mut crate::SoundApp, workspace: &Workspace, edit: bool) {
app.ui.show_tracks_list = workspace.layout.contains(&Panel::Tracks);
app.ui.show_memory_locations = workspace.layout.contains(&Panel::Memory);
app.ui.show_undo_history = workspace.layout.contains(&Panel::History);
let layout = workspace.layout();
app.ui.show_tracks_list = layout.contains(&Panel::Tracks);
app.ui.show_memory_locations = layout.contains(&Panel::Memory);
app.ui.show_undo_history = layout.contains(&Panel::History);
if edit {
app.ui.show_clip_list = workspace.layout.contains(&Panel::Clips);
app.ui.show_midi_editor = workspace.layout.contains(&Panel::Midi);
app.ui.show_clip_list = layout.contains(&Panel::Clips);
app.ui.show_midi_editor = layout.contains(&Panel::Midi);
}
}
@@ -336,9 +473,8 @@ fn store(app: &mut crate::SoundApp, workspace: Workspace, edit: bool) {
}
}
/// A `ui.dock` operation. Panels and zones are checked first so an error names the field;
/// parsed through the untagged [`UiDock`], every mistake reads "did not match any variant".
fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation<Panel>, String> {
/// A `ui.dock` operation. Panels and zones are checked first so an error names the field.
fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation, String> {
let name = fields.get("operation").ok_or("operation is required")?.as_str().ok_or("operation must be a string")?;
if name != "resizeSplit" && !fields.contains_key("panel") {
return Err("panel is required".into());
@@ -357,52 +493,48 @@ fn operation(fields: &serde_json::Map<String, Value>) -> Result<DockOperation<Pa
serde_json::from_value(Value::Object(fields.clone())).map_err(|error| error.to_string())
}
/// `ui.dock` and `ui.dock.reset`: the shared [`DockCommand`] vocabulary, applied to the
/// front window's workspace.
/// `ui.dock` and `ui.dock.reset`, applied to the front window's workspace.
pub fn command(app: &mut crate::SoundApp, id: &str, params: &Value) -> Result<Value, String> {
let edit = app.ui.window == crate::MainWindow::Edit;
if !edit && ["panel", "target"].iter().any(|field| matches!(params.get(*field).and_then(Value::as_str), Some("clips" | "midi"))) {
return Err("Clips and MIDI panels belong to the Edit window".into());
}
let mut fields = match params {
let fields = match params {
Value::Object(fields) => fields.clone(),
Value::Null => serde_json::Map::new(),
_ => return Err("Docking params must be an object".into()),
};
let command = if id == "ui.dock" && !fields.contains_key("action") {
DockCommand::UiDock(UiDock::Operation(operation(&fields)?))
} else {
fields.insert("command".into(), json!(id));
serde_json::from_value(Value::Object(fields)).map_err(|error| error.to_string())?
let command = match (id, fields.get("action")) {
("ui.dock.reset", _) => DockCommand::Reset,
(_, Some(action)) => DockCommand::Layout(serde_json::from_value(action.clone()).map_err(|error| error.to_string())?),
(_, None) => DockCommand::Operation(operation(&fields)?),
};
let previous = if edit { app.ui.docking.clone() } else { app.ui.mix_docking.clone() };
let result = command_for(app, &command, edit)?;
let next = if edit { &app.ui.docking } else { &app.ui.mix_docking };
cancel_replaced_workspace(app, &previous, next, edit);
cancel_replaced_workspace(app, &previous, next);
Ok(result)
}
fn cancel_replaced_workspace(app: &crate::SoundApp, previous: &Workspace, next: &Workspace, edit: bool) {
/// Ends a running panel drag when the workspace it started on is replaced or changed by something else
/// than the dock.
fn cancel_replaced_workspace(app: &crate::SoundApp, previous: &Workspace, next: &Workspace) {
if previous != next
&& let Some(ctx) = &app.docking_context
{
craft_ui::docking::cancel_drag::<Panel>(ctx, area(edit));
craft_ui::runtime::drag::cancel(ctx, craft_behavior::CancelReason::HostChanged);
}
}
/// Restoring complete preferences/configurations uses the same ownership boundary as commands.
pub(crate) fn cancel_replaced_state(app: &crate::SoundApp, next: &crate::UiState) {
cancel_replaced_workspace(app, &app.ui.docking, &next.docking, true);
cancel_replaced_workspace(app, &app.ui.mix_docking, &next.mix_docking, false);
cancel_replaced_workspace(app, &app.ui.docking, &next.docking);
cancel_replaced_workspace(app, &app.ui.mix_docking, &next.mix_docking);
}
fn command_for(app: &mut crate::SoundApp, command: &DockCommand<Panel>, edit: bool) -> Result<Value, String> {
fn command_for(app: &mut crate::SoundApp, command: &DockCommand, edit: bool) -> Result<Value, String> {
let mut workspace = if edit { app.ui.docking.clone() } else { app.ui.mix_docking.clone() };
if command.is_app_owned() {
// Reset is the only application-owned command SoundCraft registers.
if !matches!(command, DockCommand::ResetWorkspace {}) {
return Err("Named panel workspaces are not supported".into());
}
if *command == DockCommand::Reset {
workspace = if edit { edit_default() } else { mix_default() };
sync(&mut workspace, app, edit)?;
} else {
@@ -431,22 +563,189 @@ pub(crate) fn arrange(app: &mut crate::SoundApp) -> Result<(), String> {
validate_mix(&workspace)?;
}
let previous = workspace.clone();
let floating: Vec<_> = workspace.layout.floating.iter().filter_map(|window| window.panels().next().map(|panel| (*panel, window.rect))).collect();
for (index, (panel, mut rect)) in floating.into_iter().enumerate() {
rect[0] = 32.0 + index as f32 * 28.0;
rect[1] = 80.0 + index as f32 * 28.0;
apply(&mut workspace, Action::MoveFloating { panel, rect })?;
let floating: Vec<_> =
workspace.layout().floating.iter().filter_map(|window| window.panels().next().map(|panel| (*panel, window.rect))).collect();
for (index, (panel, rect)) in floating.into_iter().enumerate() {
let at = pos2(32.0 + index as f32 * 28.0, 80.0 + index as f32 * 28.0);
apply(&mut workspace, Action::move_floating(panel, Rect::from_min_size(at, rect.size())))?;
}
cancel_replaced_workspace(app, &previous, &workspace, edit);
cancel_replaced_workspace(app, &previous, &workspace);
store(app, workspace, edit);
Ok(())
}
/// The workspaces the Edit and Mix docks show, the panels' specs and the session views' keyboard focus.
#[derive(Default)]
pub(crate) struct LiveDocks {
edit: Option<Arc<Workspace>>,
mix: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
edit_focus: ViewFocus,
mix_focus: ViewFocus,
}
impl LiveDocks {
/// The `Arc` the dock shows for `workspace`: the last one while its arrangement is the same, so an idle pass
/// keeps the workspace's revision and the dock reads no spec.
fn shown(&mut self, edit: bool, workspace: &Workspace) -> Arc<Workspace> {
let slot = if edit { &mut self.edit } else { &mut self.mix };
if let Some(shown) = slot.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
*slot = Some(Arc::clone(&shown));
shown
}
}
/// What the dock reads of the panels: their names in the interface language.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
struct DockSpecs {
/// The tab names, in [`Panel::ALL`] order.
labels: Vec<String>,
}
impl PanelSpecs<Panel> for DockSpecs {
fn spec(&self, panel: &Panel) -> PanelSpec {
let label = Panel::ALL.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
// Every panel is SoundCraft's own egui code: the dock runs it with the window's style.
let spec = PanelSpec::new(label).limits(panel_limits(panel)).host_body();
if *panel == Panel::Canvas { spec.canvas() } else { spec }
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// Reads the panel names in the interface language, moving the specs' revision only when one changed.
fn refresh_specs(app: &mut crate::SoundApp) {
let labels: Vec<String> = Panel::ALL.iter().map(|panel| crate::localization::text(panel.label()).to_owned()).collect();
if app.docks.specs.labels != labels {
app.docks.specs.labels = labels;
}
}
/// What a session view knows of its keyboard focus from the pass that drew it last.
#[derive(Default)]
struct ViewFocus {
/// That pass's number and the document the view showed (`SoundApp::doc_epoch`).
shown: Option<(u64, u64)>,
/// The view opened or was pressed and has yet to ask for the focus.
wanted: bool,
/// The view had the focus, and no other widget has taken it.
returns: bool,
/// An overlay ([`crate::framework::overlay_open`]) was up.
overlay: bool,
/// The view kept Tab.
kept_tab: bool,
}
impl LiveDocks {
fn view_focus(&mut self, edit: bool) -> &mut ViewFocus {
if edit { &mut self.edit_focus } else { &mut self.mix_focus }
}
}
/// Gives the session view, drawn in `rect`, the keyboard focus on a press in it, when it opens or shows another
/// document, and when its focus went nowhere (a dialog that closed). It waits for
/// a modal dialog, menu or popup to close. A press leaves the focus with the text field it landed on; a view that opens
/// leaves it with any text field and with a widget of another layer. Called after the view's widgets, so that the field
/// under a press has taken the focus already.
fn focus_session_view(app: &mut crate::SoundApp, ui: &egui::Ui, edit: bool, rect: Rect) {
let ctx = ui.ctx();
let id = crate::framework::session_view_id(edit);
let focused = ctx.memory(|memory| memory.focused());
let pressed = ui.rect_contains_pointer(rect) && ui.input(|input| input.pointer.any_pressed());
let overlay = crate::framework::overlay_open(app, ctx);
let (pass, document) = (ctx.cumulative_pass_nr(), app.doc_epoch);
let state = app.docks.view_focus(edit);
let stayed = state.shown.is_some_and(|(last, shown)| shown == document && (last == pass || last + 1 == pass));
state.shown = Some((pass, document));
state.wanted |= pressed || !stayed;
state.returns |= focused == Some(id);
// egui keeps the focus on a widget of a closed overlay for the pass after the last one that drew it.
if std::mem::replace(&mut state.overlay, overlay) || overlay {
if !overlay {
ctx.request_repaint();
}
return;
}
let wanted = std::mem::take(&mut state.wanted);
state.returns &= focused.is_none_or(|focused| focused == id);
let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id);
let field_pressed =
|| ctx.text_edit_focused() && focused.and_then(|field| ctx.read_response(field)).is_some_and(|field| field.is_pointer_button_down_on());
let takes = if pressed {
focused != Some(id) && !field_pressed()
} else if wanted {
focused != Some(id) && !ctx.text_edit_focused() && focused.is_none_or(|focused| layer(focused) == layer(id))
} else {
state.returns && focused.is_none()
};
if takes {
crate::framework::focus_session_view(ctx, id);
}
}
/// The dock's panels over the app in one pass.
struct Panels<'a> {
app: &'a mut crate::SoundApp,
edit: bool,
}
impl DockPanels<Panel> for Panels<'_> {
fn body(&mut self, panel: &Panel, ui: &mut egui::Ui, _: &mut BodyCx<'_>) {
let app = &mut *self.app;
match panel {
// The session view is its group's `group_view`.
Panel::Canvas => {}
Panel::Tracks => crate::panels::tracks_and_groups(app, ui),
Panel::Clips => crate::panels::clip_list(app, ui),
Panel::Midi => {
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("soundcraft-midi-body"), ui.max_rect()));
minimum_body(ui, vec2(420.0, 260.0), |ui| crate::midi_editor::show(app, ui));
}
Panel::Memory => crate::panels::memory_locations(app, ui),
Panel::History => crate::panels::undo_history(app, ui),
}
}
/// The session view: the Edit window's tracks and timeline, or the mixer.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Canvas) {
return None;
}
let id = crate::framework::session_view_id(self.edit);
let view = ui.interact(rect, id, egui::Sense::focusable_noninteractive());
view.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Canvas, true, crate::localization::text(Panel::Canvas.label())));
// The shortcuts read the root window's keys only, so a Mix window of its own leaves Tab to the focus. A press of
// Tab is the view's to its release: the repeats of the one that reached the last stop stay here.
let shortcuts_run = ui.ctx().viewport_id() == egui::ViewportId::ROOT;
let held = self.app.docks.view_focus(self.edit).kept_tab && ui.input(|input| input.key_down(egui::Key::Tab));
let keeps_tab = |app: &crate::SoundApp| shortcuts_run && (held || crate::shortcuts::tab_has_work(app));
// Declared before the widgets drawn over it, for its place in Tab order, and again after this pass's input has
// changed what Tab has to do.
crate::framework::host_canvas(ui.ctx(), id, keeps_tab(self.app));
ui.painter().rect_filled(rect, 0.0, crate::theme::Tokens::current().window_bg);
if self.edit {
crate::edit_window::main_area(self.app, ui);
} else {
crate::mix_window::content(self.app, ui);
}
focus_session_view(self.app, ui, self.edit, rect);
let kept_tab = keeps_tab(self.app);
self.app.docks.view_focus(self.edit).kept_tab = kept_tab;
crate::framework::host_canvas(ui.ctx(), id, kept_tab);
Some(rect.height())
}
}
/// Draw and edit the dock layout for the requested window, falling back to the default layout if validation or panel
/// sync fails, then publish panel visibility, store the workspace and apply the frame's layout actions.
/// sync fails, then publish panel visibility, store the workspace and apply the pass's layout actions.
pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWindow) {
app.docking_context = Some(ui.ctx().clone());
let t = crate::theme::Tokens::current();
let edit = window == crate::MainWindow::Edit;
let mut workspace =
if edit { std::mem::replace(&mut app.ui.docking, edit_default()) } else { std::mem::replace(&mut app.ui.mix_docking, mix_default()) };
@@ -456,58 +755,31 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
workspace = if edit { edit_default() } else { mix_default() };
let _ = sync(&mut workspace, app, edit);
}
cancel_replaced_workspace(app, &before_sync, &workspace, edit);
let mut style = DockStyle::from_ui(ui);
style.min_pane = 96.0;
style.tab_height = MIDI_TAB_HEIGHT;
style.background = t.panel_bg;
style.tab_background = t.panel_bg2;
style.active_background = t.row_selected;
style.text = t.text;
style.inactive_text = t.text_dim;
style.border = egui::Stroke::new(1.0, t.border);
style.accent = t.accent;
style.font = crate::theme::regular(11.5);
// Free docking: a panel dropped at an empty window edge makes a dock there, and the top
// and bottom edges take frames (`drop_edges` keeps its default).
style.new_dock_zones = true;
style.side_edge_zones = false;
cancel_replaced_workspace(app, &before_sync, &workspace);
// The MIDI body's rect stands for a piano roll on screen (the arrow keys go to it), so only a
// frame that draws the panel records one: open behind another tab, the old rect is gone.
if edit {
ui.ctx().data_mut(|data| data.remove::<egui::Rect>(egui::Id::unique("soundcraft-midi-body")));
}
let output = DockArea::new(area(edit)).show_with_limits(
ui,
&workspace.layout,
&style,
|panel| crate::localization::text(panel.label()).into(),
permissions,
panel_limits,
|ui, panel| match panel {
Panel::Canvas => {
ui.painter().rect_filled(ui.max_rect(), 0.0, t.window_bg);
if edit {
crate::edit_window::main_area(app, ui);
} else {
crate::mix_window::content(app, ui);
}
}
Panel::Tracks => crate::panels::tracks_and_groups(app, ui),
Panel::Clips => crate::panels::clip_list(app, ui),
Panel::Midi => {
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("soundcraft-midi-body"), ui.max_rect()));
minimum_body(ui, egui::vec2(420.0, 260.0), |ui| crate::midi_editor::show(app, ui));
}
Panel::Memory => crate::panels::memory_locations(app, ui),
Panel::History => crate::panels::undo_history(app, ui),
},
);
refresh_specs(app);
let shown = app.docks.shown(edit, &workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.docks.specs);
// Floating windows stay inside the app window; a drop at an empty window edge makes a dock there, and the top and
// bottom edges take frames (`DockConfig::default()`).
let config = DockConfig::default().native_windows(false);
let output = ui
.push_id(area_id(window), |ui| {
let mut panels = Panels { app: &mut *app, edit };
DockArea::new("Panels", Bind::given(shown), &specs, &mut panels, config).show(ui)
})
.inner;
app.docks.specs = specs;
let _ = sync(&mut workspace, app, edit);
publish_visibility(app, &workspace, edit);
store(app, workspace, edit);
for action in output.actions {
if let Err(error) = command_for(app, &DockCommand::Layout { action }, edit) {
for action in output.actions.into_iter().chain(output.requested) {
if let Err(error) = command_for(app, &DockCommand::Layout(action), edit) {
app.ui.status = crate::localized_format!("Panel move was not applied: {error}", error = error);
}
}
@@ -529,14 +801,15 @@ pub(crate) fn minimum_body(ui: &mut egui::Ui, minimum: egui::Vec2, body: impl Fn
});
}
fn panel_limits(panel: &Panel) -> PanelLimits {
/// The panels' body limits: a minimum size and, for side panels, a maximum width.
fn panel_limits(panel: &Panel) -> SizeLimits {
let (min, max_width) = match panel {
Panel::Canvas => (egui::vec2(300.0, 240.0), 1_000_000.0),
Panel::Tracks => (egui::vec2(140.0, 120.0), 520.0),
Panel::Clips => (egui::vec2(180.0, 120.0), 720.0),
Panel::Midi => (egui::vec2(420.0, 260.0), 1_000_000.0),
Panel::Memory => (egui::vec2(260.0, 160.0), 1_000_000.0),
Panel::History => (egui::vec2(200.0, 160.0), 720.0),
Panel::Canvas => (vec2(300.0, 240.0), SizeLimits::BOUND),
Panel::Tracks => (vec2(140.0, 120.0), 520.0),
Panel::Clips => (vec2(180.0, 120.0), 720.0),
Panel::Midi => (vec2(420.0, 260.0), SizeLimits::BOUND),
Panel::Memory => (vec2(260.0, 160.0), SizeLimits::BOUND),
Panel::History => (vec2(200.0, 160.0), 720.0),
};
PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) }
SizeLimits::new(min, vec2(max_width, SizeLimits::BOUND))
}
+1 -1
View File
@@ -283,7 +283,7 @@ fn harness(n: usize) -> Harness<'static, SoundApp> {
fn harness_with(engine: soundcraft_engine::Engine) -> Harness<'static, SoundApp> {
let app = SoundApp::new(engine, None, crate::Services::default());
let builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0);
let builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).with_context_setup(crate::framework::install_headless);
let builder = if std::env::var_os("SOUNDCRAFT_FADE_SHOTS").is_some() { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut SoundApp| {
+34 -1
View File
@@ -135,8 +135,18 @@ pub fn definitions(system_fonts: bool) -> FontDefinitions {
fonts
}
/// Gives the context [`definitions`] through the framework runtime, which keeps its font providers and layout memory in
/// step with them. The framework's chrome draws in three families besides the monospace one: the signature family
/// (follows the proportional one) and the semibold family, which titles and strong text use because the stack the
/// runtime started with has it; SoundCraft's own bold family serves as that one. A family left out draws missing-glyph
/// boxes.
pub fn install(ctx: &egui::Context, system_fonts: bool) {
ctx.set_fonts(definitions(system_fonts));
let mut fonts = definitions(system_fonts);
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
let bold = fonts.families.get(&FontFamily::Name("bold".into())).cloned().unwrap_or_else(|| proportional.clone());
fonts.families.entry(craft_ui::fonts::FontRef::signature().family()).or_insert(proportional);
fonts.families.entry(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into())).or_insert(bold);
craft_ui::fonts::load(ctx, fonts);
}
#[cfg(test)]
@@ -175,6 +185,29 @@ mod tests {
}
}
/// Every family the framework's chrome draws in has a face after `install`, with and without system fonts: the
/// dialog title once drew boxes because the semibold family was missing.
#[test]
fn install_gives_every_chrome_family_a_face() {
for system_fonts in [false, true] {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
install(&ctx, system_fonts);
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
output.textures_delta.clear();
let families = [
FontFamily::Proportional,
FontFamily::Monospace,
craft_ui::fonts::FontRef::signature().family(),
FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()),
];
for family in families {
let font = egui::FontId::new(14.0, family.clone());
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "Check for Updates")), "{family:?} has no Latin face (system fonts {system_fonts})");
}
}
}
/// Korean names draw in every family, not as boxes; skipped when the system has no Korean font.
#[test]
fn every_family_draws_hangul_with_a_system_korean_font() {
+182
View File
@@ -0,0 +1,182 @@
//! The craft-ui runtime, hosted from SoundCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`SoundApp::before_input`] in `raw_input_hook`, [`SoundApp::close_path`]
//! last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`].
//! [`SoundApp::run_framework_dialogs`] runs the framework dialogs after SoundCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of SoundCraft's own
//! egui widgets has the keyboard. The window's Escape is read with [`escape_pressed`]; the session view is declared
//! to the runtime with [`host_canvas`], which keeps the edit chords and the clipboard events in egui's input for
//! SoundCraft's shortcuts, and Tab while the focused view has work for it. A focused view leaves the keyboard to the
//! shortcuts ([`widget_has_keyboard`]).
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::{Chord, Key, Mods, Overrides};
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet, NavCommand, QuitCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, FocusTarget, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::runtime::overlay::{self, OpenFilter};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::system::WindowSystem;
use crate::SoundApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. SoundCraft's own definitions
/// ([`crate::fonts::install`]) replace it on the first frame, before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. `forced_x11` when the app
/// opens its window through XWayland. SoundCraft keeps the system's title bar on every platform.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, forced_x11: bool) -> Result<(), String> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
install_with(ctx, ShellInfo::default().backend(backend), Arc::new(craft_window::system::SystemWindows))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
log::warn!("{error}");
}
}
/// Who SoundCraft is to the framework's dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "soundcraft", name: "SoundCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.soundcraft.png"))
.build(),
)
}
/// The runtime's default keys SoundCraft's own shortcuts use: F6 and Shift+F6 move between panes by default, and F6
/// is the Trim tool in SoundCraft; Cmd+Q (Ctrl+Q) is the runtime's Quit, and SoundCraft quits through its own
/// `app.quit`, which keeps its recording and recovery rules. Overrides are keyed by command id, which the command set
/// gives.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
overrides.insert(NavCommand::NextPane.id(), Vec::new());
overrides.insert(NavCommand::PreviousPane.id(), Vec::new());
overrides.insert(QuitCommand::Quit.id(), Vec::new());
Arc::new(overrides)
})
.clone()
}
impl SoundApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(output));
}
/// The root values of this frame. SoundCraft registers no commands with the runtime and lets it toggle no
/// chrome, so the output carries nothing it acts on. The interface scale is the one SoundCraft applied last
/// (`extra_windows`), so the runtime's zoom and SoundCraft's agree.
fn frame_input(&mut self, _output: FrameOutput) -> FrameInput {
let mode = if crate::theme::is_light() { craft_theme::Mode::Light } else { craft_theme::Mode::Dark };
// SoundCraft zooms with Cmd/Ctrl+scroll itself, so a smooth Ctrl+wheel stays a wheel event.
let root = RootEnv::new().mode(mode).scale(Scale::new(self.extra.applied_scale())).ctrl_wheel_pinch(false);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host))
}
/// The framework's part of `App::logic`, after SoundCraft's own: the root window's close path. A close the app
/// asked for itself goes through; otherwise unsaved changes hold the window open while Save Changes asks, and
/// its answer quits the app.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || {
if self.quit_requested || !crate::dialogs::ask_to_save(self, "app.quit", &serde_json::json!({})) {
CloseDecision::Close
} else {
CloseDecision::Hold
}
});
}
/// The framework dialogs open on [`SoundApp::framework_dialogs`], once per pass after SoundCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
}
}
/// The edit-mode keys (Alt+1 to Alt+4, Pro Tools' Shuffle, Slip, Spot and Grid) the session view claims, so Alt-code
/// entry leaves them to SoundCraft's shortcuts.
const EDIT_MODE_KEYS: [Chord; 4] =
[Chord::new(Mods::ALT, Key::Num1), Chord::new(Mods::ALT, Key::Num2), Chord::new(Mods::ALT, Key::Num3), Chord::new(Mods::ALT, Key::Num4)];
/// The widget of the session view: the Edit window's tracks and timeline (`edit`) or the Mix window's strips.
pub fn session_view_id(edit: bool) -> egui::Id {
egui::Id::unique(("soundcraft-session-view", edit))
}
/// Declares the session view `id`, drawn in this pass, as the window's document canvas. With nothing focused it is
/// the window's key target: the edit chords, the clipboard events and the edit-mode keys stay in egui's input for
/// SoundCraft's shortcuts, as do the arrows, Enter and the page keys. Tab and Shift+Tab stop at the view; with
/// `keeps_tab` the focused view keeps them in egui's input, else they move on from it.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id, keeps_tab: bool) {
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL).with_claims(&EDIT_MODE_KEYS);
let keys = if keeps_tab { KEYS.with_keep(KeepKeys::Tab) } else { KEYS };
craft_ui::runtime::focus::host_canvas(ctx, id, keys);
}
/// Gives the session view `id`, declared in this pass, the keyboard focus.
pub(crate) fn focus_session_view(ctx: &egui::Context, id: egui::Id) {
craft_ui::runtime::focus::request(ctx, FocusTarget::Id(id));
}
/// Whether a widget other than the session view has the keyboard. A focused session view leaves it to SoundCraft's
/// shortcuts, as with nothing focused.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
ctx.memory(|memory| memory.focused()).is_some_and(|focused| ![true, false].map(session_view_id).contains(&focused))
}
/// Whether a modal dialog, SoundCraft's, egui's or the framework's, or an egui menu or popup is up. A framework menu
/// holds the focus in its own layer.
pub(crate) fn overlay_open(app: &SoundApp, ctx: &egui::Context) -> bool {
app.dialogs.open.is_some()
|| app.ui.show_preferences
|| app.ui.show_search
|| egui::Popup::is_any_open(ctx)
|| ctx.memory(|memory| memory.top_modal_layer()).is_some()
|| overlay::any_open(ctx, OpenFilter::Modal)
}
/// Whether Escape was pressed in this pass: from egui while one of SoundCraft's own widgets or popups has the
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel_pending(ctx)
}
/// Whether the window's cancel (an Escape while nothing has framework focus) is there and untaken.
fn window_cancel_pending(ctx: &egui::Context) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = intents.untaken(&Intent::Cancel);
false
});
pending
}
+10
View File
@@ -23,6 +23,7 @@ pub mod dialogs;
pub mod docking;
pub mod edit_window;
pub mod fonts;
pub mod framework;
pub mod icons;
pub mod import;
pub mod localization;
@@ -62,6 +63,7 @@ pub use panels::video_window;
pub use panels::windows;
mod app;
mod capture;
mod services;
mod state;
@@ -378,6 +380,8 @@ pub struct SoundApp {
synthetic_pointer_active: bool,
/// Cancel that press before the next egui input pass, without a release click/drop.
cancel_synthetic_pointer: bool,
/// `ui.key` requests waiting for the framework's injected input to run.
injected_acks: VecDeque<control::InjectedAck>,
/// A key/text batch crossed its deadline after [`Self::raw_input_hook`] had already appended it
/// to the pass. Do not dispatch that stale copy through shortcuts or widgets.
cancel_synthetic_keys: bool,
@@ -447,6 +451,12 @@ pub struct SoundApp {
theme_applied: Option<bool>,
/// Last panel host context, used to cancel renderer-owned gestures on explicit replacement.
pub(crate) docking_context: Option<egui::Context>,
/// The workspaces and panel specs the Edit and Mix docks show.
pub(crate) docks: docking::LiveDocks,
/// The framework dialogs (update check and prompt); they run once per pass after the app's own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who SoundCraft is to the framework's components.
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
/// Transport simulation when there is no player (tests, offscreen renders).
sim: Option<(Samples, Option<Samples>, Option<Range>)>,
/// When Record last found nothing to record on, and why: the Record buttons show it for a moment.
+2 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn output_window(app: &mut SoundApp, ctx: &egui::Context) {
// last frame, because egui closes them before this runs.
let busy_id = egui::Id::unique("output_window_escape");
let busy = ctx.data(|d| d.get_temp(busy_id)).unwrap_or(false) || app.dialogs.open.is_some() || app.ui.show_search;
if !busy && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if !busy && crate::framework::escape_pressed(ctx) {
app.ui.output_window = None;
}
output_window_contents(app, ctx);
@@ -147,7 +147,7 @@ mod tests {
app.run("view.edit_io", json!({})).unwrap();
app.run("track.height", json!({"tracks": ["Kick"], "height": "medium"})).unwrap();
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
app.ui(ui);
+63 -3
View File
@@ -5,7 +5,6 @@ use super::{
Align2, Rect, Route, Sense, SoundApp, Stroke, StrokeKind, Tokens, Track, TrackId, TrackKind, Ui, db_text, fader, json, pan_knob, pan_text, pos2,
regular, text_toggle, vec2,
};
use craft_ui::combo::Menu;
/// Draw one send slot: the route area picks a destination, while the level area opens or edits the send level.
pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: usize, r: Rect) {
@@ -78,7 +77,7 @@ pub(crate) fn send_window(app: &mut SoundApp, ctx: &egui::Context) {
// was theirs comes from the last frame. A dialog or the search on top takes it too.
let busy_id = egui::Id::unique("send_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)) {
if !busy && crate::framework::escape_pressed(ctx) {
app.ui.send_window = None;
}
send_window_contents(app, ctx);
@@ -334,6 +333,65 @@ fn send_level_scale(ui: &mut Ui, db: f32) {
ui.painter().line_segment([pos2(x, r.min.y), pos2(x, line_y + 3.0)], Stroke::new(2.0, t.counter_text));
}
/// The most height of the send menu's contents.
const SEND_MENU_HEIGHT: f32 = 260.0;
/// A menu under `field` that opens and closes on its clicks and closes on a click outside it: `header` stays at the
/// top, `total_rows` rows of `row_height` scroll under it (only the rows in view are laid out) and `footer` stays under
/// the list. The menu is up to [`SEND_MENU_HEIGHT`] tall and the room on its side of the field, at least as wide as
/// the field, and opens below the field or above it, never beside it. Returns what `rows` and `footer` returned, or
/// `None` while the menu is closed.
fn header_footer_menu<H, R, F>(
ui: &Ui,
field: &egui::Response,
header: impl FnOnce(&mut Ui) -> H,
row_height: f32,
total_rows: impl FnOnce(&H) -> usize,
rows: impl FnOnce(&mut Ui, std::ops::Range<usize>, H) -> R,
footer: impl FnOnce(&mut Ui) -> F,
) -> Option<(R, F)> {
let screen = ui.ctx().content_rect();
let room = (screen.bottom() - field.rect.bottom()).max(field.rect.top() - screen.top());
let frame = egui::Frame::popup(ui.style()).total_margin().sum().y;
let height = SEND_MENU_HEIGHT.min(room - frame).max(0.0);
let flipped: &'static [egui::RectAlign] =
if ui.ctx().global_style().right_to_left { &[egui::RectAlign::TOP_END] } else { &[egui::RectAlign::TOP_START] };
let popup = egui::Popup::menu(field);
let id = popup.get_id();
let footer_id = id.with("footer-height");
let shown = popup
.align_alternatives(flipped)
.max_height_from_constrain(true)
.width(field.rect.width())
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show(|ui| {
ui.set_min_width(ui.available_width());
// egui offers the popup last pass's height; offer the full height so a list that shrank (a search with
// no matches) grows back.
ui.set_max_height(height.min(ui.available_height()));
let header = header(ui);
// The footer comes after the list; keep the room it took last pass.
let footer_room = ui.data(|d| d.get_temp::<f32>(footer_id)).unwrap_or(0.0) + ui.spacing().item_spacing.y;
// Labels widen a narrow menu rather than wrap early, as in egui's combo box.
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
let total = total_rows(&header);
let list = egui::ScrollArea::vertical()
.max_height((ui.available_height() - footer_room).max(0.0))
.show_rows(ui, row_height, total, |ui, range| rows(ui, range, header))
.inner;
let top = ui.cursor().top();
let footer = footer(ui);
let footer_height = ui.min_rect().bottom() - top;
ui.data_mut(|d| d.insert_temp(footer_id, footer_height));
(list, footer)
})
.map(|shown| shown.inner);
if shown.is_some() {
ui.ctx().accesskit_node_builder(id, |node| node.set_role(egui::accesskit::Role::ListBox));
}
shown
}
/// What the send menu's footer was used for.
enum SendFooter {
NewBus,
@@ -369,7 +427,9 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
};
let target = current.as_ref().map(|(route, _)| route);
let row_h = ui.spacing().interact_size.y;
let shown = Menu::new(ui, field).height(260.0).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show_rows_with_header_footer(
let shown = header_footer_menu(
ui,
field,
header,
row_h,
|(_, visible)| visible.len(),
+1 -1
View File
@@ -64,7 +64,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
let t = Tokens::current();
let mut run: Option<String> = None;
let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
let mut close = crate::framework::escape_pressed(ctx);
egui::Window::new(crate::localization::text("Search"))
.id(egui::Id::unique("Search"))
.collapsible(false)
+14 -6
View File
@@ -35,6 +35,13 @@ impl Default for ExtraState {
}
}
impl ExtraState {
/// The interface scale applied to the context last; 1 until one is applied.
pub(crate) fn applied_scale(&self) -> f32 {
self.applied.map_or(1.0, |(scale, _)| scale)
}
}
/// UI commands handled here (`window.renderer`, `window.ui_customization`, `window.config_auto_update`).
pub fn run(app: &mut SoundApp, id: &str, p: &Value) -> Option<Value> {
let flag = |v: &mut bool| {
@@ -175,7 +182,7 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
.text(crate::localization::text("Interface scale")),
);
let mut chosen_effects = None;
craft_ui::ComboBox::from_label(crate::localization::text("Reduce visual effects"))
egui::ComboBox::from_label(crate::localization::text("Reduce visual effects"))
.selected_text(crate::localization::text(app.ui.reduce_visual_effects.label()))
.show_ui(ui, |ui| {
for mode in crate::preferences::ReduceVisualEffects::ALL {
@@ -188,7 +195,7 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
let _ = app.run("ui.reduce_visual_effects", json!({"mode": mode.id()}));
}
let mut selected_language = None;
craft_ui::ComboBox::from_label(crate::localization::text("Language"))
egui::ComboBox::from_label(crate::localization::text("Language"))
.selected_text(crate::localization::text(language.native_name()))
.show_ui(ui, |ui| {
for choice in crate::localization::Language::ALL {
@@ -201,15 +208,16 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
let _ = app.run("ui.language", json!({"language": choice.id()}));
}
let mut chosen = None;
craft_ui::ComboBox::from_label(crate::localization::text("Theme"))
.selected_text(crate::localization::text(app.ui.theme.label()))
.show_ui(ui, |ui| {
egui::ComboBox::from_label(crate::localization::text("Theme")).selected_text(crate::localization::text(app.ui.theme.label())).show_ui(
ui,
|ui| {
for mode in crate::theme::ThemeMode::ALL {
if ui.selectable_label(app.ui.theme == mode, crate::localization::text(mode.label())).clicked() {
chosen = Some(mode);
}
}
});
},
);
if let Some(mode) = chosen {
let _ = app.run("ui.theme", json!({"mode": mode.id()}));
}
+2 -2
View File
@@ -432,7 +432,7 @@ fn note_pointer(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId, penc
fn note_keys(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId) {
let Roll { sequence, roll, grid_ticks, .. } = *g;
// Keyboard: Cmd+A select all; arrows transpose (Shift = octave) and move by the grid.
if ui.rect_contains_pointer(roll) && !ui.ctx().egui_wants_keyboard_input() {
if ui.rect_contains_pointer(roll) && !crate::framework::widget_has_keyboard(ui.ctx()) {
let (all, up, down, left, right, shift) = ui.input(|i| {
let arrows = !i.modifiers.alt && !i.modifiers.command && !i.modifiers.ctrl;
(
@@ -469,7 +469,7 @@ fn note_keys(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId) {
}
}
if !app.midi.selected.is_empty()
&& !ui.ctx().egui_wants_keyboard_input()
&& !crate::framework::widget_has_keyboard(ui.ctx())
&& ui.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))
{
let _ = app.run("midi.note_delete", json!({"clip": cid.0, "indices": app.midi.selected}));
+1 -1
View File
@@ -82,7 +82,7 @@ pub(super) fn plugin_windows(app: &mut SoundApp, ctx: &egui::Context) {
let mut idx = x.round().max(0.0) as usize;
let selected = p.choices.get(idx).copied().unwrap_or("?");
let selected_text = if localize_params { crate::localization::text(selected) } else { selected };
let r = craft_ui::ComboBox::from_id_salt(("pc", tid.0, slot, p.id)).selected_text(selected_text).show_ui(ui, |ui| {
let r = egui::ComboBox::from_id_salt(("pc", tid.0, slot, p.id)).selected_text(selected_text).show_ui(ui, |ui| {
for (i, c) in p.choices.iter().enumerate() {
let choice_text = if localize_params { crate::localization::text(c) } else { c };
ui.selectable_value(&mut idx, i, choice_text);
+4 -4
View File
@@ -484,7 +484,7 @@ fn chosen_device<'a>(devices: &'a [DeviceInfo], name: Option<&str>) -> Option<&'
fn device_combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut Option<String>, devices: &[DeviceInfo]) {
let default = devices.iter().find(|d| d.is_default).map_or_else(|| crate::localization::text("none").to_string(), |d| d.name.clone());
let shown = value.clone().unwrap_or_else(|| crate::localized_format!("Default ({default})", default = default));
let combo = craft_ui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| {
let combo = egui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| {
ui.selectable_value(value, None, crate::localized_format!("Default ({default})", default = default));
for d in devices {
ui.selectable_value(value, Some(d.name.clone()), format!("{} ({} ch)", d.name, d.max_channels));
@@ -499,7 +499,7 @@ fn number_combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut Option<u32>
|| crate::localization::text("Device default").to_string(),
|v| crate::localized_format!("{v} {unit}", v = v, unit = crate::localization::text(unit)),
);
let combo = craft_ui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| {
let combo = egui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| {
ui.selectable_value(value, None, crate::localization::text("Device default"));
for v in options {
ui.selectable_value(value, Some(*v), crate::localized_format!("{v} {unit}", v = v, unit = crate::localization::text(unit)));
@@ -609,7 +609,7 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
let system_label = ui.label(crate::localization::text("Audio system"));
let def = systems.iter().find(|s| s.is_default).map_or("none".to_string(), |s| s.name.clone());
let shown = draft.system.clone().unwrap_or_else(|| crate::localized_format!("Default ({default})", default = def));
let system = craft_ui::ComboBox::from_id_salt("pe-system").width(300.0).selected_text(shown).show_ui(ui, |ui| {
let system = egui::ComboBox::from_id_salt("pe-system").width(300.0).selected_text(shown).show_ui(ui, |ui| {
let before = draft.system.clone();
ui.selectable_value(&mut draft.system, None, crate::localized_format!("Default ({default})", default = def));
for s in systems.iter() {
@@ -836,7 +836,7 @@ pub fn io_setup(app: &mut SoundApp, ctx: &egui::Context) {
ui.horizontal(|ui| {
let main_label = ui.label(crate::localization::text("Main output"));
let format =
craft_ui::ComboBox::from_id_salt("main_output_format").selected_text(crate::localization::text(main.label())).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("main_output_format").selected_text(crate::localization::text(main.label())).show_ui(ui, |ui| {
for f in soundcraft_model::ChannelFormat::ALL.into_iter().filter(|f| (2..=16).contains(&f.channels())) {
if ui.selectable_label(f == main, crate::localization::text(f.label())).clicked() && f != main {
let _ = app.run("setup.main_format", json!({"format": f.label()}));
+22 -20
View File
@@ -720,7 +720,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
select_page_from_keyboard(ctx, &mut page);
// A single-line text edit releases focus on Enter in the frame that receives the key. Capture
// ownership before drawing so Enter in Search cannot also apply and close the window.
let typing = ctx.egui_wants_keyboard_input();
let typing = crate::framework::widget_has_keyboard(ctx);
// egui closes a ComboBox before this window observes Escape, so preserve the previous frame's
// popup state to keep the same key from also canceling the complete Preferences window.
let popup_was_open = app.preferences.popup_open;
@@ -800,7 +800,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
draft.remember_user_edits(draft_before_ui);
app.preferences.popup_open = ctx.any_popup_open();
if ctx.input(|i| i.key_pressed(Key::Escape)) && !popup_was_open {
if crate::framework::escape_pressed(ctx) && !popup_was_open {
action = Some(Action::Cancel);
} else if action.is_none() && ctx.input(|i| i.key_pressed(Key::Enter)) && !typing {
action = Some(Action::Apply);
@@ -941,14 +941,14 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
let id = ("preference", page, section, index);
match control {
Control::Theme => {
craft_ui::ComboBox::new(id, label("UI Theme")).selected_text(crate::localization::text(draft.theme.label())).show_ui(ui, |ui| {
egui::ComboBox::new(id, label("UI Theme")).selected_text(crate::localization::text(draft.theme.label())).show_ui(ui, |ui| {
for mode in ThemeMode::ALL {
ui.selectable_value(&mut draft.theme, mode, crate::localization::text(mode.label()));
}
});
}
Control::ReduceVisualEffects => {
craft_ui::ComboBox::new(id, label("Reduce Visual Effects"))
egui::ComboBox::new(id, label("Reduce Visual Effects"))
.selected_text(crate::localization::text(draft.reduce_visual_effects.label()))
.show_ui(ui, |ui| {
for mode in ReduceVisualEffects::ALL {
@@ -969,7 +969,7 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
}
Control::Choice(text, value) | Control::ChoiceOptions(text, value, _) => {
ui.add_enabled_ui(false, |ui| {
craft_ui::ComboBox::new(id, label(text)).selected_text(crate::localization::text(value)).show_ui(ui, |_| {});
egui::ComboBox::new(id, label(text)).selected_text(crate::localization::text(value)).show_ui(ui, |_| {});
})
.response
.on_disabled_hover_text(crate::localization::text("This preference is not available yet."));
@@ -1107,7 +1107,7 @@ mod tests {
fn preferences_harness(size: egui::Vec2) -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(Engine::default(), None, crate::Services::default());
app.ui.show_preferences = true;
Harness::builder().with_size(size).build_ui_state(
Harness::builder().with_context_setup(crate::framework::install_headless).with_size(size).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
@@ -1395,13 +1395,14 @@ mod tests {
#[test]
fn soundcraft_menu_opens_preferences_through_the_same_command() {
let app = SoundApp::new(Engine::default(), None, crate::Services::default());
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut harness =
Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
harness.run_steps(4);
harness.get_by_label("SoundCraft").click();
harness.run_steps(2);
@@ -1415,13 +1416,14 @@ mod tests {
fn soundcraft_menu_disables_preferences_during_playback() {
let mut app = SoundApp::new(Engine::default(), None, crate::Services::default());
app.engine.transport.playing = true;
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut harness =
Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
harness.run_steps(4);
harness.get_by_label("SoundCraft").click();
harness.run_steps(2);
+11 -3
View File
@@ -59,12 +59,22 @@ fn search_chord(m: Modifiers, mac: bool) -> bool {
/// resolves to, not by its keys.
const REPEATING: [&str; 3] = ["view.zoom_in", "view.zoom_out", "view.waveform_zoom"];
/// Whether a dialog that holds back the shortcuts is open.
fn dialog_open(app: &SoundApp) -> bool {
app.dialogs.open.is_some() || app.ui.show_preferences
}
/// Whether Tab has something to do in the focused session view: the shortcuts run and `edit.tab` has a stop ahead.
pub(crate) fn tab_has_work(app: &SoundApp) -> bool {
!dialog_open(app) && soundcraft_engine::cmd::tab_stop_ahead(app.engine.session())
}
/// Dispatch global keyboard shortcuts once no text field or dialog wants input, ignoring non-scripted auto-repeats
/// (except the [`REPEATING`] zoom commands) while still running a host press alongside a scripted one.
pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
// Cmd+= and Cmd+0 are Mix/Edit and Quantize to Grid, not egui's built-in interface zoom.
ctx.options_mut(|o| o.zoom_with_keyboard = false);
if ctx.egui_wants_keyboard_input() || app.dialogs.open.is_some() || app.ui.show_preferences {
if crate::framework::widget_has_keyboard(ctx) || dialog_open(app) {
return;
}
// A scripted press is identified by its exact position in this pass's events, not by matching
@@ -106,8 +116,6 @@ pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
let _ = app.run(c.0, json!({}));
}
}
// Tab moves the insertion point here, so egui must not also hand focus to the first widget: that would block every shortcut.
ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
}
/// The command a host auto-repeat of this chord runs, if it is one of [`REPEATING`]. A repeat
+21 -1
View File
@@ -527,6 +527,7 @@ fn ordinary_play_after_stop_is_full_speed() {
#[test]
fn one_synthetic_batch_survives_hidden_ticks_and_applies_once() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let raw = |w: f32| {
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, 900.0));
@@ -588,6 +589,7 @@ impl egui::DroppedFile for TestDrop {
#[test]
fn a_drop_before_fonts_are_ready_is_imported_once_after_layout() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::Engine::default(), None, super::Services::default());
let mut first =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };
@@ -617,6 +619,7 @@ fn a_drop_before_fonts_are_ready_is_imported_once_after_layout() {
#[test]
fn a_retained_host_input_holds_one_copy_of_a_pending_batch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let hidden = egui::ViewportInfo { minimized: Some(true), ..Default::default() };
@@ -697,6 +700,7 @@ fn a_pending_synthetic_batch_asks_a_hidden_window_for_a_paint() {
#[test]
fn frame_time_counts_a_multi_pass_frame_once() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -731,6 +735,7 @@ fn frame_time_counts_a_multi_pass_frame_once() {
#[test]
fn a_synthetic_pass_does_not_publish_os_clipboard_commands() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -782,6 +787,7 @@ fn a_synthetic_pass_does_not_publish_os_clipboard_commands() {
#[test]
fn a_held_key_does_not_turn_a_scripted_press_into_a_repeat() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -855,6 +861,7 @@ fn key_pass(ctx: &egui::Context, app: &mut SoundApp, events: Vec<egui::Event>) {
/// The demo app after a few idle passes, ready for keyboard input.
fn app_for_keys() -> (egui::Context, SoundApp) {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
for _ in 0..4 {
key_pass(&ctx, &mut app, Vec::new());
@@ -917,6 +924,7 @@ fn holding_cmd_z_or_enter_still_runs_once() {
#[test]
fn a_fresh_host_press_and_a_scripted_press_both_run() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -955,6 +963,7 @@ fn a_fresh_host_press_and_a_scripted_press_both_run() {
#[test]
fn a_hidden_logic_tick_after_the_hook_keeps_the_held_key_and_pending_batch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let visible = egui::ViewportInfo { inner_rect: Some(rect), ..Default::default() };
@@ -1023,6 +1032,7 @@ fn a_hidden_logic_tick_after_the_hook_keeps_the_held_key_and_pending_batch() {
#[test]
fn a_multi_pass_frame_keeps_the_held_key_and_applies_the_scripted_press_once() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -1080,6 +1090,7 @@ fn a_multi_pass_frame_keeps_the_held_key_and_applies_the_scripted_press_once() {
#[test]
fn a_focus_loss_clears_a_held_key_with_a_pending_scripted_press() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -1138,6 +1149,7 @@ fn a_focus_loss_clears_a_held_key_with_a_pending_scripted_press() {
#[test]
fn a_host_key_with_the_same_signature_does_not_acknowledge_the_batch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -1223,6 +1235,7 @@ fn synthetic_key_acknowledgement_ignores_only_the_rewritten_repeat_flag() {
#[test]
fn a_discarded_pass_acknowledges_the_synthetic_batch_it_received() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -1287,6 +1300,7 @@ fn real_widgets_apply_a_scripted_edit_navigation_and_cut_once_despite_consuming_
let mut engine = soundcraft_engine::Engine::default();
engine.execute("track.new", &json!({})).unwrap();
let mut rig = Self { ctx: egui::Context::default(), app: SoundApp::new(engine, None, Services::default()), shapes: Vec::new() };
crate::framework::install_headless(&rig.ctx);
rig.frames(4);
rig
}
@@ -1417,6 +1431,7 @@ fn real_widgets_apply_a_scripted_edit_navigation_and_cut_once_despite_consuming_
#[test]
fn a_hidden_tick_does_not_write_automation_from_the_last_pass_pointer() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
app.run("mix.automation_mode", json!({"tracks": ["Kick"], "mode": "touch"})).unwrap();
@@ -1459,6 +1474,7 @@ fn a_hidden_tick_does_not_write_automation_from_the_last_pass_pointer() {
#[test]
fn a_font_gated_pass_does_not_ack_the_pending_synthetic_batch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -1470,7 +1486,9 @@ fn a_font_gated_pass_does_not_ack_the_pending_synthetic_batch() {
app.ui(ui);
});
out.textures_delta.clear();
assert!(!app.fonts_ready, "the first pass installs fonts but does not lay out");
// The fonts load in the gated first pass, which asks for a discard pass (`craft_ui::fonts::load`); that pass
// lays out with them but gets no input events, so neither pass acknowledges the batch.
assert!(app.fonts_installed, "the first pass installs fonts");
assert!(app.synthetic_batch.is_some(), "the font gate returns before the acknowledgement");
assert_eq!(app.synthetic_applied_batches, 0);
// The next hook offers the same batch to the first laid-out pass, which applies it once.
@@ -1500,6 +1518,7 @@ fn a_font_gated_pass_does_not_ack_the_pending_synthetic_batch() {
#[test]
fn a_settled_pass_that_did_not_receive_the_batch_does_not_ack_it() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = super::SoundApp::new(soundcraft_engine::demo::demo_engine(), None, super::Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
@@ -1611,6 +1630,7 @@ fn editor_gesture_polling_survives_discarded_and_hidden_host_iterations() {
use std::rc::Rc;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));
let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() };
+2
View File
@@ -656,12 +656,14 @@ mod tests {
let appearances = [Some(egui::Theme::Light), Some(egui::Theme::Dark), Some(egui::Theme::Light), None];
for initial in [Some(egui::Theme::Light), Some(egui::Theme::Dark), None] {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.ui = serde_json::from_value(json!({"theme": "system"})).unwrap();
frame(&mut app, &ctx, initial, initial == Some(egui::Theme::Light));
}
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut engine = soundcraft_engine::demo::demo_engine();
let track = engine.session_mut().tracks.first_mut().unwrap();
track.color = [19, 83, 147];
+44 -20
View File
@@ -1,9 +1,12 @@
//! Software updates, background check at startup, and startup prompt modal.
//! Software updates: the background check at startup, the startup prompt, and the outcome of Help ▸ Check for
//! Updates, as craft-update's dialogs on the app's [`DialogHost`](craft_ui::dialog::DialogHost).
use crate::SoundApp;
#[cfg(not(target_arch = "wasm32"))]
use craft_update::dialog::{CheckResultDialog, CheckResultResponse};
use craft_ui::dialog::DialogResult;
#[cfg(not(target_arch = "wasm32"))]
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
#[cfg(not(target_arch = "wasm32"))]
use craft_update::updater::{Action, Status, Updater};
@@ -21,8 +24,6 @@ pub(crate) struct Runtime {
check_requested: bool,
/// The check-result dialog (native) or the web build's notice is showing.
manual_window_open: bool,
#[cfg(not(target_arch = "wasm32"))]
result_dialog: CheckResultDialog,
}
impl Runtime {
@@ -44,8 +45,6 @@ impl Default for Runtime {
#[cfg(not(target_arch = "wasm32"))]
check_requested: false,
manual_window_open: false,
#[cfg(not(target_arch = "wasm32"))]
result_dialog: CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")),
}
}
}
@@ -109,9 +108,9 @@ pub(crate) fn tick(app: &mut SoundApp, ctx: &egui::Context) {
{
let rt = &mut app.updates_rt;
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
rt.updater.check_now();
} else if rt.startup_check {
rt.updater.check_at_start(ctx);
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
}
@@ -119,6 +118,9 @@ pub(crate) fn tick(app: &mut SoundApp, ctx: &egui::Context) {
let _ = (app, ctx);
}
/// One pass of the update flow, before the dialog host runs ([`SoundApp::run_framework_dialogs`]): answers the check
/// result dialog closed in the last pass, drives the startup prompt, and keeps the result dialog open and current
/// while the updater has something to report.
pub(crate) fn show(app: &mut SoundApp, ctx: &egui::Context) {
if !app.update_services_allowed() {
return;
@@ -127,26 +129,44 @@ pub(crate) fn show(app: &mut SoundApp, ctx: &egui::Context) {
{
// The restart helper is scheduled before the app closes, so no update starts over unsaved work or a take being recorded.
let clean = !app.has_unsaved_changes() && !app.engine.transport.recording;
match app.updates_rt.updater.show_if(ctx, clean) {
// Answered before the dialog is kept open below, so a dismissed result does not open again at once.
match app.framework_dialogs.take::<UpdateCheckDialog>() {
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.check_requested = true,
// The next `run` asks the window to close once nothing is unsaved.
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
Some(DialogResult::Ok(CheckChoice::Update)) => {
app.updates_rt.updater.request_install(clean);
}
Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
// OK, Esc and the close box dismiss the outcome it showed.
Some(_) => app.updates_rt.updater.dismiss_status(),
None => {}
}
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Action::None => {}
_ => {}
}
// Help ▸ Check for Updates, and the first start after an update, show their outcome in the shared result dialog
// until the user closes it. A found update goes to the startup prompt, which takes over from the dialog.
let rt = &mut app.updates_rt;
rt.manual_window_open = shows_result(rt.updater.status(), rt.updater.prompt_open());
if rt.manual_window_open {
match rt.result_dialog.show(ctx, rt.updater.status()) {
CheckResultResponse::Close => rt.manual_window_open = false,
CheckResultResponse::CheckAgain => rt.updater.check_now(ctx),
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
CheckResultResponse::None => {}
}
if rt.manual_window_open && !app.framework_dialogs.is_open::<UpdateCheckDialog>() {
app.framework_dialogs.open(UpdateCheckDialog::new(env!("CARGO_PKG_VERSION")));
}
// Closing the dialog, or the prompt taking over, dismisses the outcome it showed.
if !rt.manual_window_open {
rt.updater.dismiss_status();
let updater = &app.updates_rt.updater;
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
if let Some(dialog) = app.framework_dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
// The prompt taking over dismisses the outcome the dialog showed.
if !app.updates_rt.manual_window_open {
if app.framework_dialogs.is_open::<UpdateCheckDialog>() {
app.framework_dialogs.cancel::<UpdateCheckDialog>(ctx);
}
app.updates_rt.updater.dismiss_status();
}
}
@@ -180,6 +200,7 @@ mod tests {
let mut out = ctx.run_ui(raw, |ui| {
tick(app, ui.ctx());
show(app, ui.ctx());
app.run_framework_dialogs(ui);
});
out.textures_delta.clear();
}
@@ -271,6 +292,7 @@ mod tests {
Updater::new(&crate::UPDATE_APP, "0.2.0").with_source(Arc::new(|| Ok(None))).with_pins_path(dir.join("pins.json")).with_paths(paths);
app.set_startup_update_check(true);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
for _ in 0..3 {
frame(&mut app, &ctx, Vec::new());
}
@@ -278,6 +300,8 @@ mod tests {
assert!(app.updates_rt.manual_window_open);
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
frame(&mut app, &ctx, vec![escape]);
// The dialog closes on the Escape; the next pass reads its answer.
frame(&mut app, &ctx, Vec::new());
assert_eq!(app.updates_rt.updater.status(), &Status::Idle);
assert!(!app.updates_rt.manual_window_open);
let _ = std::fs::remove_dir_all(dir);
+104 -2
View File
@@ -1,7 +1,5 @@
//! Small custom widgets in the studio style.
use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle};
use crate::icons;
use crate::theme::{Tokens, bold, regular};
use egui::{Align2, Color32, CornerRadius, Mesh, Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
@@ -91,6 +89,110 @@ fn key_light(p: &Painter, face: Rect) {
p.hline(face.min.x + 1.0..=face.max.x - 1.0, face.min.y + 0.5, Stroke::new(1.0, Color32::from_white_alpha(30)));
}
/// The background, border and icon colour of an icon button in one interaction state.
#[derive(Clone, Copy, Debug, PartialEq)]
struct ButtonVisuals {
fill: Color32,
stroke: Stroke,
icon: Color32,
}
/// The look of an icon button in each state. Selection takes precedence over press and hover.
#[derive(Clone, Copy, Debug)]
struct IconButtonStyle {
normal: ButtonVisuals,
hovered: ButtonVisuals,
/// `None` keeps the hover or normal look while pressed.
pressed: Option<ButtonVisuals>,
selected: ButtonVisuals,
corner_radius: CornerRadius,
/// An inset outline while the button has keyboard focus.
focus_stroke: Stroke,
}
impl IconButtonStyle {
fn visuals(&self, selected: bool, hovered: bool, pressed: bool) -> ButtonVisuals {
if selected {
self.selected
} else if let Some(visuals) = self.pressed.filter(|_| pressed) {
visuals
} else if hovered {
self.hovered
} else {
self.normal
}
}
}
/// An icon-only button painted in SoundCraft's own colours. The label is its accessible name; the caller paints the
/// icon, attaches a tooltip and dispatches from the response. Selection is the caller's.
struct IconButton<'a> {
label: &'a str,
size: Vec2,
selected: bool,
style: &'a IconButtonStyle,
single_shape_frame: bool,
}
impl<'a> IconButton<'a> {
fn new(label: &'a str, size: Vec2, style: &'a IconButtonStyle) -> Self {
Self { label, size, selected: false, style, single_shape_frame: false }
}
fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// Paints fill and border as one rectangle, keeping the edge tessellation of a `Painter::rect`.
fn single_shape_frame(mut self) -> Self {
self.single_shape_frame = true;
self
}
/// Paints the button and returns its response. `paint_icon` gets the button's rect and the icon tint. A
/// non-finite, non-positive or oversized (over 4096 points) size gives an inert zero-size response.
fn show(self, ui: &mut Ui, paint_icon: impl FnOnce(&Ui, Rect, Color32)) -> Response {
let valid = self.size.is_finite() && self.size.x > 0.0 && self.size.y > 0.0 && self.size.x <= 4096.0 && self.size.y <= 4096.0;
let (rect, response) =
ui.allocate_exact_size(if valid { self.size } else { Vec2::ZERO }, if valid { Sense::click() } else { Sense::hover() });
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, valid && ui.is_enabled(), self.selected, self.label));
if !valid {
return response;
}
let visuals = self.style.visuals(self.selected, response.hovered(), response.is_pointer_button_down_on());
let stroke = bounded_stroke(visuals.stroke, rect);
if self.single_shape_frame {
ui.painter().rect(rect, self.style.corner_radius, visuals.fill, stroke, StrokeKind::Inside);
} else {
if visuals.fill != Color32::TRANSPARENT {
ui.painter().rect_filled(rect, self.style.corner_radius, visuals.fill);
}
if !stroke.is_empty() {
ui.painter().rect_stroke(rect, self.style.corner_radius, stroke, StrokeKind::Inside);
}
}
paint_icon(ui, rect, visuals.icon);
if response.has_focus() && rect.width() > 4.0 && rect.height() > 4.0 {
let focus_rect = rect.shrink(2.0);
let stroke = bounded_stroke(self.style.focus_stroke, focus_rect);
if !stroke.is_empty() {
ui.painter().rect_stroke(focus_rect, self.style.corner_radius, stroke, StrokeKind::Inside);
}
}
response
}
}
/// `stroke` no wider than half of `rect`'s smaller side; none when its width is not positive.
fn bounded_stroke(stroke: Stroke, rect: Rect) -> Stroke {
if stroke.width.is_finite() && stroke.width > 0.0 {
Stroke::new(stroke.width.min(rect.width().min(rect.height()) * 0.5), stroke.color)
} else {
Stroke::NONE
}
}
/// Local colors for shared icon-button interaction; transport-specific states stay in the toolbar.
fn button_style(selected_fill: Color32, normal_icon: Color32, radius: u8) -> IconButtonStyle {
let t = Tokens::current();
+9 -8
View File
@@ -65,14 +65,15 @@ fn the_midi_editor_keeps_the_key_for_its_selected_notes() {
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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();
}
+8 -7
View File
@@ -22,13 +22,14 @@ fn the_io_columns_vol_and_pan_readout_is_readable_in_both_themes() {
app.run("view.edit_io", json!({})).unwrap();
app.run("track.height", json!({"tracks": ["Kick"], "height": "medium"})).unwrap();
app.run("ui.theme", json!({"mode": mode.id()})).unwrap();
let mut harness = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut harness =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
for _ in 0..4 {
harness.step();
}
+3
View File
@@ -28,6 +28,7 @@ fn near(a: [i32; 3], b: Color32) -> bool {
fn grid_lines_are_drawn_over_clips_while_shown() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for theme in ["dark", "light"] {
for shown in [true, false] {
app.run("ui.theme", json!({"mode": theme})).unwrap();
@@ -76,6 +77,7 @@ fn grid_lines_are_drawn_over_clips_while_shown() {
fn clips_markers_grid_draws_a_line_at_a_memory_location() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
let kick = app.engine.session().track_by_name("Kick").unwrap();
let clip = &kick.clips()[0];
let marker = clip.start + clip.length / 3;
@@ -133,6 +135,7 @@ fn clips_markers_lines_refresh_across_lanes_and_hidden_open_folders() {
s.edit.grid_lines = true;
let mut app = SoundApp::new(engine, None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for (start, marker, scroll, zoom) in [(1_200, 9_000, 0, 20.0), (3_000, 11_000, 0, 20.0), (3_000, 11_000, 1_000, 40.0)] {
let s = app.engine.session_mut();
+12 -8
View File
@@ -21,14 +21,18 @@ fn frame(h: &mut Harness<'_, SoundApp>, px: Pos2, pressed: Option<bool>) {
fn interface_scale_slider_follows_the_pointer() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.extra.show_ui_customization = true;
let mut h = Harness::builder().with_size(WINDOW_PX).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut SoundApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(WINDOW_PX)
.with_pixels_per_point(1.0)
.build_ui_state(
|ui, app: &mut SoundApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(6);
let rail = h.get_by_role(Role::Slider).rect();
let start = pos2(rail.left() + rail.width() / 3.0, rail.center().y);
+9 -8
View File
@@ -15,14 +15,15 @@ fn auto_rename_dialog() -> (Harness<'static, SoundApp>, TrackId, ClipId) {
app.run("edit.select", json!({"clips": [clip.0]})).unwrap();
menus::invoke_menu(&mut app, "clip.auto_rename", "");
assert_eq!(app.dialogs.open_name(), Some("auto_rename"));
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
(h, track, clip)
}
+11 -7
View File
@@ -8,13 +8,17 @@ use std::path::{Path, PathBuf};
fn harness() -> Harness<'static, SoundApp> {
let app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(1_000).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_max_steps(1_000)
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
+8 -7
View File
@@ -19,13 +19,14 @@ fn bounce_starts_in_the_session_folder_and_browse_picks_the_file_and_format() {
engine.path = Some("/Songs/Midnight Groove/Midnight Groove.scraft".into());
let mut app = SoundApp::new(engine, None, Services { pick_save: Some(pick_save), ..Default::default() });
assert!(app.dialogs.open_for_command(&app.engine, "file.bounce_mix"));
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.get_by_label("Browse…").click();
h.run_steps(3);
@@ -21,6 +21,7 @@ fn the_clip_gain_icon_drags_with_the_pointer_in_one_undo_step() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.engine.execute("view.clip_gain_info", &json!({"value": true})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
frame(&ctx, &mut app, vec![]);
frame(&ctx, &mut app, vec![]);
let s = app.engine.session().clone();
+9 -8
View File
@@ -23,14 +23,15 @@ fn clip_looping_fills_up_to_the_next_clip() {
assert_eq!(app.dialogs.open_name(), Some("clip_looping"));
assert_eq!(app.engine.session().track(track).unwrap().clips().len(), before);
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
h.get_by_role_and_label(Role::RadioButton, "Loop Until End of Session or Next Clip").click();
h.run_steps(2);
+12 -8
View File
@@ -37,14 +37,18 @@ fn kick_clip_count(h: &Harness<'_, SoundApp>) -> usize {
fn demo() -> Harness<'static, SoundApp> {
let engine = soundcraft_engine::demo::demo_engine();
let app = SoundApp::new(engine, None, Services::default());
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_pixels_per_point(2.0).build_ui_state(
|ui, app: &mut SoundApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(1600.0, 1000.0))
.with_pixels_per_point(2.0)
.build_ui_state(
|ui, app: &mut SoundApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
for _ in 0..6 {
step(&mut h);
}
+60 -99
View File
@@ -1,61 +1,66 @@
//! The side lists in dock columns: the default shapes, saved layouts, drops into a column and
//! panels reopening in their dock.
use craft_ui::docking::{Column, Divider, DockArea, Group, Hit, Node, Side};
use craft_ui::layout::{SplitAxis, SplitSize};
use egui::{Rect, accesskit::Role};
//! The side lists in dock columns: the default shapes, saved layouts and panels reopening in
//! their dock.
use craft_behavior::DockSide;
use craft_behavior::dock::{Column, DockEdge, Group, Node, SplitSize};
use craft_behavior::flow::Axis;
use egui::{Rect, accesskit::Role, pos2, vec2};
use egui_kittest::kittest::Queryable;
use serde_json::json;
use soundcraft_ui_egui::docking::{self, CLIPS_WIDTH, MIDI_HEIGHT, Panel, TRACKS_WIDTH};
use soundcraft_ui_egui::{MainWindow, Services, SoundApp, UiState};
use soundcraft_ui_egui::{Services, SoundApp, UiState};
use super::docking_workflows::{drag, harness};
use super::docking_workflows::harness;
fn tabs(panel: Panel) -> Node<Panel> {
Node::Tabs { panels: vec![panel], active: 0 }
Node::tabs(vec![panel], 0)
}
fn dock(side: Side, panel: Panel, width: f32) -> Node<Panel> {
Node::Dock { side, columns: vec![Column::new(vec![Group::new(vec![panel], 0)], width)] }
fn column(panels: Vec<Panel>, active: usize, width: f32) -> Column<Panel> {
Column::new(vec![Group::new(panels, active)]).with_width(width)
}
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
fn dock(side: DockEdge, panel: Panel, width: f32) -> Node<Panel> {
Node::dock(side, vec![column(vec![panel], 0, width)])
}
fn rect(x: f32, y: f32, width: f32, height: f32) -> Rect {
Rect::from_min_size(pos2(x, y), vec2(width, height))
}
/// The columns of the dock on `side`.
fn columns(node: &Node<Panel>, side: Side) -> Option<&Vec<Column<Panel>>> {
fn columns(node: &Node<Panel>, side: DockEdge) -> Option<&Vec<Column<Panel>>> {
match node {
Node::Split { first, second, .. } => columns(first, side).or_else(|| columns(second, side)),
Node::Dock { side: found, columns } if *found == side => Some(columns),
Node::Dock { side: found, columns, .. } if *found == side => Some(columns),
_ => None,
}
}
fn dock_columns(h: &egui_kittest::Harness<'_, SoundApp>, side: Side) -> Vec<Column<Panel>> {
h.state().ui.docking.layout.root.as_ref().and_then(|root| columns(root, side)).cloned().unwrap_or_default()
fn dock_columns(h: &egui_kittest::Harness<'_, SoundApp>, side: DockEdge) -> Vec<Column<Panel>> {
h.state().ui.docking.layout().root.as_ref().and_then(|root| columns(root, side)).cloned().unwrap_or_default()
}
#[test]
fn default_layouts_put_the_side_lists_in_full_height_dock_columns() {
let edit = docking::edit_default();
let session = split(SplitAxis::Vertical, SplitSize::FixedSecond(MIDI_HEIGHT + 26.0), tabs(Panel::Canvas), tabs(Panel::Midi));
let expected = split(
SplitAxis::Horizontal,
let session = Node::split(Axis::Y, SplitSize::FixedSecond(MIDI_HEIGHT + 28.0), tabs(Panel::Canvas), tabs(Panel::Midi));
let expected = Node::split(
Axis::X,
SplitSize::FixedFirst(TRACKS_WIDTH),
dock(Side::Start, Panel::Tracks, TRACKS_WIDTH),
split(SplitAxis::Horizontal, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(Side::End, Panel::Clips, CLIPS_WIDTH)),
dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH),
Node::split(Axis::X, SplitSize::FixedSecond(CLIPS_WIDTH), session, dock(DockEdge::End, Panel::Clips, CLIPS_WIDTH)),
);
assert_eq!(edit.layout.root, Some(expected));
assert_eq!(edit.layout().root, Some(expected));
assert_eq!((TRACKS_WIDTH, CLIPS_WIDTH, MIDI_HEIGHT), (168.0, 230.0, 320.0));
let mix = docking::mix_default();
assert_eq!(
mix.layout.root,
Some(split(SplitAxis::Horizontal, SplitSize::FixedFirst(TRACKS_WIDTH), dock(Side::Start, Panel::Tracks, TRACKS_WIDTH), tabs(Panel::Canvas)))
mix.layout().root,
Some(Node::split(Axis::X, SplitSize::FixedFirst(TRACKS_WIDTH), dock(DockEdge::Start, Panel::Tracks, TRACKS_WIDTH), tabs(Panel::Canvas)))
);
for workspace in [&edit, &mix] {
let floating: Vec<_> = workspace.layout.floating.iter().map(|window| (window.panels().copied().collect::<Vec<_>>(), window.rect)).collect();
assert_eq!(floating, [(vec![Panel::Memory], [160.0, 120.0, 480.0, 280.0]), (vec![Panel::History], [680.0, 120.0, 260.0, 300.0])]);
assert!(workspace.hidden.is_empty());
let floating: Vec<_> = workspace.layout().floating.iter().map(|window| (window.panels().copied().collect::<Vec<_>>(), window.rect)).collect();
assert_eq!(floating, [(vec![Panel::Memory], rect(160.0, 120.0, 480.0, 280.0)), (vec![Panel::History], rect(680.0, 120.0, 260.0, 300.0))]);
assert!(workspace.hidden().is_empty());
}
docking::validate(&edit).unwrap();
docking::validate_mix(&mix).unwrap();
@@ -70,53 +75,15 @@ fn default_layouts_put_the_side_lists_in_full_height_dock_columns() {
let midi = h.ctx.data(|data| data.get_temp::<Rect>(egui::Id::unique("soundcraft-midi-body"))).unwrap();
assert!(tracks.left() < TRACKS_WIDTH && clips.right() > width - CLIPS_WIDTH, "tracks {tracks:?}, clips {clips:?}");
assert!(midi.left() >= TRACKS_WIDTH && midi.right() <= width - CLIPS_WIDTH, "midi {midi:?}");
assert!((midi.height() - MIDI_HEIGHT).abs() < 1.0 && midi.top() > clips.bottom(), "midi {midi:?}");
}
/// The Tracks group's body in the start dock: below its tab strip, down to the column's foot.
fn tracks_body(h: &egui_kittest::Harness<'_, SoundApp>) -> Rect {
let hits = DockArea::<Panel>::hit_rects(&h.ctx, docking::area_id(MainWindow::Edit));
let strip = hits
.iter()
.filter(|(hit, _)| matches!(hit, Hit::Tab(Panel::Tracks) | Hit::DragBar(Panel::Tracks)))
.fold(Rect::NOTHING, |all, (_, rect)| all.union(*rect));
// The column's inner edge runs the column's full height.
let bottom =
hits.iter().find(|(hit, _)| *hit == Hit::Divider(Divider::Column(Panel::Tracks))).map_or(f32::NEG_INFINITY, |(_, rect)| rect.bottom());
assert!(strip.is_positive() && bottom > strip.bottom() + 100.0, "strip {strip:?}, bottom {bottom}, hits {hits:?}");
Rect::from_min_max(egui::pos2(strip.left(), strip.bottom()), egui::pos2(strip.right(), bottom))
}
#[test]
fn a_tab_dropped_on_a_dock_group_joins_it_in_the_middle_and_stacks_below_in_the_lower_third() {
let mut h = harness(None, 1400.0, 1.0);
let body = tracks_body(&h);
let clips = h.get_by_role_and_label(Role::Tab, "Clips").rect().center();
drag(&mut h, clips, body.center());
assert_eq!(
dock_columns(&h, Side::Start),
[Column::new(vec![Group { active: 1, ..Group::new(vec![Panel::Tracks, Panel::Clips], 0) }], TRACKS_WIDTH)]
);
assert!(dock_columns(&h, Side::End).is_empty(), "the emptied end dock goes");
let mut h = harness(None, 1400.0, 1.0);
let body = tracks_body(&h);
let clips = h.get_by_role_and_label(Role::Tab, "Clips").rect().center();
drag(&mut h, clips, egui::pos2(body.center().x, body.bottom() - body.height() / 6.0));
let column = dock_columns(&h, Side::Start);
let groups: Vec<_> = column.iter().flat_map(|column| column.groups.iter().map(|group| group.panels.clone())).collect();
assert_eq!(groups, [vec![Panel::Tracks], vec![Panel::Clips]], "Clips stacks below Tracks in its column");
assert_eq!(column.len(), 1);
assert!(h.state().ui.show_clip_list);
docking::validate(&h.state().ui.docking).unwrap();
assert!(midi.height() > MIDI_HEIGHT / 2.0 && midi.top() > clips.bottom(), "midi {midi:?}");
}
#[test]
fn a_panel_without_a_recorded_place_reopens_at_its_default_place() {
use craft_ui::docking::{Action, Permissions, Placement, Zone};
use craft_behavior::dock::{Action, DockPlacement, Permissions};
let close = |state: &mut UiState, panel: Panel| {
state.docking.apply(Action::Close { panel }, |_| Permissions::default()).unwrap();
state.docking.hidden.clear();
state.docking.apply(Action::close(panel), false, |_| Permissions::default()).unwrap();
state.docking.forget_hidden(|_| true);
};
// Both docks gone: each list makes its dock again, at its default width. The MIDI editor
// opens under the session view, and Memory Locations and Undo History float where they
@@ -134,13 +101,13 @@ fn a_panel_without_a_recorded_place_reopens_at_its_default_place() {
h.state_mut().run("ui.dock", json!({"operation":"open","panel":panel})).unwrap();
}
h.run_steps(4);
assert_eq!(dock_columns(&h, Side::Start), [Column::new(vec![Group::new(vec![Panel::Tracks], 0)], TRACKS_WIDTH)]);
assert_eq!(dock_columns(&h, Side::End), [Column::new(vec![Group::new(vec![Panel::Clips], 0)], CLIPS_WIDTH)]);
let layout = &h.state().ui.docking.layout;
assert_eq!(dock_columns(&h, DockEdge::Start), [column(vec![Panel::Tracks], 0, TRACKS_WIDTH)]);
assert_eq!(dock_columns(&h, DockEdge::End), [column(vec![Panel::Clips], 0, CLIPS_WIDTH)]);
let layout = h.state().ui.docking.layout();
let midi = layout.location(&Panel::Midi).unwrap();
assert_eq!((midi.anchor, midi.placement), (Some(Panel::Canvas), Placement::Split(Zone::Bottom)));
let rect = |panel: Panel| layout.floating.iter().find(|window| window.contains(&panel)).map(|window| window.rect);
assert_eq!((rect(Panel::Memory), rect(Panel::History)), (Some([160.0, 120.0, 480.0, 280.0]), Some([680.0, 120.0, 260.0, 300.0])));
assert_eq!((midi.anchor, midi.placement), (Some(Panel::Canvas), DockPlacement::Split(DockSide::Bottom)));
let floats = |panel: Panel| layout.floating.iter().find(|window| window.contains(&panel)).map(|window| window.rect);
assert_eq!((floats(Panel::Memory), floats(Panel::History)), (Some(rect(160.0, 120.0, 480.0, 280.0)), Some(rect(680.0, 120.0, 260.0, 300.0))));
let ui = &h.state().ui;
assert!(ui.show_tracks_list && ui.show_clip_list && ui.show_midi_editor && ui.show_memory_locations && ui.show_undo_history);
docking::validate(&h.state().ui.docking).unwrap();
@@ -149,14 +116,7 @@ fn a_panel_without_a_recorded_place_reopens_at_its_default_place() {
let mut state = UiState::default();
state
.docking
.apply(
Action::Move {
panel: Panel::History,
anchor: Panel::Tracks,
placement: craft_ui::docking::Placement::Group { below: true, height: None },
},
|_| Permissions::default(),
)
.apply(Action::move_beside(Panel::History, Panel::Tracks, DockPlacement::group(true, None)), false, |_| Permissions::default())
.unwrap();
close(&mut state, Panel::Tracks);
state.show_tracks_list = false;
@@ -164,41 +124,42 @@ fn a_panel_without_a_recorded_place_reopens_at_its_default_place() {
let mut h = harness(Some(state), 1400.0, 1.0);
h.state_mut().run("window.track_list", json!({})).unwrap();
h.run_steps(4);
let groups: Vec<_> = dock_columns(&h, Side::Start).iter().flat_map(|column| column.groups.iter().map(|group| group.panels.clone())).collect();
let groups: Vec<_> = dock_columns(&h, DockEdge::Start).iter().flat_map(|column| column.groups.iter().map(|group| group.panels.clone())).collect();
assert_eq!(groups, [vec![Panel::History, Panel::Tracks]]);
assert_eq!(h.state().ui.docking.layout.panel_state(&Panel::Tracks), craft_ui::docking::PanelState::Front);
assert_eq!(h.state().ui.docking.layout().panel_state(&Panel::Tracks), craft_behavior::dock::PanelState::Front);
}
/// A hidden list or editor whose recorded anchor has disappeared reopens at its default place
/// instead of where craft-ui opens a panel it cannot restore.
#[test]
fn a_recorded_place_whose_anchor_is_gone_reopens_at_its_default_place() {
use craft_ui::docking::{Action, Permissions, Placement, Zone};
use craft_behavior::dock::{Action, DockPlacement, Permissions};
let allow = |_: &Panel| Permissions::default();
let mut state = UiState::default();
// Stale saved locations: their recorded anchor closed without leaving a place to follow.
for panel in [Panel::Clips, Panel::Midi, Panel::Tracks] {
state.docking.apply(Action::Close { panel }, allow).unwrap();
state.docking.apply(Action::close(panel), false, allow).unwrap();
}
state.docking.hidden.retain(|(panel, _)| *panel != Panel::Tracks);
for (_, location) in state.docking.hidden.iter_mut().filter(|(panel, _)| matches!(panel, Panel::Clips | Panel::Midi)) {
let mut hidden: Vec<_> = state.docking.hidden().iter().filter(|(panel, _)| *panel != Panel::Tracks).cloned().collect();
for (_, location) in hidden.iter_mut().filter(|(panel, _)| matches!(panel, Panel::Clips | Panel::Midi)) {
location.anchor = Some(Panel::Tracks);
location.placement = Placement::Split(Zone::Left);
location.placement = DockPlacement::Split(DockSide::Start);
location.sibling.clear();
location.floating = None;
}
state.docking = docking::Workspace::from_parts(state.docking.layout().clone(), hidden, state.docking.floated().to_vec());
docking::validate(&state.docking).unwrap();
state.show_clip_list = false;
state.show_midi_editor = false;
state.show_tracks_list = false;
let mut h = harness(Some(state), 1400.0, 1.0);
assert!(!h.state().ui.docking.layout.contains(&Panel::Tracks), "app sync keeps the stale anchor absent");
assert!(!h.state().ui.docking.layout().contains(&Panel::Tracks), "app sync keeps the stale anchor absent");
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"clips"})).unwrap();
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"midi"})).unwrap();
h.run_steps(4);
assert_eq!(dock_columns(&h, Side::End), [Column::new(vec![Group::new(vec![Panel::Clips], 0)], CLIPS_WIDTH)]);
let midi = h.state().ui.docking.layout.location(&Panel::Midi).unwrap();
assert_eq!((midi.anchor, midi.placement), (Some(Panel::Canvas), Placement::Split(Zone::Bottom)));
assert_eq!(dock_columns(&h, DockEdge::End), [column(vec![Panel::Clips], 0, CLIPS_WIDTH)]);
let midi = h.state().ui.docking.layout().location(&Panel::Midi).unwrap();
assert_eq!((midi.anchor, midi.placement), (Some(Panel::Canvas), DockPlacement::Split(DockSide::Bottom)));
assert!(h.state().ui.show_clip_list && h.state().ui.show_midi_editor);
docking::validate(&h.state().ui.docking).unwrap();
}
@@ -240,7 +201,7 @@ fn split_frame_settings() -> serde_json::Value {
fn split_frame_settings_load_as_the_dock_defaults_and_dock_layouts_round_trip() {
let mut settings = split_frame_settings();
// The old layout still parses: the reset is what replaces it.
assert!(serde_json::from_value::<UiState>(settings.clone()).unwrap().docking.layout.contains(&Panel::Clips));
assert!(serde_json::from_value::<UiState>(settings.clone()).unwrap().docking.layout().contains(&Panel::Clips));
docking::reset_old_layouts(&mut settings);
let state: UiState = serde_json::from_value(settings).unwrap();
assert_eq!(state.docking, docking::edit_default());
@@ -270,7 +231,7 @@ fn split_frame_settings_load_as_the_dock_defaults_and_dock_layouts_round_trip()
let loaded: UiState = serde_json::from_value(value).unwrap();
assert_eq!(loaded.docking, saved.docking);
assert_eq!(loaded.mix_docking, saved.mix_docking);
let groups: Vec<_> = columns(loaded.docking.layout.root.as_ref().unwrap(), Side::Start)
let groups: Vec<_> = columns(loaded.docking.layout().root.as_ref().unwrap(), DockEdge::Start)
.unwrap()
.iter()
.flat_map(|column| column.groups.iter().map(|group| group.panels.clone()))
@@ -287,11 +248,11 @@ fn a_floating_list_closed_beside_its_shown_dock_reopens_floating() {
h.state_mut().run("ui.dock", json!({"operation":"move","panel":"tracks","target":"clips","zone":"center"})).unwrap();
h.state_mut().run("ui.dock", json!({"operation":"float","panel":"clips","rect":[300,200,260,320]})).unwrap();
h.run_steps(4);
let rect = h.state().ui.docking.layout.floating.iter().find(|w| w.contains(&Panel::Clips)).unwrap().rect;
assert!(dock_columns(&h, Side::End).iter().any(|c| c.groups.iter().any(|g| g.panels.contains(&Panel::Tracks))));
let floated = h.state().ui.docking.layout().floating.iter().find(|w| w.contains(&Panel::Clips)).unwrap().rect;
assert!(dock_columns(&h, DockEdge::End).iter().any(|c| c.groups.iter().any(|g| g.panels.contains(&Panel::Tracks))));
h.state_mut().run("ui.dock", json!({"operation":"close","panel":"clips"})).unwrap();
h.run_steps(4);
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"clips"})).unwrap();
h.run_steps(4);
assert_eq!(h.state().ui.docking.layout.floating.iter().find(|w| w.contains(&Panel::Clips)).map(|w| w.rect), Some(rect));
assert_eq!(h.state().ui.docking.layout().floating.iter().find(|w| w.contains(&Panel::Clips)).map(|w| w.rect), Some(floated));
}
+54 -101
View File
@@ -1,5 +1,5 @@
//! Real Edit/Mix panel workflows, persistence, and command ownership without OS windows.
use egui::{Event, Modifiers, PointerButton, vec2};
use egui::{Rect, pos2, vec2};
use egui_kittest::{Harness, kittest::Queryable};
use serde_json::json;
use soundcraft_ui_egui::{MainWindow, Services, SoundApp, UiState, docking::Panel};
@@ -10,69 +10,48 @@ pub(crate) fn harness(state: Option<UiState>, width: f32, scale: f32) -> Harness
if let Some(state) = state {
app.ui = state;
}
let mut h = Harness::builder().with_size(vec2(width, 900.0)).with_pixels_per_point(scale).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_size(vec2(width, 900.0))
.with_pixels_per_point(scale)
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
pub(crate) fn drag(h: &mut Harness<'_, SoundApp>, from: egui::Pos2, to: egui::Pos2) {
h.event(Event::PointerMoved(from));
h.run_steps(2);
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(2);
for step in 1..=8 {
h.event(Event::PointerMoved(from.lerp(to, step as f32 / 8.0)));
h.run_steps(1);
}
h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(4);
}
/// A real panel drag, float, close and reopen keeps the recorded floating rectangle through a UI-state reload;
/// A panel moved, floated, closed and reopened keeps its recorded floating rectangle through a UI-state reload;
/// the Trim tool and record-arm controls still work, and a floating edit panel does not cover the mix strip used
/// after switching windows.
#[test]
fn real_drag_float_close_reopen_reload_retains_transport_and_mixer_commands() {
fn move_float_close_reopen_reload_retains_transport_and_mixer_commands() {
let mut h = harness(None, 1400.0, 1.0);
let source = h.get_by_role_and_label(egui::accesskit::Role::Tab, "Clips").rect().center();
let target = h.get_by_role_and_label(egui::accesskit::Role::Tab, "Tracks and Groups").rect().center();
drag(&mut h, source, target);
assert_eq!(h.state().ui.docking.layout.location(&Panel::Clips).unwrap().anchor, Some(Panel::Tracks));
h.get_by_role_and_label(egui::accesskit::Role::Tab, "Clips").click_button(PointerButton::Secondary);
h.state_mut().run("ui.dock", json!({"operation":"move","panel":"clips","target":"tracks","zone":"tab"})).unwrap();
h.run_steps(3);
h.get_by_label("Float Panel").click();
assert_eq!(h.state().ui.docking.layout().location(&Panel::Clips).unwrap().anchor, Some(Panel::Tracks));
h.state_mut().run("ui.dock", json!({"operation":"float","panel":"clips","rect":[400,150,260,320]})).unwrap();
h.run_steps(5);
let rect = h.state().ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Clips)).unwrap().rect;
h.get_by_role_and_label(egui::accesskit::Role::Tab, "Clips").click_button(PointerButton::Secondary);
h.run_steps(3);
h.get_by_label("Close Panel").click();
let rect = h.state().ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Clips)).unwrap().rect;
h.state_mut().run("ui.dock", json!({"operation":"close","panel":"clips"})).unwrap();
h.run_steps(4);
assert!(!h.state().ui.show_clip_list);
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"clips"})).unwrap();
h.run_steps(4);
assert_eq!(h.state().ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Clips)).unwrap().rect, rect);
assert_eq!(h.state().ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Clips)).unwrap().rect, rect);
let saved = serde_json::to_string(&h.state().ui).unwrap();
let expected = serde_json::to_value(&h.state().ui.docking).unwrap();
let mut reloaded = harness(Some(serde_json::from_str(&saved).unwrap()), 1400.0, 1.0);
assert_eq!(serde_json::to_value(&reloaded.state().ui.docking).unwrap(), expected);
reloaded.state_mut().run("ui.dock", json!({"operation":"move","panel":"clips","target":"tracks","zone":"center"})).unwrap();
reloaded.run_steps(4);
// A Tracks column too narrow for both tabs lists Tracks under the "Panels" overflow.
if let Some(overflow) = reloaded.query_by_label("Panels") {
overflow.click();
reloaded.run_steps(3);
reloaded.get_by_label("Tracks and Groups").click();
} else {
reloaded.get_by_role_and_label(egui::accesskit::Role::Tab, "Tracks and Groups").click();
}
reloaded.state_mut().run("ui.dock", json!({"operation":"activate","panel":"tracks"})).unwrap();
reloaded.run_steps(3);
assert_eq!(reloaded.state().ui.docking.layout.panel_state(&Panel::Tracks), craft_ui::docking::PanelState::Front);
assert_eq!(reloaded.state().ui.docking.layout().panel_state(&Panel::Tracks), craft_behavior::dock::PanelState::Front);
reloaded.get_by_label("Trim (F6)").click();
reloaded.run_steps(3);
assert_eq!(reloaded.state().engine.session().edit.tool, soundcraft_model::Tool::Trim);
@@ -83,10 +62,10 @@ fn real_drag_float_close_reopen_reload_retains_transport_and_mixer_commands() {
reloaded.state_mut().run("ui.dock", json!({"operation":"float","panel":"tracks","rect":[900,70,220,420]})).unwrap();
reloaded.run_steps(4);
assert_eq!(serde_json::to_value(&reloaded.state().ui.docking).unwrap(), edit);
assert!(!reloaded.state().ui.mix_docking.layout.contains(&Panel::Clips));
assert!(!reloaded.state().ui.mix_docking.layout().contains(&Panel::Clips));
let record = reloaded.get_by_label_contains("Record enable");
// A real pointer click must remain outside the floating panel's occluding rectangle.
assert!(!egui::Rect::from_min_size(egui::pos2(900.0, 70.0), vec2(220.0, 420.0)).contains(record.rect().center()));
assert!(!Rect::from_min_size(pos2(900.0, 70.0), vec2(220.0, 420.0)).contains(record.rect().center()));
record.click();
reloaded.run_steps(3);
assert!(reloaded.state().engine.session().tracks[0].mixer.record_arm);
@@ -102,7 +81,7 @@ fn activating_a_hidden_panel_shows_it_and_its_window_flag() {
h.state_mut().run("ui.dock", json!({"operation":"activate","panel":"tracks"})).unwrap();
h.run_steps(4);
assert!(h.state().ui.show_tracks_list);
assert_eq!(h.state().ui.docking.layout.panel_state(&Panel::Tracks), craft_ui::docking::PanelState::Front);
assert_eq!(h.state().ui.docking.layout().panel_state(&Panel::Tracks), craft_behavior::dock::PanelState::Front);
}
#[test]
@@ -166,7 +145,7 @@ fn reset_is_enabled_and_resolves_in_native_and_in_window_menu_trees() {
assert!(menus::item_state(&app, path, Some("ui.dock.reset")).0);
app.run("ui.dock", json!({"operation":"float","panel":"tracks","rect":[50,60,260,420]})).unwrap();
menus::invoke_menu(&mut app, "ui.dock.reset", path);
assert!(!app.ui.docking.layout.floating.iter().any(|group| group.contains(&Panel::Tracks)));
assert!(!app.ui.docking.layout().floating.iter().any(|group| group.contains(&Panel::Tracks)));
}
#[test]
@@ -181,61 +160,31 @@ fn legacy_preferences_restore_the_theme_and_validate_default_docking() {
soundcraft_ui_egui::docking::validate_mix(&restored.mix_docking).unwrap();
}
/// The tab group holding `panel` in the docked frames or a dock column.
fn docked_group(node: &craft_ui::docking::Node<Panel>, panel: Panel) -> Option<Vec<Panel>> {
use craft_ui::docking::Node;
match node {
Node::Split { first, second, .. } => docked_group(first, panel).or_else(|| docked_group(second, panel)),
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(panels.clone()),
Node::Dock { columns, .. } => {
columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)).map(|group| group.panels.clone())
}
_ => None,
}
}
/// A floating window saved as one `{panels, active, rect}` group, as releases before the shared docking model wrote
/// it, loads as one window and keeps its panels, active tab and place when written back and read again.
#[test]
fn a_floating_window_saved_in_the_one_group_shape_keeps_it_when_written_back() {
use craft_ui::docking::Node;
// A floating window as one `{panels, active, rect}` group, as releases before the shared
// docking model wrote it, beside the dock layout.
fn a_floating_window_saved_in_the_one_group_shape_round_trips() {
let mut settings = serde_json::to_value(UiState { show_midi_editor: true, ..Default::default() }).unwrap();
settings["docking"]["layout"]["floating"] = json!([{"panels": ["memory", "history"], "active": 1, "rect": [300.0, 120.0, 420.0, 360.0]}]);
let state: UiState = serde_json::from_value(settings).unwrap();
soundcraft_ui_egui::docking::validate(&state.docking).unwrap();
let floating = &state.docking.layout.floating;
let floating = &state.docking.layout().floating;
assert_eq!(floating.len(), 1);
assert_eq!(floating[0].root, Node::Tabs { panels: vec![Panel::Memory, Panel::History], active: 1 });
let root = state.docking.layout.root.clone().unwrap();
let groups = floating[0].groups();
assert_eq!(groups.len(), 1);
assert_eq!((groups[0].panels.clone(), groups[0].active), (vec![Panel::Memory, Panel::History], 1));
let root = state.docking.layout().root.clone().unwrap();
let mut state = state;
state.show_memory_locations = true;
state.show_undo_history = true;
let h = harness(Some(state), 1400.0, 1.0);
assert_eq!(h.state().ui.docking.layout.root.as_ref(), Some(&root), "drawing the loaded layout must not rearrange it");
assert_eq!(h.state().ui.docking.layout.floating[0].rect, [300.0, 120.0, 420.0, 360.0]);
let saved = serde_json::to_value(&h.state().ui.docking).unwrap();
let window = saved["layout"]["floating"].as_array().unwrap().iter().find(|w| w["panels"] == json!(["memory", "history"])).unwrap();
assert_eq!(window["active"], json!(1));
assert_eq!(window["rect"], json!([300.0, 120.0, 420.0, 360.0]));
}
#[test]
fn dragging_a_group_by_its_drag_bar_joins_it_to_another_group() {
use craft_ui::docking::{DockArea, Hit};
let mut h = harness(None, 1400.0, 1.0);
let root = h.state().ui.docking.layout.root.clone().unwrap();
assert_eq!(docked_group(&root, Panel::Tracks), Some(vec![Panel::Tracks]));
let hits = DockArea::<Panel>::hit_rects(&h.ctx, soundcraft_ui_egui::docking::area_id(MainWindow::Edit));
let bar = hits.iter().find(|(hit, _)| *hit == Hit::DragBar(Panel::Clips)).expect("the Clips group has a drag bar").1;
let target = h.get_by_role_and_label(egui::accesskit::Role::Tab, "Tracks and Groups").rect().center();
drag(&mut h, bar.center(), target);
let layout = &h.state().ui.docking.layout;
let group = docked_group(layout.root.as_ref().unwrap(), Panel::Tracks).unwrap();
assert_eq!(group.len(), 2, "the dropped group joins the Tracks tabs: {group:?}");
assert!(group.contains(&Panel::Clips));
assert!(h.state().ui.show_clip_list);
soundcraft_ui_egui::docking::validate(&h.state().ui.docking).unwrap();
assert_eq!(h.state().ui.docking.layout().root.as_ref(), Some(&root), "drawing the loaded layout must not rearrange it");
let reread: UiState = serde_json::from_value(serde_json::to_value(&h.state().ui).unwrap()).unwrap();
let window = reread.docking.layout().floating.iter().find(|window| window.contains(&Panel::Memory)).unwrap();
assert!(window.contains(&Panel::History));
assert_eq!(window.groups()[0].active, 1);
assert_eq!(window.rect, Rect::from_min_size(pos2(300.0, 120.0), vec2(420.0, 360.0)));
}
#[test]
@@ -257,31 +206,35 @@ fn malformed_dock_operations_name_the_field() {
/// process.
#[test]
fn panels_hidden_one_by_one_reopen_into_their_recorded_window() {
use craft_ui::docking::{Action, Node, Permissions};
use craft_behavior::dock::{Action, Floating, Permissions};
let allow = |_: &Panel| Permissions::default();
let mut state = UiState::default();
state.docking.layout.floating.retain(|window| !window.contains(&Panel::History));
let window = state.docking.layout.floating.iter_mut().find(|window| window.contains(&Panel::Memory)).unwrap();
let mut layout = state.docking.layout().clone();
layout.floating.retain(|window| !window.contains(&Panel::History));
let window = layout.floating.iter_mut().find(|window| window.contains(&Panel::Memory)).unwrap();
let rect = window.rect;
window.root = Node::Tabs { panels: vec![Panel::Memory, Panel::History], active: 0 };
state.docking.apply(Action::Close { panel: Panel::Memory }, allow).unwrap();
state.docking.apply(Action::Close { panel: Panel::History }, allow).unwrap();
let own = &mut state.docking.hidden.iter_mut().find(|(panel, _)| *panel == Panel::Memory).unwrap().1;
*window = Floating::single(window.id, vec![Panel::Memory, Panel::History], 0, rect);
state.docking = soundcraft_ui_egui::docking::Workspace::new(layout);
state.docking.apply(Action::close(Panel::Memory), false, allow).unwrap();
state.docking.apply(Action::close(Panel::History), false, allow).unwrap();
let mut hidden = state.docking.hidden().to_vec();
let own = &mut hidden.iter_mut().find(|(panel, _)| *panel == Panel::Memory).unwrap().1;
assert_eq!(own.anchor, Some(Panel::History));
// Only the outer hidden anchor retains a floating fallback, so the chain walk is required.
own.floating = None;
let own = own.clone();
assert_eq!(state.docking.layout.clone().restore(Panel::Memory, &own), Err(craft_ui::docking::DockError::MissingTarget));
state.docking = soundcraft_ui_egui::docking::Workspace::from_parts(state.docking.layout().clone(), hidden, state.docking.floated().to_vec());
assert_eq!(state.docking.layout().clone().restore(Panel::Memory, &own), Err(craft_behavior::dock::DockError::MissingTarget));
state.show_memory_locations = false;
state.show_undo_history = false;
let mut h = harness(Some(state), 1400.0, 1.0);
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"memory"})).unwrap();
h.run_steps(4);
let hidden_history = &h.state().ui.docking.hidden.iter().find(|(panel, _)| *panel == Panel::History).unwrap().1;
let hidden_history = &h.state().ui.docking.hidden().iter().find(|(panel, _)| *panel == Panel::History).unwrap().1;
assert_eq!(hidden_history.anchor, Some(Panel::Memory), "the restored chain reverses its hidden neighbour's anchor");
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"history"})).unwrap();
h.run_steps(4);
let layout = &h.state().ui.docking.layout;
let layout = h.state().ui.docking.layout();
let window = layout.floating.iter().find(|window| window.contains(&Panel::Memory)).expect("Memory reopens in its window");
assert!(window.contains(&Panel::History), "the hidden chain reopens History in Memory's window: {window:?}");
assert_eq!(window.rect, rect);
+12 -8
View File
@@ -68,6 +68,7 @@ fn tracks(mode: &str, tool: &str, lanes: &[&[(i64, i64)]]) -> (SoundApp, egui::C
e.execute("view.zoom_set", &json!({"samples_per_px": 400.0})).unwrap();
let mut app = SoundApp::new(e, None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
frame(&ctx, &mut app, vec![]);
frame(&ctx, &mut app, vec![]);
(app, ctx, tracks, ids)
@@ -251,14 +252,17 @@ fn toolbar_clicks_add_snap_to_grid_lock_shuffle_and_switch_grid_modes_despite_th
let mut e = Engine::default();
e.execute("edit.mode", &json!({"mode": "slip"})).unwrap();
let app = SoundApp::new(e, None, Services::default());
let mut h = egui_kittest::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,
);
let mut h = egui_kittest::Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.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,
);
h.run_steps(3);
let click = |h: &mut egui_kittest::Harness<'_, SoundApp>, label: &str, modifiers: Modifiers| {
h.get_by_label(label).click_modifiers(modifiers);
@@ -52,14 +52,15 @@ fn harness(track: &str, height: &str, view: &str) -> (Harness<'static, SoundApp>
app.run(view, json!({})).unwrap();
app.run("track.height", json!({"tracks": [track], "height": height})).unwrap();
let id = app.engine.session().track_by_name(track).unwrap().id;
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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..6 {
step(&mut h);
}
@@ -14,14 +14,15 @@ use soundcraft_ui_egui::dialogs::{Dialog, ask_to_save};
use soundcraft_ui_egui::{Services, SoundApp, menus};
fn harness(app: SoundApp) -> Harness<'static, SoundApp> {
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
h
}
@@ -150,6 +151,7 @@ fn a_dialog_opened_while_a_window_button_has_the_focus_takes_enter() {
fn the_enter_that_opens_a_dialog_does_not_press_its_default_button() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
run_frame(&ctx, &mut app, vec![]);
menus::invoke_menu(&mut app, "edit.fades_create", "Edit > Fades > Create...");
run_frame(&ctx, &mut app, vec![enter_key(false), enter_up()]);
@@ -181,6 +183,7 @@ fn enter_up() -> Event {
fn the_enter_that_replaces_an_open_dialog_does_not_press_the_new_default_button() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
menus::invoke_menu(&mut app, "setup.session", "Setup > Session");
run_frame(&ctx, &mut app, vec![]);
run_frame(&ctx, &mut app, vec![]);
@@ -196,6 +199,7 @@ fn the_enter_that_replaces_an_open_dialog_does_not_press_the_new_default_button(
fn a_rename_dialog_that_replaces_an_open_dialog_ignores_the_enter_of_its_first_frame() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
menus::invoke_menu(&mut app, "setup.session", "Setup > Session");
run_frame(&ctx, &mut app, vec![]);
run_frame(&ctx, &mut app, vec![]);
@@ -236,6 +240,7 @@ fn clear_auto_rename_modify_group_and_save_changes_replacing_a_dialog_ignore_the
for (name, open) in cases {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
menus::invoke_menu(&mut app, "setup.session", "Setup > Session");
run_frame(&ctx, &mut app, vec![]);
run_frame(&ctx, &mut app, vec![]);
@@ -249,6 +254,7 @@ fn clear_auto_rename_modify_group_and_save_changes_replacing_a_dialog_ignore_the
fn a_tempo_change_dialog_that_replaces_an_open_dialog_ignores_the_enter_of_its_first_frame() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
menus::invoke_menu(&mut app, "setup.session", "Setup > Session");
run_frame(&ctx, &mut app, vec![]);
let shapes = run_frame(&ctx, &mut app, vec![]);
@@ -274,6 +280,7 @@ fn a_tempo_change_dialog_that_replaces_an_open_dialog_ignores_the_enter_of_its_f
fn a_held_enter_does_not_press_the_default_button_until_it_is_pressed_again() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
run_frame(&ctx, &mut app, vec![]);
menus::invoke_menu(&mut app, "edit.fades_create", "Edit > Fades > Create...");
run_frame(&ctx, &mut app, vec![enter_key(false)]);
+18 -16
View File
@@ -18,14 +18,15 @@ fn dragging_down_the_group_dialogs_track_list_adds_each_track() {
assert!(tracks.len() >= 4);
app.run("edit.select", json!({"tracks": [tracks[0].0], "exact": true})).unwrap();
menus::invoke_menu(&mut app, "track.group", "Track > Group...");
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
let at: Vec<Pos2> = tracks[1..4].iter().map(|(_, n)| h.get_by_role_and_label(Role::CheckBox, n).rect().center()).collect();
h.event(Event::PointerMoved(at[0]));
@@ -61,14 +62,15 @@ fn modify_group_dialog_edits_the_existing_group() {
assert_eq!((id.map(|i| i.0), name.as_str(), *edit, *mix), (Some(g), "Drums", true, true));
assert_eq!(members.iter().filter(|m| m.2).map(|m| m.0).collect::<Vec<_>>(), vec![tracks[0].0]);
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
// Add a second track and submit.
h.get_by_role_and_label(Role::CheckBox, &tracks[1].1).click();
+1
View File
@@ -15,6 +15,7 @@ fn pass(ctx: &egui::Context, app: &mut SoundApp, shown: bool) -> Duration {
#[test]
fn only_a_shown_window_animates_and_a_hidden_one_wakes_once_a_second() {
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
for _ in 0..3 {
pass(&ctx, &mut app, true);
+8 -7
View File
@@ -11,13 +11,14 @@ fn browse(picked: Vec<PathBuf>) -> Harness<'static, SoundApp> {
});
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services { pick_open_many: Some(pick_open_many), ..Default::default() });
assert!(app.dialogs.open_for_command(&app.engine, "file.import_audio"));
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.get_by_label("Browse…").click();
h.run_steps(1);
+1 -1
View File
@@ -18,7 +18,7 @@ fn step(h: &mut Harness<'_, SoundApp>) {
#[test]
fn a_long_main_menu_scrolls_to_its_last_item() {
let app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let mut h = Harness::builder().with_size(SIZE).build_ui_state(
let mut h = Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(SIZE).build_ui_state(
|ui, app: &mut SoundApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
+1
View File
@@ -50,6 +50,7 @@ mod save_as_replace;
mod save_changes;
mod scroll_into_view;
mod send_window;
mod session_view_focus;
mod shared_controls;
mod shortcuts;
mod side_lists_access;
+1
View File
@@ -16,6 +16,7 @@ impl Rig {
engine.execute("track.new", &json!({})).unwrap();
engine.execute("markers.add", &json!({"name": "Verse", "at": 96_000})).unwrap();
let mut r = Rig { ctx: egui::Context::default(), app: SoundApp::new(engine, None, Services::default()), shapes: Vec::new() };
soundcraft_ui_egui::framework::install_headless(&r.ctx);
r.frames(4);
r
}
+8 -7
View File
@@ -12,13 +12,14 @@ use soundcraft_ui_egui::{MainWindow, Services, SoundApp};
fn harness(engine: soundcraft_engine::Engine) -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(engine, None, Services::default());
app.ui.window = MainWindow::Mix;
let mut h = Harness::builder().with_size(vec2(1400.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1400.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
@@ -15,6 +15,7 @@ impl Rig {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.engine.execute("edit.tool", &json!({"tool": tool})).unwrap();
let mut r = Rig { ctx: egui::Context::default(), app };
soundcraft_ui_egui::framework::install_headless(&r.ctx);
for _ in 0..4 {
r.frame(vec![]);
}
+9 -8
View File
@@ -13,14 +13,15 @@ fn harness(rename: bool) -> Harness<'static, SoundApp> {
if rename {
app.dialogs.open_rename_track(keys, "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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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();
}
+8 -7
View File
@@ -20,13 +20,14 @@ fn harness(disabled: &[&str]) -> Harness<'static, SoundApp> {
app.midi_inputs = Some(MidiInputs::with_port_names(names(disabled), names(&["Keys", "Drum Pad"])));
app.ui.midi_inputs_off = names(disabled);
app.ui.show_playback_engine = true;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
+1 -131
View File
@@ -21,137 +21,6 @@ fn button(pos: Pos2, pressed: bool) -> Event {
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }
}
fn check_resize(with_clip: bool) {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.ui.show_midi_editor = true;
if with_clip {
app.run("edit.select", json!({"tracks": ["Keys"]})).unwrap();
}
assert_eq!(midi_editor::target_clip(&app).is_some(), with_clip);
let ctx = egui::Context::default();
for _ in 0..6 {
frame(&ctx, &mut app, vec![]);
}
let initial = panel(&ctx);
assert!((initial.height() - 320.0).abs() < 1.0, "initial panel: {initial:?}");
let notes = app.engine.session().clone();
// Drag the shared boundary up and down, then allow several idle frames
// to catch a panel that looks resized but snaps back after release.
for height in [440.0, 280.0, 200.0] {
let before = panel(&ctx);
let start = pos2(before.center().x, before.top() - 26.0 - 2.0);
let end = pos2(start.x, before.bottom() - height - 26.0 - 2.0);
frame(&ctx, &mut app, vec![Event::PointerMoved(start)]);
frame(&ctx, &mut app, vec![button(start, true)]);
for step in 1..=6 {
frame(&ctx, &mut app, vec![Event::PointerMoved(start.lerp(end, step as f32 / 6.0))]);
}
frame(&ctx, &mut app, vec![button(end, false)]);
for _ in 0..4 {
frame(&ctx, &mut app, vec![]);
}
let after = panel(&ctx);
assert!((after.height() - height.max(260.0)).abs() < 1.0, "requested {height}, panel: {after:?}");
assert!((after.bottom() - initial.bottom()).abs() < 1.0);
assert!(app.edit_layout.timeline[3] <= after.top());
}
// Closing and reopening the dock keeps the chosen height.
let resized = panel(&ctx);
app.run("window.midi_editor", json!({})).unwrap();
frame(&ctx, &mut app, vec![]);
app.run("window.midi_editor", json!({})).unwrap();
for _ in 0..4 {
frame(&ctx, &mut app, vec![]);
}
assert_eq!(panel(&ctx), resized);
let saved = serde_json::to_string(&app.ui).unwrap();
app.ui = serde_json::from_str(&saved).unwrap();
for _ in 0..4 {
frame(&ctx, &mut app, vec![]);
}
assert_eq!(panel(&ctx), resized);
assert_eq!(*app.engine.session(), notes);
}
#[test]
fn midi_panel_resizes_with_a_selected_clip() {
check_resize(true);
}
#[test]
fn midi_panel_resizes_without_a_selected_clip() {
check_resize(false);
}
#[test]
fn layout_reset_cancels_a_held_midi_divider_without_editing_the_session() {
check_held_replacement("reset");
}
#[test]
fn arrange_cancels_a_held_midi_divider_without_editing_the_session() {
check_held_replacement("arrange");
}
#[test]
fn legacy_visibility_sync_cancels_a_held_midi_divider_without_editing_the_session() {
check_held_replacement("visibility");
}
fn check_held_replacement(operation: &str) {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.ui.show_midi_editor = true;
app.run("edit.select", json!({"tracks":["Keys"]})).unwrap();
app.ui.show_memory_locations = operation == "arrange";
let session = app.engine.session().clone();
let ctx = egui::Context::default();
for _ in 0..6 {
frame(&ctx, &mut app, vec![]);
}
let initial = panel(&ctx);
let start = pos2(initial.center().x, initial.top() - 28.0);
frame(&ctx, &mut app, vec![Event::PointerMoved(start)]);
frame(&ctx, &mut app, vec![button(start, true)]);
let first = start - vec2(0.0, 80.0);
frame(&ctx, &mut app, vec![Event::PointerMoved(first)]);
frame(&ctx, &mut app, vec![]);
assert!((panel(&ctx).height() - 400.0).abs() < 1.0, "first drag must resize");
let second = start - vec2(0.0, 120.0);
frame(&ctx, &mut app, vec![Event::PointerMoved(second)]);
frame(&ctx, &mut app, vec![]);
assert!((panel(&ctx).height() - 440.0).abs() < 1.0, "a normal second held move must continue resizing");
match operation {
"reset" => {
app.run("ui.dock.reset", json!({})).unwrap();
}
"arrange" => {
app.run("window.arrange_cascade", json!({})).unwrap();
}
"visibility" => {
app.run("window.midi_editor", json!({})).unwrap();
frame(&ctx, &mut app, vec![]);
app.run("window.midi_editor", json!({})).unwrap();
frame(&ctx, &mut app, vec![]);
}
_ => panic!("unknown synthetic operation"),
}
let reset = serde_json::to_value(&app.ui.docking).unwrap();
let after_reset = start - vec2(0.0, 160.0);
frame(&ctx, &mut app, vec![Event::PointerMoved(after_reset)]);
frame(&ctx, &mut app, vec![]);
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), reset, "old held divider must not resize the replacement layout");
let expected = if operation == "reset" { 320.0 } else { 440.0 };
assert!((panel(&ctx).height() - expected).abs() < 1.0);
frame(&ctx, &mut app, vec![button(after_reset, false)]);
for _ in 0..4 {
frame(&ctx, &mut app, vec![]);
}
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), reset);
assert_eq!(*app.engine.session(), session);
}
#[test]
fn a_selected_video_clip_is_not_a_midi_target() {
use soundcraft_model::{ChannelFormat, Clip, ClipContent, SourceId, Track, TrackKind};
@@ -182,6 +51,7 @@ fn only_pencil_inserts_notes_in_the_midi_roll() {
let clip = created["clip"].as_u64().unwrap();
app.run("edit.select", json!({"clips": [clip]})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
frame(&ctx, &mut app, vec![]);
}
+8 -7
View File
@@ -12,13 +12,14 @@ fn quantize_on(grid: &str) -> i64 {
app.run("edit.select", json!({"clips": [clip]})).unwrap();
app.run("view.grid", json!({"value": grid})).unwrap();
app.ui.show_midi_editor = true;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.get_by_label("Quantize").click();
h.run_steps(3);
+13 -10
View File
@@ -25,16 +25,19 @@ fn painted_labels_with(narrow: bool, fonts: Option<FontDefinitions>) -> Vec<(Str
app.run("view.mix_section", json!({"section": "all"})).unwrap();
app.run("view.mix_section", json!({"section": "instruments"})).unwrap();
app.ui.narrow_mix = narrow;
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
if let Some(f) = &fonts {
ui.ctx().set_fonts(f.clone());
}
app.ui(ui);
},
app,
);
let mut harness = egui_kittest::Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(1600.0, 1000.0))
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(ui.ctx());
if let Some(f) = &fonts {
ui.ctx().set_fonts(f.clone());
}
app.ui(ui);
},
app,
);
for _ in 0..4 {
harness.step();
}
+8 -7
View File
@@ -14,13 +14,14 @@ fn mix_in_a_separate_window_toggles_and_closing_it_returns_to_the_main_window()
app.run("window.toggle_mix_edit", json!({})).unwrap();
assert_eq!(app.ui.window, MainWindow::Edit, "Mix is already on screen: the main window keeps Edit");
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
let app = h.state_mut();
assert!(app.ui.mix_separate, "drawing both windows keeps them both");
+1
View File
@@ -17,6 +17,7 @@ impl Rig {
engine.execute("track.new", &json!({"kind": kind})).unwrap();
engine.execute("edit.tool", &json!({"tool": "pencil"})).unwrap();
let mut r = Rig { ctx: egui::Context::default(), app: SoundApp::new(engine, None, Services::default()) };
soundcraft_ui_egui::framework::install_headless(&r.ctx);
r.frames(4);
r
}
+11 -7
View File
@@ -13,13 +13,17 @@ fn harness(tracks: usize) -> Harness<'static, SoundApp> {
engine.execute("track.new", &serde_json::json!({"count": tracks})).unwrap();
}
let app = SoundApp::new(engine, None, Services::default());
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
+8 -7
View File
@@ -13,13 +13,14 @@ fn harness(engine: soundcraft_engine::Engine, window: MainWindow) -> Harness<'st
app.ui.window = window;
app.run("view.edit_inserts_ae", json!({})).unwrap();
app.run("track.height", json!({"tracks": ["Vox"], "height": "medium"})).unwrap();
let mut h = Harness::builder().with_size(vec2(1400.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1400.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
@@ -8,14 +8,15 @@ use soundcraft_ui_egui::{Services, SoundApp};
use std::collections::BTreeMap;
fn harness(app: SoundApp) -> Harness<'static, SoundApp> {
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(4);
h
}
@@ -8,14 +8,15 @@ use soundcraft_ui_egui::{Services, SoundApp};
use std::collections::BTreeMap;
fn harness(app: SoundApp) -> Harness<'static, SoundApp> {
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(4);
h
}
+8 -7
View File
@@ -7,13 +7,14 @@ fn a_long_plugin_window_stays_on_a_short_screen() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
app.ui.plugin_windows = vec![(kick, 0)];
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 500.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(egui::vec2(1200.0, 500.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("plugin", kick.0, 0usize)))).unwrap();
assert!(window.bottom() <= 500.0, "{window:?}");
@@ -202,6 +202,7 @@ fn the_piano_roll_leaves_modified_arrows_to_the_shortcuts() {
app.ui.show_midi_editor = true;
app.run("edit.select", json!({"tracks": ["Keys"]})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
let frame = |app: &mut SoundApp, events: Vec<Event>| {
let raw = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0))), events, ..Default::default() };
ctx.run_ui(raw, |ui| {
@@ -241,6 +242,7 @@ fn the_piano_roll_selection_follows_notes_the_arrows_move_past_others() {
app.ui.show_midi_editor = true;
app.run("edit.select", json!({"tracks": ["Keys"]})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
let frame = |app: &mut SoundApp, events: Vec<Event>| {
let raw = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0))), events, ..Default::default() };
ctx.run_ui(raw, |ui| {
+8 -7
View File
@@ -9,13 +9,14 @@ use soundcraft_ui_egui::{Services, SoundApp};
fn record_in_an_empty_session_shows_why_at_both_record_buttons() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.ui.show_transport = true;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
assert_eq!(h.query_all_by_label_contains("Nothing to record on").count(), 0);
h.get_by_label("transport.record").click();
+9 -8
View File
@@ -9,14 +9,15 @@ fn typing_in_the_rename_clip_dialog_replaces_the_old_name() {
let clip = app.engine.session().track_by_name("Kick").unwrap().clips()[0].clone();
app.run("edit.select", json!({"clips": [clip.id.0]})).unwrap();
menus::invoke_menu(&mut app, "clip.rename", "Clip > Rename...");
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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();
}
+9 -8
View File
@@ -21,14 +21,15 @@ fn editing_rtp_velocity_leaves_the_other_properties_alone() {
app.run("edit.select", json!({"tracks": [t.0], "exact": true})).unwrap();
menus::invoke_menu(&mut app, "window.rtp", "Event > MIDI Real-Time Properties");
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
assert!(h.state().ui.show_rtp, "the window did not open");
let rtp = |h: &Harness<'_, SoundApp>, key: &str, d: f64| h.state().engine.session().edit.value(&format!("rtp.{}.{key}", t.0), d);
+9 -8
View File
@@ -49,14 +49,15 @@ fn harness() -> (Harness<'static, SoundApp>, TrackId) {
let keys = engine.session().tracks.iter().find(|t| t.name == "Keys").unwrap().id;
let mut app = SoundApp::new(engine, None, Services::default());
app.ui.plugin_windows.push((keys, soundcraft_mix::INSTRUMENT_SLOT));
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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..6 {
step(&mut h);
}
+8 -7
View File
@@ -19,13 +19,14 @@ fn saving_over_another_session_takes_the_replace_button() {
path: path.to_string_lossy().into(),
key: "path".into(),
});
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.key_press(egui::Key::Enter);
h.run_steps(3);
+1 -1
View File
@@ -6,7 +6,7 @@ use soundcraft_ui_egui::{Services, SoundApp, dialogs, menus};
fn harness() -> Harness<'static, SoundApp> {
let app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
+11 -7
View File
@@ -17,13 +17,17 @@ fn harness(tracks: usize) -> Harness<'static, SoundApp> {
// Uneven heights, so an offset counted as "n rows" can't pass for the real one.
app.run("track.height", json!({"tracks": ["T02"], "height": "large"})).unwrap();
app.run("track.height", json!({"tracks": ["T04"], "height": "small"})).unwrap();
let mut h = Harness::builder().with_size(vec2(SIZE.0, SIZE.1)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(SIZE.0, SIZE.1))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
+11 -7
View File
@@ -18,13 +18,17 @@ fn harness() -> (Harness<'static, SoundApp>, soundcraft_model::TrackId) {
}
let mut app = SoundApp::new(engine, None, Services::default());
app.ui.window = MainWindow::Mix;
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
(h, vox)
}
@@ -0,0 +1,300 @@
//! The session view as a Tab stop: it takes the keyboard when it opens and when it is pressed, keeps Tab while Tab has
//! a stop to go to, and leaves every other key to the shortcuts, as with nothing focused.
use std::cell::{Cell, RefCell};
use egui::accesskit::Role;
use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, ViewportId, ViewportInfo, vec2};
use egui_kittest::{Harness, kittest::Queryable};
use serde_json::json;
use soundcraft_model::{ClipId, Tool};
use soundcraft_ui_egui::framework::session_view_id;
use soundcraft_ui_egui::{Services, SoundApp, edit_window, menus};
type AppHarness = Harness<'static, SoundApp>;
fn harness() -> AppHarness {
harness_of(soundcraft_engine::demo::demo_engine())
}
fn harness_of(engine: soundcraft_engine::Engine) -> AppHarness {
let app = SoundApp::new(engine, None, Services::default());
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
fn focused(h: &AppHarness) -> Option<Id> {
h.ctx.memory(|m| m.focused())
}
fn edit_view() -> Option<Id> {
Some(session_view_id(true))
}
fn press(h: &mut AppHarness, modifiers: Modifiers, key: Key) {
h.key_press_modifiers(modifiers, key);
h.run_steps(3);
}
fn select(h: &mut AppHarness, params: serde_json::Value) {
h.state_mut().run("edit.select", params).unwrap();
h.run_steps(2);
}
fn insertion(h: &AppHarness) -> i64 {
h.state().engine.session().edit.selection.start
}
/// Where each of Kick's clips starts and ends.
fn kick_clips(h: &AppHarness) -> Vec<(ClipId, i64, i64)> {
h.state().engine.session().track_by_name("Kick").unwrap().clips().iter().map(|c| (c.id, c.start, c.end())).collect()
}
/// A point in the Edit window's timeline.
fn in_timeline(h: &AppHarness) -> Pos2 {
edit_window::rect(h.state().edit_layout.timeline).left_top() + vec2(300.0, 20.0)
}
fn button(h: &mut AppHarness, pos: Pos2, pressed: bool) {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
#[test]
fn tab_and_shift_tab_pass_through_a_session_view_with_no_stop_ahead() {
let mut h = harness();
select(&mut h, json!({"start": 1_000_000_000}));
assert_eq!(focused(&h), edit_view(), "the opened session view has the focus");
press(&mut h, Modifiers::SHIFT, Key::Tab);
let before = focused(&h);
assert!(before.is_some() && before != edit_view(), "Shift+Tab leaves the view");
press(&mut h, Modifiers::NONE, Key::Tab);
assert_eq!(focused(&h), edit_view(), "Tab from the stop before the view");
for _ in 0..3 {
press(&mut h, Modifiers::NONE, Key::Tab);
let after = focused(&h);
assert!(after.is_some() && after != edit_view() && after != before, "Tab goes on through the stops after the view");
}
for _ in 0..3 {
press(&mut h, Modifiers::SHIFT, Key::Tab);
}
assert_eq!(focused(&h), edit_view(), "Shift+Tab walks back to the view");
press(&mut h, Modifiers::SHIFT, Key::Tab);
assert_eq!(focused(&h), before, "and past it");
assert_eq!(insertion(&h), 1_000_000_000);
}
#[test]
fn the_focused_session_view_keeps_tab_until_the_last_stop() {
let mut h = harness();
let (_, start, end) = kick_clips(&h).into_iter().max_by_key(|clip| clip.2).unwrap();
select(&mut h, json!({"tracks": ["Kick"], "start": start, "exact": true}));
press(&mut h, Modifiers::SHIFT, Key::Tab);
assert_eq!((insertion(&h), focused(&h)), (start, edit_view()), "Shift+Tab extends the selection");
assert!(h.state().engine.session().edit.selection.end > start);
select(&mut h, json!({"tracks": ["Kick"], "start": start, "exact": true}));
while insertion(&h) < end {
let at = insertion(&h);
press(&mut h, Modifiers::NONE, Key::Tab);
assert!(insertion(&h) > at, "Tab goes to the next stop");
assert_eq!(focused(&h), edit_view());
}
press(&mut h, Modifiers::NONE, Key::Tab);
assert_eq!(insertion(&h), end);
assert!(focused(&h).is_some() && focused(&h) != edit_view(), "past the last stop Tab moves on");
}
#[test]
fn a_held_tab_that_reaches_the_last_stop_stays_in_the_session_view() {
let mut h = harness();
let end = kick_clips(&h).into_iter().map(|clip| clip.2).max().unwrap();
select(&mut h, json!({"tracks": ["Kick"], "start": end - 1, "exact": true}));
let tab = |h: &mut AppHarness, pressed: bool, repeat: bool| {
h.event(Event::Key { key: Key::Tab, physical_key: None, pressed, repeat, modifiers: Modifiers::NONE });
h.run_steps(1);
};
tab(&mut h, true, false);
assert_eq!((insertion(&h), focused(&h)), (end, edit_view()), "the press reaches the last stop");
for _ in 0..3 {
tab(&mut h, true, true);
assert_eq!(focused(&h), edit_view(), "a repeat");
}
tab(&mut h, false, false);
h.run_steps(2);
assert_eq!(focused(&h), edit_view());
press(&mut h, Modifiers::NONE, Key::Tab);
assert!(focused(&h).is_some() && focused(&h) != edit_view(), "the next press moves on");
}
#[test]
fn a_press_in_the_session_view_takes_the_keyboard_from_a_toolbar_button() {
let mut h = harness();
let tool = h.state().engine.session().edit.tool;
assert_ne!(tool, Tool::Trim);
h.get_by_label("Trim (F6)").focus();
h.run_steps(2);
assert!(h.get_by_label("Trim (F6)").is_focused());
let at = in_timeline(&h);
h.hover_at(at);
button(&mut h, at, true);
assert_eq!(focused(&h), edit_view(), "the press");
button(&mut h, at, false);
assert_eq!(focused(&h), edit_view(), "the click");
let markers = h.state().engine.session().markers.len();
press(&mut h, Modifiers::NONE, Key::Enter);
assert_eq!(h.state().engine.session().markers.len(), markers + 1, "Enter adds a marker");
assert_eq!(h.state().engine.session().edit.tool, tool, "and leaves the button alone");
button(&mut h, at, true);
button(&mut h, at, false);
assert_eq!(focused(&h), edit_view(), "a press in the focused view");
h.get_by_label("Trim (F6)").click();
h.run_steps(3);
assert_eq!(h.state().engine.session().edit.tool, Tool::Trim);
select(&mut h, json!({"tracks": ["Kick"], "start": 0}));
press(&mut h, Modifiers::NONE, Key::Tab);
assert!(insertion(&h) > 0, "a click on a toolbar button leaves Tab to the session view");
}
#[test]
fn a_session_view_that_opens_takes_the_focus() {
let mut h = harness();
h.state_mut().run("window.toggle_mix_edit", json!({})).unwrap();
h.run_steps(3);
assert_eq!(focused(&h), Some(session_view_id(false)), "the Mix window's");
h.state_mut().run("window.toggle_mix_edit", json!({})).unwrap();
h.run_steps(3);
assert_eq!(focused(&h), edit_view());
}
#[test]
fn a_closed_search_gives_the_focus_back_to_the_session_view() {
let mut h = harness();
for (typed, key) in [("", Key::Escape), ("Zoom In", Key::Enter)] {
h.state_mut().run("window.search", json!({})).unwrap();
h.run_steps(3);
assert!(h.ctx.text_edit_focused(), "the search field");
h.event(Event::Text(typed.into()));
press(&mut h, Modifiers::NONE, key);
h.run_steps(2);
assert!(!h.state().ui.show_search);
assert_eq!(focused(&h), edit_view(), "{key:?}");
select(&mut h, json!({"tracks": ["Kick"], "start": 0}));
press(&mut h, Modifiers::NONE, Key::Tab);
assert!(insertion(&h) > 0, "{key:?}: Tab moves the insertion point");
}
}
#[test]
fn a_session_made_from_a_dialog_takes_the_focus() {
let mut h = harness_of(soundcraft_engine::Engine::default());
h.get_by_label("Trim (F6)").focus();
h.run_steps(2);
assert_ne!(focused(&h), edit_view());
menus::invoke_menu(h.state_mut(), "session.new", "File > New Session...");
h.run_steps(3);
assert_eq!(h.state().dialogs.open_name(), Some("new_session"));
h.get_by_role_and_label(Role::Button, "Create").focus();
h.run_steps(2);
press(&mut h, Modifiers::NONE, Key::Enter);
h.run_steps(2);
assert_eq!((h.state().dialogs.open_name(), focused(&h)), (None, edit_view()));
}
thread_local! {
/// The events of the Mix window's next pass, and the widget that had its focus in the last one.
static MIX_EVENTS: RefCell<Vec<Event>> = const { RefCell::new(Vec::new()) };
static MIX_FOCUS: Cell<Option<Id>> = const { Cell::new(None) };
}
/// The open windows, as eframe lists them in the input of each: the runtime drops what it keeps of a window that the
/// input leaves out.
fn windows() -> egui::ViewportIdMap<ViewportInfo> {
let mix = ViewportInfo { parent: Some(ViewportId::ROOT), ..Default::default() };
[(ViewportId::ROOT, ViewportInfo::default()), (ViewportId::from_hash_of("soundcraft.mix"), mix)].into_iter().collect()
}
/// Draws the Mix window as a native one: its pass runs inside the main window's, as eframe's does.
fn render_mix(ctx: &egui::Context, viewport: egui::ImmediateViewport<'_>) {
let mut show = viewport.viewport_ui_cb;
let input = RawInput {
viewport_id: viewport.ids.this,
viewports: windows(),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1100.0, 720.0))),
events: MIX_EVENTS.take(),
..Default::default()
};
let mut output = ctx.run_ui(input, |ui| {
show(ui);
MIX_FOCUS.set(ui.ctx().memory(|m| m.focused()));
});
output.textures_delta.clear();
}
/// Runs a frame of both windows with `events` in the Mix window, then settles.
fn mix_frames(ctx: &egui::Context, app: &mut SoundApp, events: Vec<Event>) -> Option<Id> {
MIX_EVENTS.set(events);
for _ in 0..4 {
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0)));
ctx.run_ui(RawInput { viewports: windows(), screen_rect, ..Default::default() }, |ui| {
app.logic(ui.ctx());
app.ui(ui);
})
.textures_delta
.clear();
}
MIX_FOCUS.get()
}
#[test]
fn tab_and_shift_tab_leave_the_session_view_of_a_separate_mix_window() {
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
ctx.set_embed_viewports(false);
egui::Context::set_immediate_viewport_renderer(render_mix);
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.run("edit.select", json!({"tracks": ["Kick"], "start": 0})).unwrap();
app.run("window.mix_separate", json!({"value": true})).unwrap();
let view = Some(session_view_id(false));
assert_eq!(mix_frames(&ctx, &mut app, Vec::new()), view, "the opened Mix window's session view has its focus");
let tab = |modifiers: Modifiers| -> Vec<Event> {
let key = [true, false].map(|pressed| Event::Key { key: Key::Tab, physical_key: None, pressed, repeat: false, modifiers });
[Event::ModifiersChanged(modifiers)].into_iter().chain(key).chain([Event::ModifiersChanged(Modifiers::NONE)]).collect()
};
let after = mix_frames(&ctx, &mut app, tab(Modifiers::NONE));
assert!(after.is_some() && after != view, "Tab goes on to the strips: {after:?}, the view is {view:?}");
assert_eq!(mix_frames(&ctx, &mut app, tab(Modifiers::SHIFT)), view, "Shift+Tab walks back");
let before = mix_frames(&ctx, &mut app, tab(Modifiers::SHIFT));
assert!(before.is_some() && before != view, "and past the view: {before:?}");
assert_eq!(app.engine.session().edit.selection.start, 0);
}
#[test]
fn the_shortcuts_run_with_the_session_view_focused() {
let mut h = harness();
let zoom = |h: &AppHarness| h.state().engine.session().edit.zoom.samples_per_px;
let before = zoom(&h);
press(&mut h, Modifiers::NONE, Key::T);
assert!(zoom(&h) < before, "T zooms in");
let (clip, ..) = kick_clips(&h)[0];
select(&mut h, json!({"clips": [clip.0]}));
press(&mut h, Modifiers::NONE, Key::Delete);
assert!(h.state().engine.session().find_clip(clip).is_none(), "Delete clears the clip");
press(&mut h, Modifiers::COMMAND, Key::Z);
assert!(h.state().engine.session().find_clip(clip).is_some(), "Ctrl+Z brings it back");
press(&mut h, Modifiers::NONE, Key::Home);
assert_eq!(h.state().engine.session().edit.playhead, 0, "Home returns to zero");
press(&mut h, Modifiers::NONE, Key::ArrowDown);
press(&mut h, Modifiers::NONE, Key::Escape);
assert_eq!(focused(&h), edit_view(), "the arrows and Escape leave the focus in the view");
}
+28 -21
View File
@@ -105,13 +105,14 @@ fn tool_and_record_buttons_handle_keyboard_disabled_state_and_cancelled_clicks()
#[test]
fn toolbar_keyboard_activation_changes_tools_without_transport_or_marker_actions() {
let app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.get_by_label("Trim (F6)").click();
h.run_steps(3);
@@ -138,13 +139,14 @@ fn toolbar_keyboard_activation_changes_tools_without_transport_or_marker_actions
fn track_record_button_arms_the_track_without_starting_transport() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.run("track.new", serde_json::json!({"name": "Voice"})).unwrap();
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.get_by_label_contains("Record enable").click();
h.run_steps(3);
@@ -167,13 +169,18 @@ fn shared_controls_visuals() {
std::fs::create_dir_all(&directory).unwrap();
for scale in [1.0, 2.0] {
let app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_pixels_per_point(scale).wgpu().build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
.with_size(vec2(1600.0, 1000.0))
.with_pixels_per_point(scale)
.wgpu()
.build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.input_mut().max_texture_side = Some(8192);
for (name, size) in [("normal", vec2(1600.0, 1000.0)), ("narrow", vec2(1000.0, 700.0))] {
h.set_size(size);
+8 -2
View File
@@ -42,12 +42,15 @@ fn type_in_app(ctx: &egui::Context, app: &mut SoundApp, keys: &[(Key, Modifiers)
fn tab_leaves_the_keys_to_the_shortcuts() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..3 {
type_in_app(&ctx, &mut app, &[]);
}
app.run("edit.select", json!({"tracks": ["Kick"], "start": 0})).unwrap();
let view = Some(soundcraft_ui_egui::framework::session_view_id(true));
for tab in [Modifiers::NONE, Modifiers::SHIFT] {
type_in_app(&ctx, &mut app, &[(Key::Tab, tab)]);
assert_eq!(ctx.memory(|m| m.focused()), None, "{tab:?}");
assert_eq!(ctx.memory(|m| m.focused()), view, "{tab:?}");
let zoom = app.engine.session().edit.zoom.samples_per_px;
type_in_app(&ctx, &mut app, &[(Key::T, Modifiers::NONE)]);
assert_eq!(app.engine.session().edit.zoom.samples_per_px, zoom / 2.0, "{tab:?}");
@@ -139,6 +142,7 @@ fn x_and_middle(app: &SoundApp, at: i64) -> (f32, f32) {
fn left_and_right_arrows_centre_the_edit_window_on_the_selected_clip() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
let (clip_id, clip) = app.engine.session().tracks.iter().flat_map(|t| t.clips()).find(|c| c.start > 100_000).map(|c| (c.id, c.range())).unwrap();
app.run("view.zoom_set", json!({"samples_per_px": 10.0})).unwrap();
app.run("view.scroll", json!({"to": 0})).unwrap();
@@ -172,6 +176,7 @@ fn the_piano_roll_keeps_the_plain_arrows() {
app.run("view.zoom_set", json!({"samples_per_px": 10.0})).unwrap();
app.run("view.scroll", json!({"to": 1_000_000})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
app_frame(&ctx, &mut app, vec![]);
}
@@ -201,6 +206,7 @@ fn a_midi_editor_behind_another_tab_leaves_the_arrows_to_the_edit_window() {
app.run("view.zoom_set", json!({"samples_per_px": 10.0})).unwrap();
app.run("view.scroll", json!({"to": 0})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
app_frame(&ctx, &mut app, vec![]);
}
@@ -211,7 +217,7 @@ fn a_midi_editor_behind_another_tab_leaves_the_arrows_to_the_edit_window() {
app_frame(&ctx, &mut app, vec![]);
}
assert!(app.ui.show_midi_editor, "the MIDI editor is still open");
assert_ne!(app.ui.docking.layout.panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_ui::docking::PanelState::Front);
assert_ne!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
app_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(body.center())]);
app.run("edit.select", json!({"clips": [clip_id.0]})).unwrap();
+9 -8
View File
@@ -15,14 +15,15 @@ fn harness() -> Harness<'static, SoundApp> {
let first = app.engine.session().tracks.first().map(|t| t.id.0).unwrap_or_default();
app.run("track.group", json!({"name": "Rhythm", "tracks": [first]})).unwrap();
app.engine.session_mut().edit.selected_tracks.clear();
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
h
}
+9 -8
View File
@@ -12,14 +12,15 @@ fn harness() -> Harness<'static, SoundApp> {
app.run("track.rename", json!({"track": first, "name": LONG_TRACK})).unwrap();
app.run("track.group", json!({"name": LONG_GROUP, "tracks": [first]})).unwrap();
app.engine.session_mut().edit.selected_tracks.clear();
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
h
}
@@ -15,14 +15,15 @@ fn strip_silence_dialog() -> (Harness<'static, SoundApp>, TrackId, Vec<(i64, i64
let before = app.engine.session().track(track).unwrap().clips().iter().map(|c| (c.start, c.end())).collect();
menus::invoke_menu(&mut app, "edit.strip_silence", "Edit > Strip Silence");
assert_eq!(app.dialogs.open_name(), Some("strip_silence"));
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
h.run_steps(3);
(h, track, before)
}
@@ -15,14 +15,15 @@ fn strip_silence_dialog() -> (Harness<'static, SoundApp>, TrackId) {
app.run("edit.select", json!({"tracks": [track.0], "start": 0, "end": end})).unwrap();
menus::invoke_menu(&mut app, "edit.strip_silence", "Edit > Strip Silence");
assert_eq!(app.dialogs.open_name(), Some("strip_silence"));
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,
);
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).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,
);
settle(&mut h);
(h, track)
}

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