diff --git a/CLAUDE.md b/CLAUDE.md index 750db80..f9ca98b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -83,6 +83,8 @@ Nothing to add in `rustortion-plugin/src/params.rs` — stage parameters are not (REV-7 remainder). - **NAM models** (`.nam`, WaveNet + LSTM via `nam-rs`) load from a user folder with rescan, into a process-global registry; stages resolve them **by name**. No rfd file-picker — rfd/gtk3 breaks CI. + The NAM tab (`rustortion-ui/src/components/nam_browser/`) is a view over the `StageConfig::Nam` + stages in the chain; there is no separate NAM slot, and the Amp tab shows each NAM stage as a link row. - **IR files** live in `impulse_responses/` and `~/.config/rustortion/impulse_responses/`; loading is async, off the RT thread. Keep convolver type configurable — FIR beat FFT on the Pi in real testing, and the TwoStage tail math is numerically wrong until REV-2 lands. diff --git a/Cargo.lock b/Cargo.lock index 6d2b38c..b74ca7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1927,19 +1927,6 @@ dependencies = [ "thiserror 2.0.18", ] -[[package]] -name = "iced_aw" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b7f923642b024c415150b70ef84ee5c11626e3b0af73b954d817d573bcd0a4" -dependencies = [ - "cfg-if", - "iced_core", - "iced_fonts", - "iced_widget", - "web-time", -] - [[package]] name = "iced_baseview" version = "0.1.0" @@ -1990,29 +1977,6 @@ dependencies = [ "log", ] -[[package]] -name = "iced_fonts" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214cff7c8499e328774216690e58e315a1a5f8f6fdd1035aed6298e62ffc4c1d" -dependencies = [ - "iced_core", - "iced_fonts_macros", - "iced_widget", -] - -[[package]] -name = "iced_fonts_macros" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef5125e110cb19cd1910a28298661c98c5d9ab02eef43594968352940e8752e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "ttf-parser", -] - [[package]] name = "iced_futures" version = "0.14.0" @@ -3902,7 +3866,6 @@ version = "0.3.0" dependencies = [ "anyhow", "iced", - "iced_aw", "log", "rustortion-core", "serde", diff --git a/rustortion-core/src/nam/info.rs b/rustortion-core/src/nam/info.rs index 1769d99..160dceb 100644 --- a/rustortion-core/src/nam/info.rs +++ b/rustortion-core/src/nam/info.rs @@ -331,7 +331,7 @@ mod tests { assert_eq!(info.includes_cab, None, "{name} must not read as a cab"); } // The dangerous class: names that mention a cab in order to say there - // isn't one. Reading these as "cab included" makes the card advise + // isn't one. Reading these as "cab included" makes the NAM tab advise // bypassing the IR, leaving the signal with no cab at all. Note that the // `-`/`_` normalization is what turns "cab-less" into a bare `cab` token, // so this is a trap the normalization itself creates. diff --git a/rustortion-core/src/nam/registry.rs b/rustortion-core/src/nam/registry.rs index ee23b9b..bde8474 100644 --- a/rustortion-core/src/nam/registry.rs +++ b/rustortion-core/src/nam/registry.rs @@ -78,3 +78,44 @@ pub fn available_names() -> Vec { names.sort(); names } + +/// Every registered model's key and native sample rate in Hz, sorted by key. +/// +/// One lock acquisition, so a GUI list needn't call [`get`] per row. +#[must_use] +pub fn catalog() -> Vec<(String, u32)> { + let map = store() + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut entries: Vec<(String, u32)> = map + .iter() + .map(|(name, model)| (name.clone(), model.expected_sample_rate() as u32)) + .collect(); + drop(map); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + entries +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Uses the same fixture dir as the NAM stage parity test, so the two tests + /// leave the process-global registry in the same state whichever runs first. + #[test] + fn catalog_lists_every_model_with_its_native_rate_sorted_by_key() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + let loader = NamLoader::new(&dir).expect("fixture dir loads"); + init_from_loader(&loader); + + let entries = catalog(); + + let names: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!(names, available_names()); + assert!(!entries.is_empty(), "fixture model must be listed"); + for (key, rate) in &entries { + let model = get(key).expect("listed model is registered"); + assert_eq!(*rate, model.expected_sample_rate() as u32); + } + } +} diff --git a/rustortion-plugin/src/editor.rs b/rustortion-plugin/src/editor.rs index 236e9a8..0cdcb7b 100644 --- a/rustortion-plugin/src/editor.rs +++ b/rustortion-plugin/src/editor.rs @@ -10,6 +10,7 @@ use crate::params::RustortionParams; use rustortion_ui::app::{SharedApp, UpdateResult}; use rustortion_ui::backend::ParamBackend; use rustortion_ui::components::ir_cabinet_control::IrCabinetControl; +use rustortion_ui::components::nam_browser::NamBrowser; use rustortion_ui::components::peak_meter::PeakMeterDisplay; use rustortion_ui::components::pitch_shift_control::PitchShiftControl; use rustortion_ui::handlers::hotkey::HotkeyHandler; @@ -150,7 +151,7 @@ impl iced_baseview::Application for PluginApp { let factory_presets = crate::factory::load_factory_presets(); let mut preset_handler = PresetHandler::new_from_presets(factory_presets); - // Seeded from the params rather than `default()`: the NAM card renders the IR + // Seeded from the params rather than `default()`: the NAM tab renders the IR // state as a coloured verdict about the signal chain, so a stale `false` here // means reopening a project with the IR bypassed shows a warning that the // audio contradicts — and the button offered to fix it would write the value @@ -210,6 +211,7 @@ impl iced_baseview::Application for PluginApp { input_filter_config: params.input_filters(), oversampling_factor, is_recording: false, + nam_browser: NamBrowser::default(), }; // If we have stored stages, restore them directly. diff --git a/rustortion-standalone/src/audio/manager.rs b/rustortion-standalone/src/audio/manager.rs index 938516a..1b0c472 100644 --- a/rustortion-standalone/src/audio/manager.rs +++ b/rustortion-standalone/src/audio/manager.rs @@ -30,9 +30,9 @@ pub struct Manager { xrun_count: Arc, available_irs: Vec, ir_load_handle: Option, - /// Live NAM models directory — the single source of truth the NAM stage - /// card displays and rescans. Updated whenever a rescan succeeds (from the - /// settings dialog or the stage card) so the displayed path never drifts. + /// Live NAM models directory — the single source of truth the NAM tab + /// displays and rescans. Updated whenever a rescan succeeds (from the + /// settings dialog or the NAM tab) so the displayed path never drifts. nam_dir: Mutex, } @@ -257,7 +257,7 @@ impl Manager { match load_nam_models(dir) { Ok(count) => { // Keep the live directory in sync so `nam_dir()` (the source of - // truth the NAM stage card displays/rescans) reflects the path + // truth the NAM tab displays/rescans) reflects the path // that was just scanned. if let Ok(mut d) = self.nam_dir.lock() { *d = dir.to_string(); diff --git a/rustortion-standalone/src/gui/app.rs b/rustortion-standalone/src/gui/app.rs index 8c1a08d..3060d9d 100644 --- a/rustortion-standalone/src/gui/app.rs +++ b/rustortion-standalone/src/gui/app.rs @@ -15,12 +15,15 @@ use crate::settings::Settings; use rustortion_ui::app::{SharedApp, UpdateResult}; use rustortion_ui::backend::ParamBackend; use rustortion_ui::components::ir_cabinet_control::IrCabinetControl; +use rustortion_ui::components::nam_browser::NamBrowser; use rustortion_ui::components::peak_meter::PeakMeterDisplay; use rustortion_ui::components::pitch_shift_control::PitchShiftControl; use rustortion_ui::handlers::hotkey::HotkeyHandler; use rustortion_ui::handlers::preset::PresetHandler; use rustortion_ui::i18n; -use rustortion_ui::messages::{HotkeyMessage, Message, MidiMessage, PresetMessage, TunerMessage}; +use rustortion_ui::messages::{ + HotkeyMessage, Message, MidiMessage, NamTabMessage, PresetMessage, TunerMessage, +}; use rustortion_ui::stages::StageType; use rustortion_ui::tabs::Tab; @@ -149,6 +152,7 @@ impl AmplifierApp { input_filter_config, oversampling_factor, is_recording: false, + nam_browser: NamBrowser::default(), }; Ok(Self { @@ -207,15 +211,7 @@ impl AmplifierApp { pub fn update(&mut self, message: Message) -> Task { // Detect messages that need standalone-side persistence *before* // shared handles them (because shared may consume the variant). - let needs_collapse_persist = matches!( - message, - Message::AddStage - | Message::RemoveStage(_) - | Message::MoveStageUp(_) - | Message::MoveStageDown(_) - | Message::ToggleStageCollapse(_) - | Message::ToggleAllStagesCollapse - ); + let needs_collapse_persist = needs_collapse_persist(&message); let ir_bypassed_value = match &message { Message::IrBypassed(b) => Some(*b), @@ -432,3 +428,50 @@ impl AmplifierApp { } } } + +const fn needs_collapse_persist(message: &Message) -> bool { + matches!( + message, + Message::AddStage + | Message::RemoveStage(_) + | Message::MoveStageUp(_) + | Message::MoveStageDown(_) + | Message::ToggleStageCollapse(_) + | Message::ToggleAllStagesCollapse + | Message::Nam(NamTabMessage::ModelClicked(_)) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chain_layout_changes_persist_the_collapsed_state() { + use rustortion_ui::messages::NamTabMessage; + for message in [ + Message::AddStage, + Message::RemoveStage(0), + Message::MoveStageUp(0), + Message::MoveStageDown(0), + Message::ToggleStageCollapse(0), + Message::ToggleAllStagesCollapse, + Message::Nam(NamTabMessage::ModelClicked("a".to_owned())), + ] { + assert!( + needs_collapse_persist(&message), + "{message:?} changes the chain layout" + ); + } + for message in [ + Message::Nam(NamTabMessage::FilterChanged("x".to_owned())), + Message::Nam(NamTabMessage::Rescan), + Message::RebuildTick, + ] { + assert!( + !needs_collapse_persist(&message), + "{message:?} does not change the chain layout" + ); + } + } +} diff --git a/rustortion-ui/Cargo.toml b/rustortion-ui/Cargo.toml index e6cdade..449bd40 100644 --- a/rustortion-ui/Cargo.toml +++ b/rustortion-ui/Cargo.toml @@ -5,7 +5,6 @@ edition = "2024" [dependencies] iced = { version = "0.14", features = ["tokio"] } -iced_aw = { version = "0.14.1", default-features = false, features = ["menu"] } rustortion-core = { path = "../rustortion-core" } serde = { version = "1.0", features = ["derive"] } anyhow = "1.0" diff --git a/rustortion-ui/src/app.rs b/rustortion-ui/src/app.rs index 3beb6f5..24d1e8b 100644 --- a/rustortion-ui/src/app.rs +++ b/rustortion-ui/src/app.rs @@ -8,6 +8,8 @@ use iced::{Alignment, Element, Length, Subscription, Task, keyboard, time, time: use crate::backend::{ExternalEvent, ParamBackend}; use crate::components::ir_cabinet_control::IrCabinetControl; use crate::components::minimap; +use crate::components::nam_browser::selection::ChainEdit; +use crate::components::nam_browser::{NamBrowser, NamViewContext}; use crate::components::peak_meter::PeakMeterDisplay; use crate::components::pitch_shift_control::PitchShiftControl; use crate::components::widgets::common::{ @@ -16,13 +18,16 @@ use crate::components::widgets::common::{ }; use crate::handlers::hotkey::HotkeyHandler; use crate::handlers::preset::PresetHandler; -use crate::messages::{HotkeyMessage, Message, PresetMessage}; +use crate::messages::{HotkeyMessage, Message, NamTabMessage, PresetMessage}; +use crate::stages::NamMessage; use crate::stages::{ - ParamUpdate, StageCategory, StageConfig, StageType, apply_stage_config, view_stage_config, + ParamUpdate, StageCategory, StageConfig, StageMessage, StageType, apply_stage_config, + view_stage_config, }; use crate::tabs::Tab; use crate::tr; use rustortion_core::amp::chain::DEFAULT_CHAIN_CAPACITY; +use rustortion_core::amp::stages::nam::NamConfig; use rustortion_core::preset::InputFilterConfig; const REBUILD_INTERVAL: Duration = Duration::from_millis(100); @@ -53,6 +58,7 @@ pub struct SharedApp { pub oversampling_factor: u32, /// Whether recording is active — set by standalone, displayed in header. pub is_recording: bool, + pub nam_browser: NamBrowser, } impl SharedApp { @@ -61,11 +67,18 @@ impl SharedApp { Message::TabSelected(tab) => { self.active_tab = tab; self.sync_stage_type_with_tab(tab); + // Pin the implicit "first NAM stage" so a later reorder can't change what is shown. + if tab == Tab::Nam + && let Some(idx) = self.nam_browser.focused_stage(&self.stages) + { + self.nam_browser.focus_stage(idx); + } } Message::SetStages(stages) => { self.collapsed_stages.resize(stages.len(), false); self.stages = stages; self.dirty_params.clear(); + self.nam_browser.chain_edited(ChainEdit::Replaced); self.update_processor_chain(); self.backend.persist_chain_state(&self.stages); } @@ -91,24 +104,14 @@ impl SharedApp { } Message::RebuildTick => self.flush_dirty_params(), Message::AddStage => { - // Cap the chain so the engine's stage list never has to grow on - // the RT thread. See `DEFAULT_CHAIN_CAPACITY`. - if self.stages.len() < DEFAULT_CHAIN_CAPACITY { - self.flush_dirty_params(); - let new_stage = StageConfig::from(self.selected_stage_type); - let category = new_stage.category(); - let insert_idx = self.category_end_index(category); - self.stages.insert(insert_idx, new_stage); - self.collapsed_stages.insert(insert_idx, false); - self.backend.add_stage(insert_idx, &self.stages[insert_idx]); - self.backend.persist_chain_state(&self.stages); - } + self.insert_stage(StageConfig::from(self.selected_stage_type)); } Message::RemoveStage(idx) => { if idx < self.stages.len() { self.flush_dirty_params(); self.stages.remove(idx); self.collapsed_stages.remove(idx); + self.nam_browser.chain_edited(ChainEdit::Removed(idx)); self.backend.remove_stage(idx); self.backend.persist_chain_state(&self.stages); } @@ -123,6 +126,7 @@ impl SharedApp { self.flush_dirty_params(); self.stages.swap(prev, idx); self.collapsed_stages.swap(prev, idx); + self.nam_browser.chain_edited(ChainEdit::Swapped(prev, idx)); self.backend.swap_stages(prev, idx); self.backend.persist_chain_state(&self.stages); } @@ -137,6 +141,7 @@ impl SharedApp { self.flush_dirty_params(); self.stages.swap(idx, next); self.collapsed_stages.swap(idx, next); + self.nam_browser.chain_edited(ChainEdit::Swapped(idx, next)); self.backend.swap_stages(idx, next); self.backend.persist_chain_state(&self.stages); } @@ -153,7 +158,7 @@ impl SharedApp { .stages .iter() .enumerate() - .filter(|(_, s)| s.category() == cat) + .filter(|(_, s)| s.category() == cat && !matches!(s, StageConfig::Nam(_))) .map(|(i, _)| i) .collect(); @@ -214,36 +219,11 @@ impl SharedApp { self.backend.rebuild_stage(idx, &self.stages[idx]); self.backend.persist_chain_state(&self.stages); } - Some(ParamUpdate::RescanNamModels) => { - // The pick-list refreshes automatically because the NAM - // view reads `registry::available_names()` live. - match self.backend.rescan_nam_models() { - Ok(count) => { - log::info!("Rescanned NAM models: {count} found"); - // Rescan replaces the global registry, but already-built - // NamStage instances own their loaded model — rebuild the - // live NAM stages so an in-place `.nam` edit takes effect - // immediately (and re-selecting the same name still works). - for idx in 0..self.stages.len() { - if self.stages[idx].stage_type() == StageType::Nam { - self.backend.rebuild_stage(idx, &self.stages[idx]); - } - } - } - Err(e) => log::error!("Failed to rescan NAM models: {e}"), - } - } - Some(ParamUpdate::OpenNamModelsDir) => { - if let Some(dir) = self.backend.nam_models_dir() { - crate::platform::open_directory(&dir); - } else { - log::warn!("No NAM models directory to open"); - } - } None => {} } } } + Message::Nam(msg) => self.handle_nam(msg), Message::Hotkey(msg) => return self.handle_hotkey(msg), Message::KeyPressed(key, modifiers) => { return self.handle_key_pressed(&key, modifiers); @@ -279,6 +259,82 @@ impl SharedApp { UpdateResult::Handled(Task::none()) } + fn handle_nam(&mut self, msg: NamTabMessage) { + match msg { + NamTabMessage::FilterChanged(filter) => self.nam_browser.set_filter(filter), + NamTabMessage::FolderToggled(path) => self.nam_browser.toggle_folder(path), + NamTabMessage::StageFocused(idx) => self.nam_browser.focus_stage(idx), + NamTabMessage::OpenStage(idx) => { + self.nam_browser.focus_stage(idx); + self.active_tab = Tab::Nam; + } + NamTabMessage::ModelClicked(key) => self.load_model(key), + NamTabMessage::Rescan => { + // The browser reads the registry live each frame, so only the + // already-built stages need refreshing. + match self.backend.rescan_nam_models() { + Ok(count) => { + log::info!("Rescanned NAM models: {count} found"); + // Built NamStages own their model: rebuild them so an + // in-place `.nam` edit takes effect. + for idx in 0..self.stages.len() { + if self.stages[idx].stage_type() == StageType::Nam { + self.backend.rebuild_stage(idx, &self.stages[idx]); + } + } + } + Err(e) => log::error!("Failed to rescan NAM models: {e}"), + } + } + NamTabMessage::OpenFolder => { + if let Some(dir) = self.backend.nam_models_dir() { + crate::platform::open_directory(&dir); + } else { + log::warn!("No NAM models directory to open"); + } + } + } + } + + /// Load `key` into the selected NAM stage, or add a NAM stage holding it. + fn load_model(&mut self, key: String) { + if let Some(idx) = self.nam_browser.focused_stage(&self.stages) { + let already_loaded = matches!( + &self.stages[idx], + StageConfig::Nam(cfg) if cfg.model_name.as_deref() == Some(key.as_str()) + ); + if !already_loaded { + self.update(Message::Stage( + idx, + StageMessage::Nam(NamMessage::ModelSelected(key)), + )); + } + } else if let Some(idx) = self.insert_stage(StageConfig::Nam(NamConfig { + model_name: Some(key), + ..NamConfig::default() + })) { + self.nam_browser.focus_stage(idx); + } + } + + /// Insert `stage` at the end of its category and tell the backend. Returns its + /// index, or `None` when the chain is full. + fn insert_stage(&mut self, stage: StageConfig) -> Option { + // Cap the chain so the engine's stage list never has to grow on the RT + // thread. See `DEFAULT_CHAIN_CAPACITY`. + if self.stages.len() >= DEFAULT_CHAIN_CAPACITY { + return None; + } + self.flush_dirty_params(); + let idx = self.category_end_index(stage.category()); + self.stages.insert(idx, stage); + self.collapsed_stages.insert(idx, false); + self.nam_browser.chain_edited(ChainEdit::Inserted(idx)); + self.backend.add_stage(idx, &self.stages[idx]); + self.backend.persist_chain_state(&self.stages); + Some(idx) + } + fn handle_hotkey(&mut self, msg: HotkeyMessage) -> UpdateResult { if matches!(msg, HotkeyMessage::Open) { let presets = self.preset_handler.get_available_presets().to_vec(); @@ -324,6 +380,7 @@ impl SharedApp { Tab::Effects => self.view_effects_tab(), Tab::Cabinet => self.view_cabinet_tab(), Tab::Io => self.view_io_tab(), + Tab::Nam => self.view_nam_tab(), }; let signal_minimap = minimap::view(&self.stages, &self.input_filter_config, self.active_tab); @@ -410,6 +467,7 @@ impl SharedApp { let tabs = [ (Tab::Io, tr!(tab_io)), (Tab::Amp, tr!(tab_amp)), + (Tab::Nam, tr!(tab_nam)), (Tab::Effects, tr!(tab_effects)), (Tab::Cabinet, tr!(tab_cabinet)), ]; @@ -470,15 +528,6 @@ impl SharedApp { can_move_up, can_move_down, bypassed, - // Effective rate (device × oversampling) — the rate stages are - // built at, so NAM's mismatch check compares against the right value. - engine_sample_rate: self.backend.sample_rate() - * self.backend.oversampling_factor(), - // NAM-specific: where the NAM stage card shows users to drop models. - nam_models_dir: self.backend.nam_models_dir(), - // NAM-specific: lets a cab-inclusive model report whether the IR - // after it is a second cab or already bypassed. - ir_bypassed: self.ir_cabinet_control.is_bypassed(), }, )); } @@ -496,13 +545,16 @@ impl SharedApp { } fn view_collapse_toggle(&self, category: StageCategory) -> Element<'_, Message> { - let category_has_stages = self.stages.iter().any(|s| s.category() == category); + let category_has_stages = self + .stages + .iter() + .any(|s| s.category() == category && !matches!(s, StageConfig::Nam(_))); let all_collapsed = category_has_stages && self .stages .iter() .enumerate() - .filter(|(_, s)| s.category() == category) + .filter(|(_, s)| s.category() == category && !matches!(s, StageConfig::Nam(_))) .all(|(i, _)| self.collapsed_stages.get(i).copied().unwrap_or(false)); let label = if all_collapsed { @@ -538,6 +590,17 @@ impl SharedApp { .into() } + fn view_nam_tab(&self) -> Element<'_, Message> { + let ctx = NamViewContext { + stages: &self.stages, + engine_sample_rate: self.backend.sample_rate() * self.backend.oversampling_factor(), + models_dir: self.backend.nam_models_dir(), + ir_bypassed: self.ir_cabinet_control.is_bypassed(), + chain_full: self.stages.len() >= DEFAULT_CHAIN_CAPACITY, + }; + view_tab_panel(self.nam_browser.view(&ctx)) + } + fn view_cabinet_tab(&self) -> Element<'_, Message> { let content = scrollable( column![self.ir_cabinet_control.view()] @@ -776,3 +839,314 @@ pub fn tab_button_inactive( ..iced::widget::button::Style::default() } } + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use rustortion_core::amp::stages::nam::NamConfig; + + use super::*; + use crate::backend::Capabilities; + use crate::components::nam_browser::NamBrowser; + use crate::hotkey::HotkeySettings; + use crate::messages::NamTabMessage; + + #[derive(Debug, Clone, PartialEq)] + enum Call { + AddStage(usize), + RemoveStage(usize), + RebuildStage(usize), + SetParameter(usize, &'static str), + Rescan, + } + + struct MockBackend { + calls: Mutex>, + capabilities: Capabilities, + } + + impl MockBackend { + fn record(&self, call: Call) { + self.calls.lock().unwrap().push(call); + } + } + + impl ParamBackend for MockBackend { + fn set_parameter(&self, stage_idx: usize, name: &'static str, _value: f32) { + self.record(Call::SetParameter(stage_idx, name)); + } + fn rebuild_stage(&self, stage_idx: usize, _config: &StageConfig) { + self.record(Call::RebuildStage(stage_idx)); + } + fn set_amp_chain(&self, _stages: &[StageConfig]) {} + fn set_bypass(&self, _stage_idx: usize, _bypassed: bool) {} + fn add_stage(&self, idx: usize, _config: &StageConfig) { + self.record(Call::AddStage(idx)); + } + fn remove_stage(&self, idx: usize) { + self.record(Call::RemoveStage(idx)); + } + fn swap_stages(&self, _a: usize, _b: usize) {} + fn set_ir(&self, _path: &str) {} + fn set_ir_bypass(&self, _bypassed: bool) {} + fn set_ir_gain(&self, _gain: f32) {} + fn set_input_filter(&self, _filter: &InputFilterConfig) {} + fn set_pitch_shift(&self, _semitones: i32) {} + fn set_oversampling(&self, _factor: u32) {} + fn sample_rate(&self) -> u32 { + 48_000 + } + fn oversampling_factor(&self) -> u32 { + 1 + } + fn capabilities(&self) -> &Capabilities { + &self.capabilities + } + fn get_available_irs(&self) -> Vec { + Vec::new() + } + fn get_peak_meter_info(&self) -> Option { + None + } + fn nam_models_dir(&self) -> Option { + None + } + fn rescan_nam_models(&self) -> Result { + self.record(Call::Rescan); + Ok(0) + } + } + + fn app(stages: Vec) -> SharedApp { + SharedApp { + backend: MockBackend { + calls: Mutex::new(Vec::new()), + capabilities: Capabilities::plugin(), + }, + collapsed_stages: vec![false; stages.len()], + stages, + dirty_params: HashMap::new(), + active_tab: Tab::default(), + selected_stage_type: StageType::default(), + ir_cabinet_control: IrCabinetControl::default(), + pitch_shift_control: PitchShiftControl::new(0), + preset_handler: PresetHandler::new_from_presets(Vec::new()), + peak_meter_display: PeakMeterDisplay::default(), + hotkey_handler: HotkeyHandler::new(HotkeySettings::default()), + input_filter_config: InputFilterConfig::default(), + oversampling_factor: 1, + is_recording: false, + nam_browser: NamBrowser::default(), + } + } + + fn calls(app: &SharedApp) -> Vec { + app.backend.calls.lock().unwrap().clone() + } + + fn nam(model: Option<&str>) -> StageConfig { + StageConfig::Nam(NamConfig { + model_name: model.map(str::to_owned), + ..NamConfig::default() + }) + } + + fn stage(kind: StageType) -> StageConfig { + StageConfig::from(kind) + } + + fn click(app: &mut SharedApp, key: &str) { + app.update(Message::Nam(NamTabMessage::ModelClicked(key.to_owned()))); + } + + fn model_at(app: &SharedApp, idx: usize) -> Option<&str> { + match &app.stages[idx] { + StageConfig::Nam(cfg) => cfg.model_name.as_deref(), + other => panic!("stage {idx} is {:?}, not NAM", other.stage_type()), + } + } + + #[test] + fn clicking_a_model_with_no_nam_stage_inserts_one_after_the_amp_stages() { + let mut app = app(vec![ + stage(StageType::NoiseGate), + stage(StageType::Level), + stage(StageType::Delay), + ]); + app.collapsed_stages = vec![true, false, true]; + click(&mut app, "Pack/model"); + assert_eq!(app.stages.len(), 4); + assert_eq!(model_at(&app, 2), Some("Pack/model")); + assert_eq!(app.stages[3].stage_type(), StageType::Delay); + assert_eq!(app.collapsed_stages, [true, false, false, true]); + assert_eq!(calls(&app), [Call::AddStage(2)]); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(2)); + } + + #[test] + fn clicking_a_model_swaps_the_selected_stages_model() { + let mut app = app(vec![nam(None)]); + click(&mut app, "a"); + assert_eq!(app.stages.len(), 1); + assert_eq!(model_at(&app, 0), Some("a")); + assert_eq!(calls(&app), [Call::RebuildStage(0)]); + } + + #[test] + fn collapse_all_ignores_nam_rows() { + let mut app = app(vec![stage(StageType::Level), nam(Some("a"))]); + app.collapsed_stages = vec![true, false]; + app.update(Message::ToggleAllStagesCollapse); + assert!( + !app.collapsed_stages[0], + "the only real card was collapsed, so the toggle expands it" + ); + } + + #[test] + fn clicking_the_loaded_model_does_nothing() { + let mut app = app(vec![nam(Some("a"))]); + click(&mut app, "a"); + assert!(calls(&app).is_empty()); + } + + #[test] + fn clicking_a_model_loads_into_the_selected_stage_when_there_are_two() { + let mut app = app(vec![nam(Some("a")), nam(Some("b"))]); + app.update(Message::Nam(NamTabMessage::StageFocused(1))); + click(&mut app, "c"); + assert_eq!(model_at(&app, 0), Some("a")); + assert_eq!(model_at(&app, 1), Some("c")); + } + + #[test] + fn clicking_a_model_on_a_full_chain_with_no_nam_stage_does_nothing() { + let mut app = app(vec![stage(StageType::Level); DEFAULT_CHAIN_CAPACITY]); + click(&mut app, "a"); + assert_eq!(app.stages.len(), DEFAULT_CHAIN_CAPACITY); + assert!( + app.stages + .iter() + .all(|s| s.stage_type() == StageType::Level) + ); + assert!(calls(&app).is_empty()); + assert_eq!(app.collapsed_stages.len(), DEFAULT_CHAIN_CAPACITY); + assert_eq!(app.nam_browser.focused_stage(&app.stages), None); + } + + #[test] + fn a_pending_slider_edit_is_sent_before_the_insert_shifts_indices() { + let mut app = app(vec![stage(StageType::Level), stage(StageType::Delay)]); + app.dirty_params.insert((1, "feedback"), 0.5); + click(&mut app, "a"); + assert_eq!( + calls(&app), + [Call::SetParameter(1, "feedback"), Call::AddStage(1)] + ); + assert!(app.dirty_params.is_empty()); + } + + #[test] + fn removing_the_selected_nam_stage_selects_the_first_remaining_one() { + let mut app = app(vec![ + nam(Some("a")), + stage(StageType::Level), + nam(Some("b")), + ]); + app.update(Message::Nam(NamTabMessage::StageFocused(2))); + app.update(Message::RemoveStage(2)); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(0)); + } + + #[test] + fn removing_an_earlier_stage_keeps_the_same_nam_stage_selected() { + let mut app = app(vec![ + stage(StageType::Level), + nam(Some("a")), + nam(Some("b")), + ]); + app.update(Message::Nam(NamTabMessage::StageFocused(2))); + app.update(Message::RemoveStage(0)); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(1)); + assert_eq!(model_at(&app, 1), Some("b")); + } + + #[test] + fn moving_the_selected_nam_stage_keeps_it_selected() { + let mut app = app(vec![nam(Some("a")), nam(Some("b"))]); + app.update(Message::Nam(NamTabMessage::StageFocused(1))); + app.update(Message::MoveStageUp(1)); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(0)); + assert_eq!(model_at(&app, 0), Some("b")); + } + + #[test] + fn the_stage_shown_when_the_nam_tab_opens_stays_shown_after_a_reorder() { + let mut app = app(vec![nam(Some("a")), nam(Some("b"))]); + app.update(Message::TabSelected(Tab::Nam)); + app.update(Message::TabSelected(Tab::Amp)); + app.update(Message::MoveStageUp(1)); + let shown = app + .nam_browser + .focused_stage(&app.stages) + .expect("a NAM stage is selected"); + assert_eq!(model_at(&app, shown), Some("a")); + } + + #[test] + fn moving_the_selected_nam_stage_down_keeps_it_selected() { + let mut app = app(vec![nam(Some("a")), nam(Some("b"))]); + app.update(Message::Nam(NamTabMessage::StageFocused(0))); + app.update(Message::MoveStageDown(0)); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(1)); + assert_eq!(model_at(&app, 1), Some("a")); + } + + #[test] + fn loading_a_preset_selects_its_first_nam_stage() { + let mut app = app(vec![ + stage(StageType::Level), + stage(StageType::Level), + nam(Some("a")), + ]); + app.update(Message::Nam(NamTabMessage::StageFocused(2))); + app.update(Message::SetStages(vec![ + stage(StageType::Level), + nam(Some("c")), + nam(Some("d")), + ])); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(1)); + } + + #[test] + fn open_stage_selects_it_and_switches_to_the_nam_tab() { + let mut app = app(vec![nam(Some("a")), nam(Some("b"))]); + app.update(Message::Nam(NamTabMessage::OpenStage(1))); + assert_eq!(app.active_tab, Tab::Nam); + assert_eq!(app.nam_browser.focused_stage(&app.stages), Some(1)); + } + + #[test] + fn rescan_works_with_no_nam_stage_and_rebuilds_the_live_ones() { + let mut empty = app(Vec::new()); + empty.update(Message::Nam(NamTabMessage::Rescan)); + assert_eq!(calls(&empty), [Call::Rescan]); + + let mut two = app(vec![nam(Some("a")), stage(StageType::Level), nam(None)]); + two.update(Message::Nam(NamTabMessage::Rescan)); + assert_eq!( + calls(&two), + [Call::Rescan, Call::RebuildStage(0), Call::RebuildStage(2)] + ); + } + + #[test] + fn add_stage_still_adds_an_empty_nam_stage_from_the_amp_tab() { + let mut app = app(vec![stage(StageType::Level)]); + app.update(Message::StageTypeSelected(StageType::Nam)); + app.update(Message::AddStage); + assert_eq!(model_at(&app, 1), None); + assert_eq!(calls(&app), [Call::AddStage(1)]); + } +} diff --git a/rustortion-ui/src/components/minimap.rs b/rustortion-ui/src/components/minimap.rs index 296f3f3..ff82e01 100644 --- a/rustortion-ui/src/components/minimap.rs +++ b/rustortion-ui/src/components/minimap.rs @@ -1,9 +1,9 @@ use iced::widget::{button, container, row, text}; use iced::{Alignment, Element, Length}; -use crate::messages::Message; -use crate::stages::{StageCategory, StageConfig}; -use crate::tabs::Tab; +use crate::messages::{Message, NamTabMessage}; +use crate::stages::StageConfig; +use crate::tabs::{Tab, tab_for_stage}; use rustortion_core::preset::InputFilterConfig; const fn stage_abbreviation(cfg: &StageConfig) -> &'static str { @@ -127,19 +127,21 @@ pub fn view<'a>( ); // Stage blocks - for stage in stages { + for (idx, stage) in stages.iter().enumerate() { chain = chain.push(text("\u{2192}").size(11)); let abbr = stage_abbreviation(stage); - let cat = stage.category(); - let tab = match cat { - StageCategory::Amp => Tab::Amp, - StageCategory::Effect => Tab::Effects, - }; + let tab = tab_for_stage(stage); let is_active = active_tab == tab; let bypassed = stage.bypassed(); + // A NAM block opens its own stage; the rest just switch tabs. + let on_press = if matches!(stage, StageConfig::Nam(_)) { + Message::Nam(NamTabMessage::OpenStage(idx)) + } else { + Message::TabSelected(tab) + }; chain = chain.push( button(text(abbr).size(11)) - .on_press(Message::TabSelected(tab)) + .on_press(on_press) .style(block_style(is_active, bypassed)) .padding([2, 6]), ); diff --git a/rustortion-ui/src/components/mod.rs b/rustortion-ui/src/components/mod.rs index 35110d1..feaf6e6 100644 --- a/rustortion-ui/src/components/mod.rs +++ b/rustortion-ui/src/components/mod.rs @@ -2,6 +2,7 @@ pub mod dialogs; pub mod input_filter_control; pub mod ir_cabinet_control; pub mod minimap; +pub mod nam_browser; pub mod peak_meter; pub mod pitch_shift_control; pub mod preset_bar; diff --git a/rustortion-ui/src/components/nam_browser/mod.rs b/rustortion-ui/src/components/nam_browser/mod.rs new file mode 100644 index 0000000..ee62bb9 --- /dev/null +++ b/rustortion-ui/src/components/nam_browser/mod.rs @@ -0,0 +1,95 @@ +use std::collections::HashSet; + +use crate::stages::StageConfig; +use selection::ChainEdit; + +pub mod selection; +pub mod tree; +mod view; + +pub use view::NamViewContext; + +#[derive(Debug, Default)] +pub struct NamBrowser { + filter: String, + open_folders: HashSet, + focus: Option, +} + +impl NamBrowser { + pub fn set_filter(&mut self, filter: String) { + self.filter = filter; + } + + /// Opens a closed folder, closes an open one. + pub fn toggle_folder(&mut self, path: String) { + if !self.open_folders.remove(&path) { + self.open_folders.insert(path); + } + } + + pub const fn focus_stage(&mut self, idx: usize) { + self.focus = Some(idx); + } + + /// Call after every edit to `SharedApp::stages`. + pub fn chain_edited(&mut self, edit: ChainEdit) { + self.focus = selection::focus_after(self.focus, edit); + } + + /// The selected NAM stage's chain index, resolved against the live chain. + pub fn focused_stage(&self, stages: &[StageConfig]) -> Option { + selection::resolve_focus(self.focus, stages) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::stages::{StageConfig, StageType}; + use rustortion_core::amp::stages::nam::NamConfig; + + #[test] + fn browser_keeps_its_selection_on_the_same_stage() { + use selection::ChainEdit; + let nam = |m: &str| { + StageConfig::Nam(NamConfig { + model_name: Some(m.to_owned()), + ..NamConfig::default() + }) + }; + let level = || StageConfig::from(StageType::Level); + + let mut browser = NamBrowser::default(); + let mut chain = vec![level(), nam("a"), nam("b")]; + assert_eq!( + browser.focused_stage(&chain), + Some(1), + "defaults to the first NAM stage" + ); + + browser.focus_stage(2); + chain.remove(0); + browser.chain_edited(ChainEdit::Removed(0)); + assert_eq!( + browser.focused_stage(&chain), + Some(1), + "still the stage holding b" + ); + + chain.remove(1); + browser.chain_edited(ChainEdit::Removed(1)); + assert_eq!( + browser.focused_stage(&chain), + Some(0), + "falls to the first remaining NAM stage" + ); + + browser.toggle_folder("Pack".into()); + browser.toggle_folder("Pack".into()); + assert!( + browser.open_folders.is_empty(), + "toggling twice closes it again" + ); + } +} diff --git a/rustortion-ui/src/components/nam_browser/selection.rs b/rustortion-ui/src/components/nam_browser/selection.rs new file mode 100644 index 0000000..0e296c1 --- /dev/null +++ b/rustortion-ui/src/components/nam_browser/selection.rs @@ -0,0 +1,177 @@ +//! Pure selection logic for the NAM tab: which NAM stage is focused and what the pane shows. + +use crate::stages::StageConfig; + +/// Chain indices of every NAM stage, in chain order. +pub fn nam_stage_indices(stages: &[StageConfig]) -> Vec { + stages + .iter() + .enumerate() + .filter_map(|(i, s)| matches!(s, StageConfig::Nam(_)).then_some(i)) + .collect() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChainEdit { + Inserted(usize), + Removed(usize), + Swapped(usize, usize), + Replaced, +} + +/// Index arithmetic only: where a selected chain index lands after `edit`. +/// `Removed(i)` of the selected stage and `Replaced` both give `None`. +pub fn focus_after(focus: Option, edit: ChainEdit) -> Option { + let f = focus?; + match edit { + ChainEdit::Inserted(at) => Some(if at <= f { f + 1 } else { f }), + ChainEdit::Removed(at) if at == f => None, + ChainEdit::Removed(at) => Some(if at < f { f - 1 } else { f }), + ChainEdit::Swapped(a, b) if f == a => Some(b), + ChainEdit::Swapped(a, b) if f == b => Some(a), + ChainEdit::Swapped(..) => Some(f), + ChainEdit::Replaced => None, + } +} + +/// `focus` if it names a NAM stage, otherwise the first NAM stage, otherwise `None`. +pub fn resolve_focus(focus: Option, stages: &[StageConfig]) -> Option { + focus + .filter(|&i| matches!(stages.get(i), Some(StageConfig::Nam(_)))) + .or_else(|| nam_stage_indices(stages).first().copied()) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PaneState { + /// No NAM stage in the chain. + NoStage, + /// A NAM stage with no model chosen. + Empty { + idx: usize, + }, + Loaded { + idx: usize, + key: String, + }, + /// The stage names a model the registry does not have. + Missing { + idx: usize, + key: String, + }, +} + +pub fn pane_state( + stages: &[StageConfig], + focus: Option, + is_registered: impl Fn(&str) -> bool, +) -> PaneState { + let Some(idx) = resolve_focus(focus, stages) else { + return PaneState::NoStage; + }; + let Some(StageConfig::Nam(cfg)) = stages.get(idx) else { + return PaneState::NoStage; + }; + match &cfg.model_name { + None => PaneState::Empty { idx }, + Some(key) if is_registered(key) => PaneState::Loaded { + idx, + key: key.clone(), + }, + Some(key) => PaneState::Missing { + idx, + key: key.clone(), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::stages::{StageConfig, StageType}; + use rustortion_core::amp::stages::nam::NamConfig; + + fn nam(model: Option<&str>) -> StageConfig { + StageConfig::Nam(NamConfig { + model_name: model.map(str::to_owned), + ..NamConfig::default() + }) + } + fn level() -> StageConfig { + StageConfig::from(StageType::Level) + } + + #[test] + fn nam_stage_indices_are_in_chain_order() { + assert_eq!( + nam_stage_indices(&[level(), nam(None), level(), nam(Some("a"))]), + [1, 3] + ); + assert!(nam_stage_indices(&[level()]).is_empty()); + } + + #[test] + fn focus_follows_its_stage_through_edits() { + assert_eq!(focus_after(Some(3), ChainEdit::Removed(0)), Some(2)); + assert_eq!(focus_after(Some(3), ChainEdit::Removed(5)), Some(3)); + assert_eq!(focus_after(Some(3), ChainEdit::Removed(3)), None); + assert_eq!(focus_after(Some(3), ChainEdit::Inserted(3)), Some(4)); + assert_eq!(focus_after(Some(3), ChainEdit::Inserted(4)), Some(3)); + assert_eq!(focus_after(Some(1), ChainEdit::Swapped(0, 1)), Some(0)); + assert_eq!(focus_after(Some(0), ChainEdit::Swapped(0, 1)), Some(1)); + assert_eq!(focus_after(Some(2), ChainEdit::Swapped(0, 1)), Some(2)); + assert_eq!(focus_after(Some(2), ChainEdit::Replaced), None); + assert_eq!(focus_after(None, ChainEdit::Removed(0)), None); + } + + #[test] + fn a_stale_or_missing_focus_resolves_to_the_first_nam_stage() { + let chain = [level(), nam(Some("a")), nam(Some("b"))]; + assert_eq!(resolve_focus(Some(2), &chain), Some(2)); + assert_eq!(resolve_focus(None, &chain), Some(1)); + assert_eq!( + resolve_focus(Some(0), &chain), + Some(1), + "index 0 is not a NAM stage" + ); + assert_eq!( + resolve_focus(Some(99), &chain), + Some(1), + "out of range must not panic" + ); + assert_eq!(resolve_focus(Some(0), &[level()]), None); + assert_eq!(resolve_focus(None, &[]), None); + } + + #[test] + fn pane_state_covers_the_four_states() { + let known = |key: &str| key == "a"; + assert_eq!(pane_state(&[level()], None, known), PaneState::NoStage); + assert_eq!( + pane_state(&[level(), nam(None)], None, known), + PaneState::Empty { idx: 1 } + ); + assert_eq!( + pane_state(&[nam(Some("a"))], None, known), + PaneState::Loaded { + idx: 0, + key: "a".into() + } + ); + assert_eq!( + pane_state(&[nam(Some("gone"))], None, known), + PaneState::Missing { + idx: 0, + key: "gone".into() + } + ); + } + + #[test] + fn pane_state_follows_the_selected_stage_not_the_first() { + let chain = [nam(Some("a")), nam(None)]; + assert_eq!( + pane_state(&chain, Some(1), |_| true), + PaneState::Empty { idx: 1 } + ); + } +} diff --git a/rustortion-ui/src/components/nam_browser/tree.rs b/rustortion-ui/src/components/nam_browser/tree.rs new file mode 100644 index 0000000..fcf2114 --- /dev/null +++ b/rustortion-ui/src/components/nam_browser/tree.rs @@ -0,0 +1,345 @@ +//! Pure list logic for the NAM browser: the folder tree, the filter, and visible rows. + +use std::collections::HashSet; +use std::hash::BuildHasher; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ModelNode { + /// `path` is the folder's full path from the root, e.g. "Pack/Deep". + Folder { + label: String, + path: String, + children: Vec, + }, + /// `key` is the full registry key; `label` its last segment. + Model { + label: String, + key: String, + rate_hz: u32, + }, +} + +impl ModelNode { + fn label(&self) -> &str { + match self { + Self::Folder { label, .. } | Self::Model { label, .. } => label, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ListRow { + Folder { + depth: usize, + label: String, + path: String, + open: bool, + }, + /// `folder` is set only while filtering, so the flat list can show where a match lives. + Model { + depth: usize, + label: String, + key: String, + folder: Option, + rate_hz: u32, + }, +} + +/// The last path segment of a registry key. +pub fn leaf_label(key: &str) -> &str { + key.rsplit('/').next().unwrap_or(key) +} + +/// Everything before the last '/', or `None` for a loose file. +pub fn folder_of(key: &str) -> Option<&str> { + key.rsplit_once('/').map(|(folder, _)| folder) +} + +/// Group registry keys into a folder tree. Folders and loose files sort together +/// by name, ignoring case, at every level. +pub fn model_tree(entries: &[(String, u32)]) -> Vec { + let mut root = Vec::new(); + for (key, rate_hz) in entries { + let mut segments = key.split('/').peekable(); + let mut level = &mut root; + let mut path = String::new(); + let mut depth = 0; + while let Some(segment) = segments.next() { + if segments.peek().is_none() { + level.push(ModelNode::Model { + label: segment.to_owned(), + key: key.clone(), + rate_hz: *rate_hz, + }); + break; + } + if depth > 0 { + path.push('/'); + } + path.push_str(segment); + depth += 1; + let position = level + .iter() + .position(|node| matches!(node, ModelNode::Folder { path: p, .. } if *p == path)) + .unwrap_or_else(|| { + level.push(ModelNode::Folder { + label: segment.to_owned(), + path: path.clone(), + children: Vec::new(), + }); + level.len() - 1 + }); + let ModelNode::Folder { children, .. } = &mut level[position] else { + unreachable!("position was found by matching a Folder"); + }; + level = children; + } + } + sort_tree(&mut root); + root +} + +fn sort_tree(nodes: &mut [ModelNode]) { + nodes.sort_by_cached_key(|node| node.label().to_lowercase()); + for node in nodes { + if let ModelNode::Folder { children, .. } = node { + sort_tree(children); + } + } +} + +/// Case-insensitive substring match on the full key. `filter` is matched literally. +pub fn matches_filter(key: &str, filter: &str) -> bool { + key.to_lowercase().contains(&filter.to_lowercase()) +} + +/// The rows to draw: the tree honouring open folders, or a flat list of matches +/// while a filter is set. +pub fn visible_rows( + tree: &[ModelNode], + filter: &str, + open_folders: &HashSet, + loaded: Option<&str>, +) -> Vec { + let filter = filter.trim(); + let mut rows = Vec::new(); + if filter.is_empty() { + push_tree(tree, 0, open_folders, loaded, &mut rows); + } else { + push_matches(tree, filter, &mut rows); + } + rows +} + +fn push_tree( + nodes: &[ModelNode], + depth: usize, + open_folders: &HashSet, + loaded: Option<&str>, + rows: &mut Vec, +) { + for node in nodes { + match node { + ModelNode::Folder { + label, + path, + children, + } => { + let open = open_folders.contains(path) + || loaded.is_some_and(|key| { + key.strip_prefix(path.as_str()) + .is_some_and(|rest| rest.starts_with('/')) + }); + rows.push(ListRow::Folder { + depth, + label: label.clone(), + path: path.clone(), + open, + }); + if open { + push_tree(children, depth + 1, open_folders, loaded, rows); + } + } + ModelNode::Model { + label, + key, + rate_hz, + } => rows.push(ListRow::Model { + depth, + label: label.clone(), + key: key.clone(), + folder: None, + rate_hz: *rate_hz, + }), + } + } +} + +fn push_matches(nodes: &[ModelNode], filter: &str, rows: &mut Vec) { + for node in nodes { + match node { + ModelNode::Folder { children, .. } => push_matches(children, filter, rows), + ModelNode::Model { + label, + key, + rate_hz, + } => { + if matches_filter(key, filter) { + rows.push(ListRow::Model { + depth: 0, + label: label.clone(), + key: key.clone(), + folder: folder_of(key).map(str::to_owned), + rate_hz: *rate_hz, + }); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entries(keys: &[&str]) -> Vec<(String, u32)> { + keys.iter().map(|k| ((*k).to_owned(), 48_000)).collect() + } + fn labels(rows: &[ListRow]) -> Vec<&str> { + rows.iter() + .map(|r| match r { + ListRow::Folder { label, .. } | ListRow::Model { label, .. } => label.as_str(), + }) + .collect() + } + + #[test] + fn model_tree_groups_keys_by_folder_and_sorts_ignoring_case() { + let tree = model_tree(&entries(&[ + "Pack/Deep/leaf", + "Pack/inner", + "alpha", + "Zeta/one", + "beta", + "Pack", + ])); + let top: Vec<&str> = tree.iter().map(ModelNode::label).collect(); + assert_eq!(top, ["alpha", "beta", "Pack", "Pack", "Zeta"]); + let ModelNode::Folder { path, children, .. } = &tree[2] else { + panic!("expected the Pack folder") + }; + assert_eq!(path, "Pack"); + let ModelNode::Folder { + path: deep, + children: deep_children, + .. + } = &children[0] + else { + panic!("expected Deep") + }; + assert_eq!(deep, "Pack/Deep"); + assert_eq!( + deep_children[0], + ModelNode::Model { + label: "leaf".into(), + key: "Pack/Deep/leaf".into(), + rate_hz: 48_000 + } + ); + } + + #[test] + fn leaf_label_and_folder_of_split_a_key() { + assert_eq!(leaf_label("Pack/Deep/leaf"), "leaf"); + assert_eq!(leaf_label("alpha"), "alpha"); + assert_eq!(folder_of("Pack/Deep/leaf"), Some("Pack/Deep")); + assert_eq!(folder_of("alpha"), None); + } + + #[test] + fn filter_is_a_literal_case_insensitive_substring() { + assert!(matches_filter( + "S-[AMP] 020W BOLD CLEAN Clean-Blues #01 (Factory)", + "[amp]" + )); + assert!(matches_filter( + "S-[AMP] 020W BOLD CLEAN Clean-Blues #01 (Factory)", + "#01 (" + )); + assert!(matches_filter("Boosted-6505+-A2-Chugs-FullRig", "6505+")); + assert!(matches_filter("Pack/Deluxe Reverb", "pack/del")); + assert!(matches_filter("合集/失真 高增益", "高增益")); + assert!(!matches_filter("Deluxe Reverb", ".*")); + assert!(!matches_filter("Deluxe Reverb", "bassman")); + } + + #[test] + fn collapsed_folders_hide_their_models() { + let tree = model_tree(&entries(&["Pack/a", "Pack/b", "loose"])); + let rows = visible_rows(&tree, "", &HashSet::new(), None); + assert_eq!(labels(&rows), ["loose", "Pack"]); + assert!(matches!( + &rows[1], + ListRow::Folder { + open: false, + depth: 0, + .. + } + )); + } + + #[test] + fn opened_folders_show_their_models_one_level_in() { + let tree = model_tree(&entries(&["Pack/a", "Pack/b", "loose"])); + let open = HashSet::from(["Pack".to_owned()]); + let rows = visible_rows(&tree, "", &open, None); + assert_eq!(labels(&rows), ["loose", "Pack", "a", "b"]); + assert!(matches!( + &rows[2], + ListRow::Model { + depth: 1, + folder: None, + .. + } + )); + } + + #[test] + fn the_folders_holding_the_loaded_model_are_open_without_being_asked() { + let tree = model_tree(&entries(&["Pack/Deep/leaf", "Pack/other", "Zeta/one"])); + let rows = visible_rows(&tree, "", &HashSet::new(), Some("Pack/Deep/leaf")); + assert_eq!(labels(&rows), ["Pack", "Deep", "leaf", "other", "Zeta"]); + } + + #[test] + fn filtering_flattens_the_tree_and_says_where_each_match_lives() { + let tree = model_tree(&entries(&["Pack/Deluxe", "Deluxe Reverb", "Pack/Bassman"])); + let rows = visible_rows(&tree, " DELUXE ", &HashSet::new(), None); + assert_eq!( + rows, + [ + ListRow::Model { + depth: 0, + label: "Deluxe Reverb".into(), + key: "Deluxe Reverb".into(), + folder: None, + rate_hz: 48_000 + }, + ListRow::Model { + depth: 0, + label: "Deluxe".into(), + key: "Pack/Deluxe".into(), + folder: Some("Pack".into()), + rate_hz: 48_000 + }, + ] + ); + } + + #[test] + fn malformed_keys_do_not_panic_and_keep_their_key() { + let tree = model_tree(&entries(&["a//b", "c/", "/d"])); + let rows = visible_rows(&tree, "b", &HashSet::new(), None); + assert!(matches!(&rows[0], ListRow::Model { key, .. } if key == "a//b")); + } +} diff --git a/rustortion-ui/src/components/nam_browser/view.rs b/rustortion-ui/src/components/nam_browser/view.rs new file mode 100644 index 0000000..ee5d97f --- /dev/null +++ b/rustortion-ui/src/components/nam_browser/view.rs @@ -0,0 +1,602 @@ +//! The NAM tab: every model in a list on the left, the selected NAM stage on the right. + +use std::path::PathBuf; + +use iced::widget::text::Wrapping; +use iced::widget::{button, column, container, row, rule, scrollable, text, text_input, tooltip}; +use iced::{Alignment, Border, Color, Element, Length, Padding}; + +use rustortion_core::amp::stages::nam::NamConfig; +use rustortion_core::nam::{ModelInfo, registry}; + +use super::NamBrowser; +use super::selection::{PaneState, nam_stage_indices, pane_state}; +use super::tree::{ListRow, leaf_label, model_tree, visible_rows}; +use crate::app::{tab_button_active, tab_button_inactive}; +use crate::components::widgets::common::{ + BORDER_RADIUS_CARD, COLOR_MUTED, COLOR_SUBTLE, COLOR_WARNING, PADDING_NORMAL, PADDING_SMALL, + SPACING_NORMAL, SPACING_TIGHT, TEXT_SIZE_SECTION_TITLE, TEXT_SIZE_SMALL, icon_button, + labeled_slider, section_container, +}; +use crate::messages::{Message, NamTabMessage}; +use crate::stages::{NamMessage, StageConfig, StageMessage}; +use crate::tr; + +/// Extra left padding per folder level in the model list. +const INDENT_PER_LEVEL: f32 = 18.0; +/// Opacity of the `palette.primary` tint behind the loaded model's row. +const LOADED_ROW_ALPHA: f32 = 0.22; +/// Gap between list rows, so neighbouring hover highlights stay apart. +const ROW_SPACING: f32 = 2.0; + +pub struct NamViewContext<'a> { + pub stages: &'a [StageConfig], + /// Device rate × oversampling: the rate stages are built at. + pub engine_sample_rate: u32, + pub models_dir: Option, + pub ir_bypassed: bool, + /// The chain is at `DEFAULT_CHAIN_CAPACITY`. + pub chain_full: bool, +} + +impl NamBrowser { + pub fn view<'a>(&'a self, ctx: &NamViewContext<'a>) -> Element<'a, Message> { + let pane = pane_state(ctx.stages, self.focus, |k| registry::get(k).is_some()); + row![ + pane_card(self.list_pane(ctx, &pane), 9), + pane_card(stage_pane(ctx, &pane), 11), + ] + .spacing(SPACING_NORMAL) + .height(Length::Fill) + .into() + } + + fn list_pane<'a>(&'a self, ctx: &NamViewContext<'a>, pane: &PaneState) -> Element<'a, Message> { + let catalog = registry::catalog(); + let dir = ctx.models_dir.as_ref().map(|p| p.display().to_string()); + + let input = text_input(tr!(nam_filter_placeholder), &self.filter) + .on_input(|f| Message::Nam(NamTabMessage::FilterChanged(f))) + // A no-op resend: without `on_submit` the field lets Enter through to the hotkeys. + .on_submit(Message::Nam(NamTabMessage::FilterChanged( + self.filter.clone(), + ))); + // Clearing must not need the keyboard, which some plugin hosts swallow. + let clear = (!self.filter.is_empty()).then(|| { + icon_button( + "×", + Some(Message::Nam(NamTabMessage::FilterChanged(String::new()))), + button::secondary, + ) + }); + // Always a row, so the input keeps its focus when the button appears. + let filter = row![input, clear] + .spacing(SPACING_TIGHT) + .align_y(Alignment::Center); + + let list = if catalog.is_empty() { + empty_folder_hint(dir.as_deref()) + } else { + let loaded = loaded_key(pane); + // A click would add a NAM stage, and there is no room for one. + let models_clickable = !(ctx.chain_full && *pane == PaneState::NoStage); + let rows = visible_rows( + &model_tree(&catalog), + &self.filter, + &self.open_folders, + loaded, + ) + .into_iter() + .map(|r| list_row(r, loaded, ctx.engine_sample_rate, models_clickable)); + scrollable(column(rows).spacing(ROW_SPACING).width(Length::Fill)) + .spacing(SPACING_TIGHT) + .height(Length::Fill) + .into() + }; + + column![ + filter, + list, + rule::horizontal(1), + list_footer(dir.as_deref(), catalog.len()), + ] + .spacing(SPACING_NORMAL) + .height(Length::Fill) + .into() + } +} + +/// One of the two side-by-side cards: `portion` of the row wide, full height. +fn pane_card(content: Element<'_, Message>, portion: u16) -> Element<'_, Message> { + container(section_container(content)) + .width(Length::FillPortion(portion)) + .height(Length::Fill) + .into() +} + +/// The model the selected NAM stage names, whether or not it is registered. +fn loaded_key(pane: &PaneState) -> Option<&str> { + match pane { + PaneState::Loaded { key, .. } | PaneState::Missing { key, .. } => Some(key), + PaneState::NoStage | PaneState::Empty { .. } => None, + } +} + +fn text_color(color: Color) -> impl Fn(&iced::Theme) -> text::Style { + move |_| text::Style { color: Some(color) } +} + +// --- Left pane --- + +fn empty_folder_hint<'a>(dir: Option<&str>) -> Element<'a, Message> { + container( + column![ + text(tr!(nam_empty_folder_hint)), + text(dir.unwrap_or("—").to_owned()).wrapping(Wrapping::WordOrGlyph), + ] + .spacing(SPACING_TIGHT), + ) + .height(Length::Fill) + .into() +} + +fn list_footer<'a>(dir: Option<&str>, count: usize) -> Element<'a, Message> { + let summary = format!("{} · {count} {}", dir.unwrap_or("—"), tr!(nam_models_count)); + // With no directory there is nothing to open, so the button renders disabled. + let open_folder = button(text(tr!(nam_open_folder))) + .style(button::secondary) + .on_press_maybe( + dir.is_some() + .then_some(Message::Nam(NamTabMessage::OpenFolder)), + ); + // The summary gets its own line: beside the buttons a long path wraps glyph by glyph. + column![ + text(summary) + .size(TEXT_SIZE_SMALL) + .style(text_color(COLOR_SUBTLE)) + .wrapping(Wrapping::WordOrGlyph) + .width(Length::Fill), + row![ + open_folder, + button(text(tr!(nam_rescan_models))) + .style(button::secondary) + .on_press(Message::Nam(NamTabMessage::Rescan)), + ] + .spacing(SPACING_TIGHT), + ] + .spacing(SPACING_TIGHT) + .into() +} + +fn list_row<'a>( + row_data: ListRow, + loaded: Option<&str>, + engine_rate: u32, + models_clickable: bool, +) -> Element<'a, Message> { + match row_data { + ListRow::Folder { + depth, + label, + path, + open, + } => folder_row(depth, label, path, open), + ListRow::Model { + depth, + label, + key, + folder, + rate_hz, + } => { + let is_loaded = loaded == Some(key.as_str()); + let on_press = + models_clickable.then_some(Message::Nam(NamTabMessage::ModelClicked(key))); + model_row( + depth, + label, + folder, + rate_hz, + engine_rate, + is_loaded, + on_press, + ) + } + } +} + +fn folder_row<'a>(depth: usize, label: String, path: String, open: bool) -> Element<'a, Message> { + let caret = if open { "\u{25BE}" } else { "\u{25B8}" }; + list_button( + row![ + text(caret), + text(label) + .wrapping(Wrapping::WordOrGlyph) + .width(Length::Fill), + ] + .spacing(SPACING_TIGHT), + depth, + false, + ) + .on_press(Message::Nam(NamTabMessage::FolderToggled(path))) + .into() +} + +fn model_row<'a>( + depth: usize, + label: String, + folder: Option, + rate_hz: u32, + engine_rate: u32, + is_loaded: bool, + on_press: Option, +) -> Element<'a, Message> { + // The engine passes a model at another rate through dry, so say so before the click. + let rate_mismatch = rate_hz.abs_diff(engine_rate) > 1; + + let mut name = column![]; + if let Some(folder) = folder { + name = name.push( + text(folder) + .size(TEXT_SIZE_SMALL) + .style(text_color(COLOR_SUBTLE)) + .wrapping(Wrapping::WordOrGlyph), + ); + } + name = name.push( + text(label) + .wrapping(Wrapping::WordOrGlyph) + .style(move |_| text::Style { + color: rate_mismatch.then_some(COLOR_MUTED), + }), + ); + + let mut content = row![name.width(Length::Fill)] + .spacing(SPACING_NORMAL) + .align_y(Alignment::Center); + if rate_mismatch { + content = content.push(text(format_khz(rate_hz)).style(text_color(COLOR_WARNING))); + } + + list_button(content, depth, is_loaded) + .on_press_maybe(on_press) + .into() +} + +/// A flat, full-width list row, indented by folder depth. +fn list_button<'a>( + content: impl Into>, + depth: usize, + is_loaded: bool, +) -> button::Button<'a, Message> { + let indent = depth as f32 * INDENT_PER_LEVEL; + button(content) + .width(Length::Fill) + .padding(Padding::from([PADDING_SMALL, PADDING_NORMAL]).left(PADDING_NORMAL + indent)) + .style(move |theme: &iced::Theme, status| { + let style = menu_row_style(theme, status); + if is_loaded { + style.with_background(Color { + a: LOADED_ROW_ALPHA, + ..theme.palette().primary + }) + } else { + style + } + }) +} + +/// Flat and transparent at rest, so a column of rows reads as one list rather than +/// a stack of buttons. Disabled is a model row that cannot load because the chain is full. +fn menu_row_style(theme: &iced::Theme, status: button::Status) -> button::Style { + let palette = theme.extended_palette(); + let base = button::Style { + text_color: palette.background.base.text, + border: Border::default().rounded(BORDER_RADIUS_CARD), + ..button::Style::default() + }; + match status { + button::Status::Active | button::Status::Disabled => { + base.with_background(Color::TRANSPARENT) + } + button::Status::Hovered => base.with_background(palette.background.strong.color), + button::Status::Pressed => base.with_background(palette.primary.weak.color), + } +} + +/// `44100` → "44.1 kHz", `48000` → "48 kHz". Integer maths, so nothing rounds. +fn format_khz(rate_hz: u32) -> String { + let (whole, frac) = (rate_hz / 1000, rate_hz % 1000); + if frac == 0 { + format!("{whole} kHz") + } else { + let frac = format!("{frac:03}"); + format!("{whole}.{} kHz", frac.trim_end_matches('0')) + } +} + +// --- Right pane --- + +fn stage_pane<'a>(ctx: &NamViewContext<'a>, pane: &PaneState) -> Element<'a, Message> { + let (idx, key) = match pane { + PaneState::NoStage => return no_stage_message(ctx.chain_full), + PaneState::Empty { idx } => (*idx, None), + PaneState::Loaded { idx, key } | PaneState::Missing { idx, key } => { + (*idx, Some(key.as_str())) + } + }; + // `pane_state` only ever names a NAM stage. + let Some(stage @ StageConfig::Nam(cfg)) = ctx.stages.get(idx) else { + return no_stage_message(ctx.chain_full); + }; + let title = key.map_or_else( + || tr!(nam_no_model_loaded).to_owned(), + |k| leaf_label(k).to_owned(), + ); + // Extracted once at load, so this is cheap per frame. + let info = key.and_then(registry::info); + let native_rate = match pane { + PaneState::Loaded { key, .. } => { + registry::get(key).map(|model| model.expected_sample_rate() as u32) + } + _ => None, + }; + + let mut content = column![].spacing(SPACING_NORMAL).width(Length::Fill); + if let Some(switcher) = stage_switcher(ctx.stages, idx) { + content = content.push(switcher); + } + content = content.push(stage_header(idx, title, stage.bypassed())); + if matches!(pane, PaneState::Missing { .. }) { + content = content.push(text(tr!(nam_model_not_found)).style(text_color(COLOR_WARNING))); + } + // A mismatched model is bypassed (dry passthrough, no resampling): show both rates. + if let Some(native) = native_rate + && native.abs_diff(ctx.engine_sample_rate) > 1 + { + content = content.push( + text(format!( + "{}: {native} Hz · {} Hz", + tr!(nam_rate_mismatch_bypassed), + ctx.engine_sample_rate + )) + .style(text_color(COLOR_WARNING)), + ); + } + content = content + .push(rule::horizontal(1)) + .push(cab_line(info.as_deref(), ctx.ir_bypassed)) + .push(rule::horizontal(1)) + .push(gain_sliders(idx, cfg)); + if let Some(native) = native_rate { + content = content + .push(rule::horizontal(1)) + .push(detail_rows(info.as_deref(), native)); + } + + scrollable(content) + .spacing(SPACING_TIGHT) + .height(Length::Fill) + .into() +} + +fn no_stage_message<'a>(chain_full: bool) -> Element<'a, Message> { + let hint = if chain_full { + tr!(nam_chain_full) + } else { + tr!(nam_click_to_load) + }; + container( + column![ + text(tr!(nam_no_model_loaded)).size(TEXT_SIZE_SECTION_TITLE), + text(hint) + .style(text_color(COLOR_SUBTLE)) + .align_x(Alignment::Center), + ] + .spacing(SPACING_TIGHT) + .align_x(Alignment::Center), + ) + .center(Length::Fill) + .into() +} + +/// One button per NAM stage, or nothing when there is only one to pick. +fn stage_switcher<'a>(stages: &[StageConfig], selected: usize) -> Option> { + let indices = nam_stage_indices(stages); + if indices.len() <= 1 { + return None; + } + let buttons = indices.into_iter().map(|idx| { + let model = match stages.get(idx) { + Some(StageConfig::Nam(cfg)) => cfg.model_name.as_deref().map(leaf_label), + _ => None, + } + .unwrap_or_else(|| tr!(nam_no_model_loaded)); + button( + text(format!("{} {} · {model}", tr!(stage_nam), idx + 1)) + .wrapping(Wrapping::WordOrGlyph), + ) + .width(Length::Fill) + .padding([PADDING_SMALL, PADDING_NORMAL]) + .style(if idx == selected { + tab_button_active + } else { + tab_button_inactive + }) + .on_press(Message::Nam(NamTabMessage::StageFocused(idx))) + .into() + }); + Some(row(buttons).spacing(SPACING_TIGHT).into()) +} + +fn stage_header<'a>(idx: usize, title: String, bypassed: bool) -> Element<'a, Message> { + let bypass = tooltip( + icon_button( + "⏻", + Some(Message::ToggleStageBypass(idx)), + if bypassed { + button::secondary + } else { + button::success + }, + ), + tr!(stage_bypass_tooltip), + tooltip::Position::Bottom, + ); + row![ + bypass, + text(title) + .size(TEXT_SIZE_SECTION_TITLE) + .wrapping(Wrapping::WordOrGlyph) + .width(Length::Fill), + icon_button("×", Some(Message::RemoveStage(idx)), button::danger), + ] + .spacing(SPACING_NORMAL) + .align_y(Alignment::Center) + .into() +} + +/// The model's cab set against the live IR state, with the one button that toggles the IR. +fn cab_line<'a>(info: Option<&ModelInfo>, ir_bypassed: bool) -> Element<'a, Message> { + // `gear_type` is never displayed — only the conclusion drawn from it, the + // live IR state, and a toggle. Always shown: the pairing is what matters, so + // hiding it when the model says nothing just leaves the IR state a mystery. + // Warning colour marks the two mismatched combinations; the rest stay quiet. + let (cab_text, needs_attention) = match info.map(|info| (info.includes_cab, info.cab_from_name)) + { + Some((Some(true), from_name)) => { + // A name-derived conclusion is a guess; don't present it as fact. + let source = if from_name { + format!(" ({})", tr!(nam_cab_from_name)) + } else { + String::new() + }; + let cab = format!("{}{source}", tr!(nam_cab_included)); + if ir_bypassed { + (format!("{cab} · {}", tr!(nam_cab_ir_bypassed)), false) + } else { + (format!("{cab} · {}", tr!(nam_cab_ir_conflict)), true) + } + } + Some((Some(false), _)) => { + let cab = tr!(nam_cab_not_included); + if ir_bypassed { + (format!("{cab} · {}", tr!(nam_ir_recommended)), true) + } else { + (format!("{cab} · {}", tr!(nam_ir_active)), false) + } + } + // Nothing known about the model: report the IR state without judging it. + Some((None, _)) | None => ( + if ir_bypassed { + tr!(nam_cab_ir_bypassed).to_owned() + } else { + tr!(nam_ir_active).to_owned() + }, + false, + ), + }; + + row![ + text(cab_text) + .style(text_color(if needs_attention { + COLOR_WARNING + } else { + COLOR_SUBTLE + })) + .width(Length::Fill), + // The IR bypass is never changed automatically; this button is the only + // NAM control that touches it, so the write is always a real user + // gesture — which is what a plugin host records as automation. + button(text(if ir_bypassed { + tr!(nam_enable_ir) + } else { + tr!(nam_bypass_ir) + })) + .on_press(Message::IrBypassed(!ir_bypassed)), + ] + .spacing(SPACING_NORMAL) + .align_y(Alignment::Center) + .into() +} + +fn gain_sliders<'a>(idx: usize, cfg: &NamConfig) -> Element<'a, Message> { + let nam = move |msg| Message::Stage(idx, StageMessage::Nam(msg)); + column![ + labeled_slider( + tr!(nam_input_gain), + -24.0..=24.0, + cfg.input_gain_db, + move |v| nam(NamMessage::InputGainChanged(v)), + |v| format!("{v:+.1} dB"), + 0.1, + ), + labeled_slider( + tr!(nam_output_gain), + -24.0..=24.0, + cfg.output_gain_db, + move |v| nam(NamMessage::OutputGainChanged(v)), + |v| format!("{v:+.1} dB"), + 0.1, + ), + labeled_slider( + tr!(nam_mix), + 0.0..=1.0, + cfg.mix, + move |v| nam(NamMessage::MixChanged(v)), + |v| format!("{:.0}%", v * 100.0), + 0.01, + ), + ] + .spacing(SPACING_TIGHT) + .into() +} + +/// What the file says about itself. A field it lacks gets no row. +fn detail_rows<'a>(info: Option<&ModelInfo>, native_rate: u32) -> Element<'a, Message> { + let mut rows: Vec<(&str, String)> = Vec::new(); + if let Some(info) = info { + if let Some(gear) = &info.gear { + rows.push((tr!(nam_gear), gear.clone())); + } + if let Some(tone) = &info.tone_type { + rows.push((tr!(nam_tone_type), tone.clone())); + } + if let Some(by) = &info.modeled_by { + rows.push((tr!(nam_modeled_by), by.clone())); + } + if let Some(dbfs) = info.loudness_dbfs { + rows.push((tr!(nam_loudness), format!("{dbfs:.1} dBFS"))); + } + } + rows.push((tr!(nam_native_rate), format!("{native_rate} Hz"))); + + column(rows.into_iter().map(|(label, value)| { + row![ + text(label) + .size(TEXT_SIZE_SMALL) + .style(text_color(COLOR_SUBTLE)) + .width(Length::FillPortion(3)), + text(value) + .size(TEXT_SIZE_SMALL) + .wrapping(Wrapping::WordOrGlyph) + .width(Length::FillPortion(7)), + ] + .spacing(SPACING_NORMAL) + .into() + })) + .spacing(ROW_SPACING) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rates_are_shown_in_khz_without_trailing_zeros() { + assert_eq!(format_khz(44_100), "44.1 kHz"); + assert_eq!(format_khz(48_000), "48 kHz"); + assert_eq!(format_khz(96_000), "96 kHz"); + assert_eq!(format_khz(88_200), "88.2 kHz"); + } +} diff --git a/rustortion-ui/src/components/widgets/common.rs b/rustortion-ui/src/components/widgets/common.rs index 337bff7..2c7dc19 100644 --- a/rustortion-ui/src/components/widgets/common.rs +++ b/rustortion-ui/src/components/widgets/common.rs @@ -1,7 +1,7 @@ use crate::messages::Message; use crate::tr; use iced::widget::{ - button, column, container, pick_list, row, rule, slider, text, tooltip, vertical_slider, + Space, button, column, container, pick_list, row, rule, slider, text, tooltip, vertical_slider, }; use iced::{Alignment, Color, Element, Length}; @@ -104,18 +104,6 @@ pub struct StageViewState { pub can_move_up: bool, pub can_move_down: bool, pub bypassed: bool, - /// Effective engine sample rate in Hz — the device rate times the oversampling - /// factor, i.e. the rate stages are actually built and run at. Used by stages - /// (e.g. NAM) to detect rate mismatches, so it must match what `to_stage` sees. - pub engine_sample_rate: u32, - /// NAM-specific: directory the NAM stage loads `.nam` models from, shown on - /// the NAM stage card so users know where to drop model files. `None` if the - /// backend has no NAM directory. Ignored by all other stage views. - pub nam_models_dir: Option, - /// Whether the IR cabinet is bypassed. NAM reads it to tell a cab-inclusive - /// model apart from a double-cab: the same model is fine with the IR bypassed - /// and wrong without. Ignored by all other stage views. - pub ir_bypassed: bool, } fn stage_header<'a>( @@ -132,6 +120,18 @@ fn stage_header<'a>( iced::widget::button::secondary, ); + row![ + collapse_btn, + stage_action_buttons(idx, state), + text(header_text) + ] + .spacing(SPACING_TIGHT) + .align_y(Alignment::Center) + .into() +} + +/// The move up, move down, remove and bypass buttons shared by every stage row. +fn stage_action_buttons<'a>(idx: usize, state: &StageViewState) -> Element<'a, Message> { let move_up_btn = if state.can_move_up { icon_button( "↑", @@ -172,17 +172,46 @@ fn stage_header<'a>( iced::widget::tooltip::Position::Bottom, ); - row![ - collapse_btn, - move_up_btn, - move_down_btn, - remove_btn, - bypass_btn, - text(header_text) + row![move_up_btn, move_down_btn, remove_btn, bypass_btn] + .spacing(SPACING_TIGHT) + .align_y(Alignment::Center) + .into() +} + +/// A stage drawn as one row with no body: the usual move/remove/bypass buttons, a label, +/// and a button that opens its editor elsewhere. +pub fn stage_link_row<'a>( + label: String, + idx: usize, + state: &StageViewState, + open_label: &'a str, + on_open: Message, +) -> Element<'a, Message> { + let content = row![ + Space::new().width(ICON_BUTTON_WIDTH), + stage_action_buttons(idx, state), + text(label) + .width(Length::Fill) + .wrapping(iced::widget::text::Wrapping::WordOrGlyph), + button(text(open_label)) + .on_press(on_open) + .style(iced::widget::button::secondary), ] .spacing(SPACING_TIGHT) .align_y(Alignment::Center) - .into() + .padding(PADDING_SMALL); + + let opacity = if state.bypassed { 0.5 } else { 1.0 }; + + container(content) + .width(Length::Fill) + .style(move |theme: &iced::Theme| { + let bg = theme.palette().background; + container::Style::default() + .background(iced::Color::from_rgba(bg.r, bg.g, bg.b, opacity)) + .border(iced::Border::default().rounded(BORDER_RADIUS_CARD)) + }) + .into() } pub fn stage_card<'a>( diff --git a/rustortion-ui/src/i18n/mod.rs b/rustortion-ui/src/i18n/mod.rs index ada2864..aa46cf8 100644 --- a/rustortion-ui/src/i18n/mod.rs +++ b/rustortion-ui/src/i18n/mod.rs @@ -94,7 +94,6 @@ pub struct Translations { pub nam_models_dir: &'static str, pub nam_rescan_models: &'static str, pub nam_open_folder: &'static str, - pub nam_metadata: &'static str, pub nam_gear: &'static str, pub nam_tone_type: &'static str, pub nam_modeled_by: &'static str, @@ -182,14 +181,19 @@ pub struct Translations { pub stage_eq: &'static str, pub stage_tremolo: &'static str, pub stage_nam: &'static str, - pub nam_model: &'static str, - pub nam_no_model: &'static str, pub nam_native_rate: &'static str, pub nam_rate_mismatch_bypassed: &'static str, pub nam_model_not_found: &'static str, pub nam_input_gain: &'static str, pub nam_output_gain: &'static str, pub nam_mix: &'static str, + pub nam_filter_placeholder: &'static str, + pub nam_no_model_loaded: &'static str, + pub nam_click_to_load: &'static str, + pub nam_chain_full: &'static str, + pub nam_empty_folder_hint: &'static str, + pub nam_models_count: &'static str, + pub nam_open: &'static str, pub stage_bypass: &'static str, pub stage_bypass_tooltip: &'static str, @@ -271,6 +275,7 @@ pub struct Translations { // Tabs pub tab_amp: &'static str, + pub tab_nam: &'static str, pub tab_effects: &'static str, pub tab_cabinet: &'static str, pub tab_io: &'static str, @@ -318,7 +323,6 @@ pub static EN: Translations = Translations { nam_models_dir: "NAM Models Directory", nam_rescan_models: "Rescan Models", nam_open_folder: "Open Folder", - nam_metadata: "Metadata", nam_gear: "Gear", nam_tone_type: "Tone type", nam_modeled_by: "By", @@ -406,14 +410,19 @@ pub static EN: Translations = Translations { stage_eq: "Graphic EQ", stage_tremolo: "Tremolo", stage_nam: "NAM", - nam_model: "Model", - nam_no_model: "Select a model…", nam_native_rate: "Native rate", nam_rate_mismatch_bypassed: "Bypassed — model rate vs engine rate", nam_model_not_found: "Model not found", nam_input_gain: "Input", nam_output_gain: "Output", nam_mix: "Mix", + nam_filter_placeholder: "Filter models…", + nam_no_model_loaded: "No model loaded", + nam_click_to_load: "Click a model on the left to load it.", + nam_chain_full: "The chain is full. Remove a stage to add NAM.", + nam_empty_folder_hint: "No models found. Put .nam files in this folder, then press Rescan Models:", + nam_models_count: "models", + nam_open: "Open", stage_bypass: "Bypass", stage_bypass_tooltip: "Toggle stage bypass", @@ -495,6 +504,7 @@ pub static EN: Translations = Translations { // Tabs tab_amp: "AMP", + tab_nam: "NAM", tab_effects: "EFFECTS", tab_cabinet: "CABINET", tab_io: "INPUT", @@ -533,7 +543,6 @@ pub static ZH_CN: Translations = Translations { nam_models_dir: "NAM 模型目录", nam_rescan_models: "重新扫描模型", nam_open_folder: "打开文件夹", - nam_metadata: "元数据", nam_gear: "设备", nam_tone_type: "音色类型", nam_modeled_by: "制作者", @@ -621,14 +630,19 @@ pub static ZH_CN: Translations = Translations { stage_eq: "图形均衡器", stage_tremolo: "颤音", stage_nam: "NAM", - nam_model: "模型", - nam_no_model: "选择模型…", nam_native_rate: "原始采样率", nam_rate_mismatch_bypassed: "已旁通 — 模型采样率 vs 引擎采样率", nam_model_not_found: "未找到模型", nam_input_gain: "输入", nam_output_gain: "输出", nam_mix: "混合", + nam_filter_placeholder: "筛选模型…", + nam_no_model_loaded: "未加载模型", + nam_click_to_load: "点击左侧的模型即可加载。", + nam_chain_full: "信号链已满。请先移除一个级,再添加 NAM。", + nam_empty_folder_hint: "未找到模型。请将 .nam 文件放入此文件夹,然后点击“重新扫描模型”:", + nam_models_count: "个模型", + nam_open: "打开", stage_bypass: "旁路", stage_bypass_tooltip: "切换旁路", @@ -710,6 +724,7 @@ pub static ZH_CN: Translations = Translations { // Tabs tab_amp: "音箱", + tab_nam: "NAM", tab_effects: "效果", tab_cabinet: "箱体", tab_io: "输入", diff --git a/rustortion-ui/src/messages/mod.rs b/rustortion-ui/src/messages/mod.rs index 0241ea6..b8ae197 100644 --- a/rustortion-ui/src/messages/mod.rs +++ b/rustortion-ui/src/messages/mod.rs @@ -4,12 +4,14 @@ use rustortion_core::preset::InputFilterConfig; pub mod hotkey; pub mod midi; +pub mod nam; pub mod preset; pub mod settings; pub mod tuner; pub use hotkey::*; pub use midi::*; +pub use nam::*; pub use preset::*; pub use settings::*; pub use tuner::*; @@ -67,6 +69,9 @@ pub enum Message { // Stage-specific messages Stage(usize, StageMessage), + // NAM tab messages + Nam(NamTabMessage), + // Tuner messages Tuner(TunerMessage), diff --git a/rustortion-ui/src/messages/nam.rs b/rustortion-ui/src/messages/nam.rs new file mode 100644 index 0000000..2fe2672 --- /dev/null +++ b/rustortion-ui/src/messages/nam.rs @@ -0,0 +1,15 @@ +/// Messages from the NAM tab. +#[derive(Debug, Clone)] +pub enum NamTabMessage { + FilterChanged(String), + /// Folder path, as in `ListRow::Folder::path`. + FolderToggled(String), + /// Registry key of the model that was clicked. + ModelClicked(String), + /// Chain index picked in the switcher. + StageFocused(usize), + /// Select this chain index and switch to the NAM tab. + OpenStage(usize), + Rescan, + OpenFolder, +} diff --git a/rustortion-ui/src/stages/mod.rs b/rustortion-ui/src/stages/mod.rs index f6e89ef..6faa05d 100644 --- a/rustortion-ui/src/stages/mod.rs +++ b/rustortion-ui/src/stages/mod.rs @@ -10,10 +10,6 @@ pub enum ParamUpdate { Changed(&'static str, f32), /// A non-float parameter changed -- rebuild this stage only. NeedsStageRebuild, - /// Re-scan the NAM models directory and re-register the global registry. - RescanNamModels, - /// Open the NAM models directory in the user's file manager. - OpenNamModelsDir, } macro_rules! gui_stage_registry { diff --git a/rustortion-ui/src/stages/nam.rs b/rustortion-ui/src/stages/nam.rs index ea5d145..3b38dd1 100644 --- a/rustortion-ui/src/stages/nam.rs +++ b/rustortion-ui/src/stages/nam.rs @@ -1,207 +1,28 @@ -use iced::widget::{button, column, container, responsive, row, rule, text}; -use iced::{Alignment, Border, Color, Element, Length, Padding}; -use iced_aw::menu::{self, Item, Menu, MenuBar}; +use iced::Element; use rustortion_core::amp::stages::nam::NamConfig; -use rustortion_core::nam::registry; -use crate::components::widgets::common::{ - BORDER_RADIUS_CARD, COLOR_SUBTLE, COLOR_WARNING, PADDING_NORMAL, PADDING_SMALL, SPACING_NORMAL, - SPACING_TIGHT, SPACING_WIDE, StageViewState, TEXT_SIZE_SMALL, labeled_slider, stage_card, -}; -use crate::messages::Message; +use crate::components::nam_browser::tree::leaf_label; +use crate::components::widgets::common::{StageViewState, stage_link_row}; +use crate::messages::{Message, NamTabMessage}; use crate::tr; -use super::{ParamUpdate, StageMessage}; +use super::ParamUpdate; // --- Message --- #[derive(Debug, Clone)] pub enum NamMessage { - ModelSelected(Option), + ModelSelected(String), InputGainChanged(f32), OutputGainChanged(f32), MixChanged(f32), - /// Re-scan the NAM models directory and refresh the model pick-list. - Rescan, - /// Reveal the NAM models directory in the file manager. - OpenFolder, - /// The picker's root button was pressed. The menu bar opens itself on the - /// release; this exists only so the button has a press handler. - MenuOpened, } -// --- Model tree --- - -/// One entry of the model picker menu: a folder that fans out into its contents, or -/// a model that can be selected. Built from the registry's flat `Folder/Model` keys. -#[derive(Debug, Clone, PartialEq, Eq)] -enum ModelNode { - Folder { - label: String, - children: Vec, - }, - Model { - /// Shown in the menu: the file's own name. - label: String, - /// Stored in the preset and looked up in the registry: the full key. - key: String, - }, -} - -impl ModelNode { - fn label(&self) -> &str { - match self { - Self::Folder { label, .. } | Self::Model { label, .. } => label, - } - } -} - -/// The last path segment of a registry key: what the closed picker shows, since -/// the folder is visible in the menu and the full key would not fit the card. -fn leaf_label(key: &str) -> &str { - key.rsplit('/').next().unwrap_or(key) -} - -/// Group registry keys into a folder tree. Folders and loose files sort together -/// by name, ignoring case, at every level. -fn model_tree(keys: &[String]) -> Vec { - let mut root = Vec::new(); - for key in keys { - let mut segments = key.split('/').peekable(); - let mut level = &mut root; - while let Some(segment) = segments.next() { - if segments.peek().is_none() { - level.push(ModelNode::Model { - label: segment.to_owned(), - key: key.clone(), - }); - break; - } - let position = level - .iter() - .position(|node| matches!(node, ModelNode::Folder { label, .. } if label == segment)) - .unwrap_or_else(|| { - level.push(ModelNode::Folder { - label: segment.to_owned(), - children: Vec::new(), - }); - level.len() - 1 - }); - let ModelNode::Folder { children, .. } = &mut level[position] else { - unreachable!("position was found by matching a Folder"); - }; - level = children; - } - } - sort_tree(&mut root); - root -} - -fn sort_tree(nodes: &mut [ModelNode]) { - nodes.sort_by_cached_key(|node| node.label().to_lowercase()); - for node in nodes { - if let ModelNode::Folder { children, .. } = node { - sort_tree(children); - } - } -} - -/// Pointing right: this entry fans out into a child menu. -const MENU_CARET_RIGHT: &str = "\u{25B8}"; -/// Pointing down: the closed picker, as a pick list draws it. -const MENU_CARET_DOWN: &str = "\u{25BE}"; -/// Wide enough for the long capture names packs use without wrapping every row. -const MENU_WIDTH: f32 = 380.0; - -type MenuItem<'a> = Item<'a, Message, iced::Theme, iced::Renderer>; -type ModelMenu<'a> = Menu<'a, Message, iced::Theme, iced::Renderer>; - -/// A child menu, sized and spaced the same at every depth. -fn model_menu(items: Vec>) -> ModelMenu<'_> { - Menu::new(items) - .width(MENU_WIDTH) - .offset(PADDING_SMALL) - .spacing(2.0) -} - -/// One selectable row. The selected model is marked in the warning colour rather -/// than a check mark, which would shift every other label over by a column. -fn menu_entry<'a>(label: String, selected: bool, on_press: Message) -> Element<'a, Message> { - button(text(label).style(move |theme: &iced::Theme| iced::widget::text::Style { - color: Some(if selected { COLOR_WARNING } else { theme.palette().text }), - })) - .width(Length::Fill) - .padding([PADDING_SMALL, PADDING_NORMAL]) - .style(menu_row_style) - .on_press(on_press) - .into() -} - -/// A folder row. It has no press action: hovering opens the child menu, and the -/// menu bar draws the highlight for the open path itself. -fn menu_folder<'a>(label: String) -> Element<'a, Message> { - button( - row![text(label).width(Length::Fill), text(MENU_CARET_RIGHT)].spacing(SPACING_TIGHT), - ) - .width(Length::Fill) - .padding([PADDING_SMALL, PADDING_NORMAL]) - .style(menu_row_style) - .into() -} - -/// Flat and transparent at rest, so a column of rows reads as one list rather than -/// a stack of buttons. Disabled is the folder rows' resting state, not an error. -fn menu_row_style(theme: &iced::Theme, status: button::Status) -> button::Style { - let palette = theme.extended_palette(); - let base = button::Style { - text_color: palette.background.base.text, - border: Border::default().rounded(BORDER_RADIUS_CARD), - ..button::Style::default() - }; - match status { - button::Status::Active | button::Status::Disabled => { - base.with_background(Color::TRANSPARENT) - } - button::Status::Hovered => base.with_background(palette.background.strong.color), - button::Status::Pressed => base.with_background(palette.primary.weak.color), - } -} - -/// Menu items for one level of the tree, recursing into folders. -fn menu_items<'a>( - nodes: &[ModelNode], - idx: usize, - selected: Option<&str>, -) -> Vec> { - nodes - .iter() - .map(|node| match node { - ModelNode::Folder { label, children } => Item::with_menu( - menu_folder(label.clone()), - model_menu(menu_items(children, idx, selected)), - ) - // The bar closes on any item click by default, and people do click a - // folder to open it. Only picking a model, or clicking away, closes. - .close_on_click(false), - ModelNode::Model { label, key } => Item::new(menu_entry( - label.clone(), - selected == Some(key.as_str()), - Message::Stage( - idx, - StageMessage::Nam(NamMessage::ModelSelected(Some(key.clone()))), - ), - )), - }) - .collect() -} - -// --- Apply --- - pub fn apply(cfg: &mut NamConfig, msg: NamMessage) -> Option { match msg { - NamMessage::ModelSelected(name) => { - cfg.model_name = name; + NamMessage::ModelSelected(key) => { + cfg.model_name = Some(key); // Selecting a model is a non-float change: rebuild the stage. Some(ParamUpdate::NeedsStageRebuild) } @@ -217,356 +38,55 @@ pub fn apply(cfg: &mut NamConfig, msg: NamMessage) -> Option { cfg.mix = v; Some(ParamUpdate::Changed("mix", v)) } - NamMessage::Rescan => Some(ParamUpdate::RescanNamModels), - NamMessage::OpenFolder => Some(ParamUpdate::OpenNamModelsDir), - NamMessage::MenuOpened => None, } } // --- View --- -pub fn view(idx: usize, cfg: &NamConfig, state: StageViewState) -> Element<'_, Message> { - let model_name = cfg.model_name.clone(); - let input_gain_db = cfg.input_gain_db; - let output_gain_db = cfg.output_gain_db; - let mix = cfg.mix; - // The folder where `.nam` files live, shown so users know where to drop models. - let models_dir = state - .nam_models_dir - .as_ref() - .map(|p| p.display().to_string()); - // Effective engine rate, read out before `state` is moved into the card closure. - let engine_rate = state.engine_sample_rate; - // Lets a cab-inclusive model say whether the IR is a second cab or already out. - let ir_bypassed = state.ir_bypassed; - - stage_card(tr!(stage_nam), idx, state, move || { - // The picker is a one-root menu bar rather than a pick list: a pick list is a - // flat list, and packs ship as folders of dozens of files. Each folder fans - // out sideways; loose files sit alongside the folders at the same level. - // - // The bar lays its root out against an unbounded width, so a `Fill` button - // inside it never gets a size. `responsive` hands over the width the row - // actually allotted, and the button takes exactly that. - let tree = model_tree(®istry::available_names()); - let picker_model = model_name.clone(); - let closed_label = model_name - .as_deref() - .map_or_else(|| tr!(nam_no_model).to_owned(), |key| leaf_label(key).to_owned()); - let model_picker = responsive(move |size| { - // "(None)" first so a selected model can be cleared back to passthrough. - let mut items = vec![Item::new(menu_entry( - tr!(nam_no_model).to_owned(), - picker_model.is_none(), - Message::Stage(idx, StageMessage::Nam(NamMessage::ModelSelected(None))), - ))]; - items.extend(menu_items(&tree, idx, picker_model.as_deref())); - - MenuBar::new(vec![Item::with_menu( - button( - row![ - text(closed_label.clone()).width(Length::Fill), - text(MENU_CARET_DOWN), - ] - .spacing(SPACING_TIGHT), - ) - .width(size.width) - .style(button::secondary) - // Opening is handled by the menu bar; the press itself does nothing, - // but a button without `on_press` renders as disabled. - .on_press(Message::Stage(idx, StageMessage::Nam(NamMessage::MenuOpened))), - // As wide as the button, so it hangs straight below it like a pick - // list. Left free, the bar would right-align it whenever the button - // sits in the right half of the window. - model_menu(items).width(size.width), - )]) - // Behave like a pick list: stay open until something is clicked. - .close_on_item_click_global(true) - .close_on_background_click_global(true) - // Leaving the menu must not close it either. The bar pads its bounds - // by this margin and tests containment, and `width + 2 * MAX` - // overflows to infinity, so the cursor is never outside. A large - // finite value would depend on the monitor size. - .safe_bounds_margin(f32::MAX) - // Highlights the folder whose child menu is open. - .draw_path(menu::DrawPath::Backdrop) - .into() - }) - .width(Length::FillPortion(7)) - .height(Length::Shrink); - - let model_selector = row![ - text(tr!(nam_model)).width(Length::FillPortion(3)), - model_picker, - ] - .spacing(SPACING_NORMAL) - .align_y(Alignment::Center); - - // Read-only info: the selected model's native sample rate (or "not found"). - // When the native rate mismatches the engine rate the model is bypassed (dry - // passthrough, no resampling) — surface that here using both rates. - let info_line: Element<'_, Message> = match model_name.as_deref() { - Some(name) => match registry::get(name) { - Some(model) => { - let native_rate = model.expected_sample_rate() as u32; - if native_rate.abs_diff(engine_rate) > 1 { - text(format!( - "{}: {native_rate} Hz · {engine_rate} Hz", - tr!(nam_rate_mismatch_bypassed) - )) - } else { - text(format!("{}: {native_rate} Hz", tr!(nam_native_rate))) - } - } - None => text(tr!(nam_model_not_found)), - } - .into(), - None => text(String::new()).into(), - }; - - // Extracted once at load, so this is cheap per frame. - let model_info = model_name.as_deref().and_then(registry::info); - - // Filenames in the wild are often cryptic while the metadata names the real - // amp. A field the file doesn't carry gets no row. - let metadata_rows: Vec<(&str, String)> = model_info.as_deref().map_or_else( - Vec::new, - |info| { - let mut rows: Vec<(&str, String)> = Vec::new(); - if let Some(gear) = info.gear.as_deref() { - rows.push((tr!(nam_gear), gear.to_owned())); - } - if let Some(tone) = info.tone_type.as_deref() { - rows.push((tr!(nam_tone_type), tone.to_owned())); - } - if let Some(by) = info.modeled_by.as_deref() { - rows.push((tr!(nam_modeled_by), by.to_owned())); - } - // Spans >20 dB across models — the volume jump when switching. - if let Some(dbfs) = info.loudness_dbfs { - rows.push((tr!(nam_loudness), format!("{dbfs:.1} dBFS"))); - } - rows - }, - ); - - // Smaller and dimmer than the controls: it describes the file rather than - // doing anything. Omitted when the file says nothing. - let metadata_section: Element<'_, Message> = if metadata_rows.is_empty() { - column![].into() - } else { - let rows = metadata_rows.into_iter().map(|(label, value)| { - row![ - text(format!("{label}:")) - .size(TEXT_SIZE_SMALL) - .style(|_| iced::widget::text::Style { - color: Some(COLOR_SUBTLE), - }) - .width(Length::FillPortion(4)), - text(value) - .size(TEXT_SIZE_SMALL) - .width(Length::FillPortion(6)), - ] - .spacing(SPACING_TIGHT) - .into() - }); - - column![ - rule::horizontal(1), - text(format!("{}:", tr!(nam_metadata))) - .size(TEXT_SIZE_SMALL) - .style(|_| iced::widget::text::Style { - color: Some(COLOR_SUBTLE), - }), - container(column(rows).spacing(2)) - .padding(Padding::ZERO.left(SPACING_WIDE)), - ] - .spacing(SPACING_TIGHT) - .into() - }; - - // `gear_type` is never displayed — only the conclusion drawn from it, the - // live IR state, and a toggle. Always shown: the pairing is what matters, so - // hiding it when the model says nothing just leaves the IR state a mystery. - // Warning colour marks the two mismatched combinations; the rest stay quiet. - let (cab_text, needs_attention) = match model_info - .as_deref() - .map(|info| (info.includes_cab, info.cab_from_name)) - { - Some((Some(true), from_name)) => { - // A name-derived conclusion is a guess; don't present it as fact. - let source = if from_name { - format!(" ({})", tr!(nam_cab_from_name)) - } else { - String::new() - }; - let cab = format!("{}{source}", tr!(nam_cab_included)); - if ir_bypassed { - (format!("{cab} · {}", tr!(nam_cab_ir_bypassed)), false) - } else { - (format!("{cab} · {}", tr!(nam_cab_ir_conflict)), true) - } - } - Some((Some(false), _)) => { - let cab = tr!(nam_cab_not_included); - if ir_bypassed { - (format!("{cab} · {}", tr!(nam_ir_recommended)), true) - } else { - (format!("{cab} · {}", tr!(nam_ir_active)), false) - } - } - // Nothing known about the model: report the IR state without judging it. - Some((None, _)) | None => ( - if ir_bypassed { - tr!(nam_cab_ir_bypassed).to_owned() - } else { - tr!(nam_ir_active).to_owned() - }, - false, - ), - }; - - let cab_line = row![ - text(cab_text) - .style(move |_| iced::widget::text::Style { - color: Some(if needs_attention { - COLOR_WARNING - } else { - COLOR_SUBTLE - }), - }) - .width(Length::Fill), - // The IR bypass is never changed automatically; this button is the only - // thing on this card that touches it, so the write is always a real user - // gesture — which is what a plugin host records as automation. - button(text(if ir_bypassed { - tr!(nam_enable_ir) - } else { - tr!(nam_bypass_ir) - })) - .on_press(Message::IrBypassed(!ir_bypassed)), - ] - .spacing(SPACING_NORMAL) - .align_y(Alignment::Center); - - // Rescan picks up newly dropped `.nam` files without restarting the host. - let dir_text = models_dir.as_deref().map_or_else( - || format!("{}: —", tr!(nam_models_dir)), - |dir| format!("{}: {dir}", tr!(nam_models_dir)), - ); - // With no directory the row shows "—", so the button has nothing to open: - // leave `on_press` unset and iced renders it disabled, rather than offering - // a click whose only effect is a log line. - let open_folder = button(text(tr!(nam_open_folder))); - let open_folder = if models_dir.is_some() { - open_folder.on_press(Message::Stage( - idx, - StageMessage::Nam(NamMessage::OpenFolder), - )) - } else { - open_folder - }; - let folder_row = row![ - text(dir_text).width(Length::Fill), - open_folder, - button(text(tr!(nam_rescan_models))) - .on_press(Message::Stage(idx, StageMessage::Nam(NamMessage::Rescan))), - ] - .spacing(SPACING_NORMAL) - .align_y(Alignment::Center); +/// "NAM 2 · leaf", or the no-model text when nothing is loaded. +fn row_label(idx: usize, cfg: &NamConfig) -> String { + let model = cfg + .model_name + .as_deref() + .map_or_else(|| tr!(nam_no_model_loaded), leaf_label); + format!("{} {} · {model}", tr!(stage_nam), idx + 1) +} - // The cab/IR line stays with the controls: it reports a change to the live - // signal chain, not a description of the file. - column![ - model_selector, - folder_row, - info_line, - cab_line, - labeled_slider( - tr!(nam_input_gain), - -24.0..=24.0, - input_gain_db, - move |v| Message::Stage(idx, StageMessage::Nam(NamMessage::InputGainChanged(v))), - |v| format!("{v:+.1} dB"), - 0.1, - ), - labeled_slider( - tr!(nam_output_gain), - -24.0..=24.0, - output_gain_db, - move |v| Message::Stage(idx, StageMessage::Nam(NamMessage::OutputGainChanged(v))), - |v| format!("{v:+.1} dB"), - 0.1, - ), - labeled_slider( - tr!(nam_mix), - 0.0..=1.0, - mix, - move |v| Message::Stage(idx, StageMessage::Nam(NamMessage::MixChanged(v))), - |v| format!("{:.0}%", v * 100.0), - 0.01, - ), - metadata_section, - ] - .spacing(SPACING_TIGHT) - .into() - }) +pub fn view(idx: usize, cfg: &NamConfig, state: StageViewState) -> Element<'_, Message> { + stage_link_row( + row_label(idx, cfg), + idx, + &state, + tr!(nam_open), + Message::Nam(NamTabMessage::OpenStage(idx)), + ) } #[cfg(test)] mod tests { use super::*; - fn folder(node: &ModelNode) -> (&str, &[ModelNode]) { - match node { - ModelNode::Folder { label, children } => (label.as_str(), children.as_slice()), - ModelNode::Model { .. } => panic!("expected a folder, got {node:?}"), - } - } - - fn model(node: &ModelNode) -> (&str, &str) { - match node { - ModelNode::Model { label, key } => (label.as_str(), key.as_str()), - ModelNode::Folder { .. } => panic!("expected a model, got {node:?}"), - } - } - - /// Registry keys are `Folder/Sub/Model`. The menu groups them by folder, keeps - /// the full key on each leaf (that is what gets selected), and sorts folders - /// and loose files together by name, ignoring case, at every level. #[test] - fn model_tree_groups_keys_by_folder() { - // `Pack` is both a folder and a loose file: both must survive, side by side. - let names = [ - "Pack/Deep/leaf", - "Pack/inner", - "alpha", - "Zeta/one", - "beta", - "Pack", - ] - .map(str::to_owned); - - let tree = model_tree(&names); - - let labels: Vec<&str> = tree.iter().map(ModelNode::label).collect(); - assert_eq!(labels, ["alpha", "beta", "Pack", "Pack", "Zeta"]); - assert_eq!(model(&tree[0]), ("alpha", "alpha")); - assert_eq!(model(&tree[3]), ("Pack", "Pack")); - - let (_, pack) = folder(&tree[2]); - assert_eq!(pack.len(), 2); - let (deep_label, deep) = folder(&pack[0]); - assert_eq!(deep_label, "Deep"); - assert_eq!(model(&deep[0]), ("leaf", "Pack/Deep/leaf")); - assert_eq!(model(&pack[1]), ("inner", "Pack/inner")); + fn the_amp_tab_row_names_the_stage_and_its_model() { + let with_model = NamConfig { + model_name: Some("Pack/Deep/leaf".into()), + ..NamConfig::default() + }; + assert_eq!( + row_label(1, &with_model), + format!("{} 2 · leaf", tr!(stage_nam)) + ); + assert_eq!( + row_label(0, &NamConfig::default()), + format!("{} 1 · {}", tr!(stage_nam), tr!(nam_no_model_loaded)) + ); } - /// What the closed picker shows: only the file's own name, since the folder is - /// visible in the menu and the full key would not fit the card. #[test] - fn leaf_label_drops_the_folder_prefix() { - assert_eq!(leaf_label("Pack/Deep/leaf"), "leaf"); - assert_eq!(leaf_label("alpha"), "alpha"); + fn selecting_a_model_rebuilds_the_stage() { + let mut cfg = NamConfig::default(); + let update = apply(&mut cfg, NamMessage::ModelSelected("a".into())); + assert_eq!(cfg.model_name.as_deref(), Some("a")); + assert!(matches!(update, Some(ParamUpdate::NeedsStageRebuild))); } } diff --git a/rustortion-ui/src/tabs.rs b/rustortion-ui/src/tabs.rs index 65dd68f..5ff6c49 100644 --- a/rustortion-ui/src/tabs.rs +++ b/rustortion-ui/src/tabs.rs @@ -1,9 +1,10 @@ -use crate::stages::StageCategory; +use crate::stages::{StageCategory, StageConfig}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Tab { #[default] Amp, + Nam, Effects, Cabinet, Io, @@ -18,3 +19,35 @@ impl Tab { } } } + +/// The tab a stage is edited on: NAM stages on `Tab::Nam`, the rest by category. +pub const fn tab_for_stage(cfg: &StageConfig) -> Tab { + match cfg { + StageConfig::Nam(_) => Tab::Nam, + _ => match cfg.category() { + StageCategory::Amp => Tab::Amp, + StageCategory::Effect => Tab::Effects, + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::stages::StageType; + + #[test] + fn nam_stages_belong_to_the_nam_tab_and_the_rest_to_their_category() { + assert_eq!(tab_for_stage(&StageConfig::from(StageType::Nam)), Tab::Nam); + assert_eq!( + tab_for_stage(&StageConfig::from(StageType::Preamp)), + Tab::Amp + ); + assert_eq!( + tab_for_stage(&StageConfig::from(StageType::Reverb)), + Tab::Effects + ); + assert_eq!(Tab::Nam.stage_category(), None); + assert_eq!(Tab::default(), Tab::Amp); + } +}