diff --git a/Cargo.lock b/Cargo.lock index bb35703d..231a2794 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -235,6 +235,7 @@ dependencies = [ "thiserror 2.0.21", "uuid", "walkdir", + "windows-sys 0.61.2", ] [[package]] diff --git a/README.md b/README.md index 7b7ad4ef..41d62506 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ | Game | Bundled instruments | | --- | --- | -| **Genshin Impact** | 11 instruments, including lyres, zithers, pianos, percussion, Ukulele, Nightwind Horn, and Lingering Euphonia | +| **Genshin Impact** | 11 instrument entries, including lyres, zithers, pianos, percussion, Nightwind Horn, plus Ukulele and Lingering Euphonia with Keyboard and Chords modes | | **Wuthering Waves** | 21-key instrument layout | | **Neverness to Everness (NTE)** | Piano (21-key and 36-key), Guitar | | **Where Winds Meet** | Guqin | @@ -64,11 +64,14 @@ Here's where the main controls live. The annotated screenshots use the current i * **Smart transpose and Auto Correct** - Help notes fit instruments with limited ranges or missing sharps and flats. You can also choose Up, Down, or Ignore transposition. * **Hold Notes and Tap Threshold** - Choose between short key taps and held notes, or tap short notes while holding longer ones. * **Merge Notes** - Join repeated notes of the same pitch when they overlap or fall within your chosen gap. Try it on songs where repeated taps sound too busy. -* **Auto Chord** - Match groups of notes to built-in chord keys on instruments that support them, such as Genshin's Ukulele and Lingering Euphonia. +* **Chord & Fret Instruments** - Switch between Keyboard and Chords modes on Genshin's Ukulele and Lingering Euphonia, or use Keyboard, Chords, and Frets modes on NTE's Guitar. +* **Default configuration updates** - Add missing bundled layouts and instruments on launch. A setup screen reviews changed JSON and duplicate IDs before the player initializes, with opt-in replacement and backed-up removal of older duplicates. See [configuration update behavior](docs/instrument-configuration.md#existing-configurations). * **Pedals and layouts** - Use sustain, sostenuto, and soft pedals where supported. Edit pedal bindings for the selected keyboard layout, and choose from QWERTY, QWERTZ, AZERTY, Dvorak, and other available mappings. Every game's instrument behaves a little differently. Preview your changes, then try a short section in-game to find what sounds best. +NTE's **Guitar** has separate Keyboard, Chords, and Frets controls, including 24 wheel chords and frets 0–24 with automatic paging. Its guitar display shows six strings and a string/fret readout. See the [NTE guitar setup guide](docs/nte-guitar.md) and [instrument JSON schema](docs/instrument-configuration.md). + ### Listen Before You Play Listen Mode plays through your speakers using SoundFonts instead of sending game keys. Pick **Game Preview (Adapted)** to hear notes fitted to the selected instrument, or **Full Chromatic (Raw)** to hear the original MIDI pitches. diff --git a/crates/amp-core/Cargo.toml b/crates/amp-core/Cargo.toml index 71c4002e..2ce62b56 100644 --- a/crates/amp-core/Cargo.toml +++ b/crates/amp-core/Cargo.toml @@ -32,6 +32,9 @@ notify = "8.2" regex = "1.11" quick-xml = "0.42" +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging", "Win32_System_Threading"] } + [[bin]] name = "amp-cli" path = "src/main.rs" diff --git a/crates/amp-core/src/input/chord_wheel.rs b/crates/amp-core/src/input/chord_wheel.rs new file mode 100644 index 00000000..5d2aadbe --- /dev/null +++ b/crates/amp-core/src/input/chord_wheel.rs @@ -0,0 +1,728 @@ +//! Prepare selector/page changes ahead of the musical onset, without sleeping. +use super::{ + config::ChordWheelConfigJson, + mapping::{parse_key_stroke, KeyStroke}, + simulator::KeyboardOutput, +}; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WheelButton { + Left, + Right, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChordWheelState { + pub page: Option, + pub busy: bool, + pub error: Option, +} + +enum Stage { + PageDown, + PageUp, + PageWait, + Move, + SelectDown, + SelectUp, + Ready, + StrumUp, +} +struct Attack { + owner: Option, + config: ChordWheelConfigJson, + processes: Vec, + target_page: usize, + slot: Option, + stage: Stage, + at: Instant, + page_delta: isize, +} + +pub(super) struct ChordWheelOutput { + attack: Option, + held: Option, + page_key: Option, + page: Option, + selected: Option, + held_strings: Vec, +} + +impl Default for ChordWheelOutput { + fn default() -> Self { + Self { + attack: None, + held: None, + page_key: None, + page: Some(0), + selected: None, + held_strings: Vec::new(), + } + } +} + +impl ChordWheelOutput { + pub fn state(&self) -> ChordWheelState { + ChordWheelState { + page: self.page, + busy: self.is_active(), + error: None, + } + } + pub fn assume_page(&mut self, page: usize) { + self.page = Some(page); + self.selected = None; + } + pub fn forget_page(&mut self) { + self.page = None; + self.selected = None; + } + pub fn retire(&mut self) { + self.attack = None; + self.held = None; + self.page_key = None; + self.selected = None; + self.held_strings.clear(); + } + pub fn preparation_ms(&self, config: &ChordWheelConfigJson, index: usize) -> u64 { + if self.selected == Some(index) { + // No selector work is needed, but keep a small lookahead so the + // transport prepares this owner before its final sub-ms wait. + return 2; + } + let pages = self.page.map_or(config.page_count - 1, |page| { + let distance = page.abs_diff(index / config.positions.len()); + distance.min(config.page_count - distance) + }); + (pages as u64) * u64::from(config.page_hold_ms + config.page_wait_ms) + + u64::from(config.move_delay_ms + config.select_hold_ms + config.after_select_ms) + + 30 + } + pub fn prepare( + &mut self, + output: &mut dyn KeyboardOutput, + config: &ChordWheelConfigJson, + processes: &[String], + index: Option, + target_page: usize, + owner: Option, + now: Instant, + ) -> Result<(), String> { + if self.is_active() { + return Err("The chord wheel is busy.".into()); + } + if self.page.is_none() { + return Err("Set the current game page before resuming chord playback.".into()); + } + if target_page >= config.page_count { + return Err("Chord wheel page is unavailable.".into()); + } + if processes.is_empty() { + return Err("The selected game has no process target for chord playback.".into()); + } + output.wheel_move(processes, config.strum_position)?; + let already_selected = index.is_some() && self.selected == index; + if !already_selected { + self.selected = None; + } + self.attack = Some(Attack { + owner, + config: config.clone(), + processes: processes.to_vec(), + target_page, + slot: index.map(|index| index % config.positions.len()), + stage: if already_selected { + Stage::Ready + } else { + Stage::PageDown + }, + at: now, + page_delta: 0, + }); + self.tick(output, now) + } + pub fn tick(&mut self, output: &mut dyn KeyboardOutput, now: Instant) -> Result<(), String> { + let Some(attack) = &mut self.attack else { + return Ok(()); + }; + if !output.wheel_focused() { + return Err("The game lost focus; chord playback was paused.".into()); + } + if now < attack.at { + return Ok(()); + } + // Holds and settle intervals are measured from actual dispatch. + match attack.stage { + Stage::PageDown | Stage::PageWait => { + let page = self.page.ok_or("The current game page is unknown")?; + if page == attack.target_page { + if attack.slot.is_none() { + self.attack = None; + return Ok(()); + } + attack.stage = Stage::Move; + } else { + let count = attack.config.page_count; + let forward = (attack.target_page + count - page) % count; + let backward = (page + count - attack.target_page) % count; + attack.page_delta = if forward <= backward { 1 } else { -1 }; + let stroke = parse_key_stroke( + &attack.config.page_keys[usize::from(attack.page_delta > 0)], + ) + .ok_or("Invalid chord page key")?; + self.page_key = Some(stroke); + for (key, up) in stroke.press_events() { + output.key(key, up)?; + } + attack.stage = Stage::PageUp; + attack.at = now + Duration::from_millis(attack.config.page_hold_ms.into()); + } + } + Stage::PageUp => { + if let Some(stroke) = self.page_key { + output.key(stroke.key, true)?; + } + self.page_key = None; + self.page = self.page.map(|page| { + (page as isize + attack.page_delta) + .rem_euclid(attack.config.page_count as isize) as usize + }); + attack.stage = Stage::PageWait; + attack.at = now + Duration::from_millis(attack.config.page_wait_ms.into()); + } + Stage::Move => { + output.wheel_move( + &attack.processes, + attack.config.positions[attack.slot.unwrap()], + )?; + attack.stage = Stage::SelectDown; + attack.at = now + Duration::from_millis(attack.config.move_delay_ms.into()); + } + Stage::SelectDown => { + self.held = Some(WheelButton::Left); + output.wheel_button(WheelButton::Left, false)?; + attack.stage = Stage::SelectUp; + attack.at = now + Duration::from_millis(attack.config.select_hold_ms.into()); + } + Stage::SelectUp => { + output.wheel_button(WheelButton::Left, true)?; + self.held = None; + self.selected = attack + .slot + .map(|slot| attack.target_page * attack.config.positions.len() + slot); + attack.stage = Stage::Ready; + attack.at = now + Duration::from_millis(attack.config.after_select_ms.into()); + } + Stage::Ready => {} + Stage::StrumUp => { + if self.held == Some(WheelButton::Right) { + output.wheel_button(WheelButton::Right, true)?; + self.held = None; + } + for stroke in &self.held_strings { output.key(stroke.key, true)?; } + self.held_strings.clear(); + self.attack = None; + } + } + Ok(()) + } + pub fn ready(&self, owner: usize, now: Instant) -> bool { + self.attack.as_ref().is_some_and(|attack| { + attack.owner == Some(owner) && matches!(attack.stage, Stage::Ready) && now >= attack.at + }) + } + pub fn strum( + &mut self, + output: &mut dyn KeyboardOutput, + owner: usize, + hold_ms: u64, + now: Instant, + ) -> Result<(), String> { + if !self.ready(owner, now) { + return Err("Chord selection could not finish before the next note. Reduce playback speed or mouse timing.".into()); + } + let attack = self.attack.as_mut().unwrap(); + output.wheel_move(&attack.processes, attack.config.strum_position)?; + self.held = Some(WheelButton::Right); + output.wheel_button(WheelButton::Right, false)?; + attack.stage = Stage::StrumUp; + attack.at = now + Duration::from_millis(hold_ms.max(1)); + Ok(()) + } + pub fn cancel(&mut self, output: &mut dyn KeyboardOutput) -> Result<(), String> { + self.attack = None; + self.selected = None; + let mut error = None; + if let Some(stroke) = self.page_key { + self.page = None; + for key in [ + Some(stroke.key), + stroke.shift.then_some(enigo::Key::Shift), + stroke.control.then_some(enigo::Key::Control), + ] + .into_iter() + .flatten() + { + if let Err(failure) = output.key(key, true) { + error = Some(failure); + } + } + if error.is_none() { + self.page_key = None; + } + } + if let Some(button) = self.held { + match output.wheel_button(button, true) { + Ok(()) => self.held = None, + Err(failure) => error = Some(failure), + } + } + self.held_strings.retain(|stroke| { + match output.key(stroke.key, true) { + Ok(()) => false, + Err(failure) => { error = Some(failure); true } + } + }); + error.map_or(Ok(()), Err) + } + pub fn pluck(&mut self, output: &mut dyn KeyboardOutput, owner: usize, + strokes: &[KeyStroke], hold_ms: u64, now: Instant) -> Result<(), String> { + if !self.ready(owner, now) { return Err("Fret selection could not finish before the next note. Reduce playback speed or input timing.".into()); } + if !output.wheel_focused() { return Err("The game lost focus; fret playback was paused.".into()); } + for &stroke in strokes { + self.held_strings.push(stroke); + for (key, up) in stroke.press_events() { output.key(key, up)?; } + } + let attack = self.attack.as_mut().unwrap(); + attack.stage = Stage::StrumUp; + attack.at = now + Duration::from_millis(hold_ms.max(1)); + Ok(()) + } + pub fn is_active(&self) -> bool { + self.attack.is_some() || self.held.is_some() || self.page_key.is_some() || !self.held_strings.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use enigo::Key; + + #[derive(Debug, PartialEq, Eq)] + enum Event { + Move([u16; 2]), + Key(Key, bool), + Button(WheelButton, bool), + } + + struct Output { + events: Vec, + focused: bool, + fail_release: bool, + } + + impl Default for Output { + fn default() -> Self { + Self { + events: Vec::new(), + focused: true, + fail_release: false, + } + } + } + + impl KeyboardOutput for Output { + fn key(&mut self, key: Key, up: bool) -> Result<(), String> { + self.events.push(Event::Key(key, up)); + Ok(()) + } + + fn wheel_move(&mut self, processes: &[String], point: [u16; 2]) -> Result<(), String> { + assert!(processes.contains(&"HTGame".to_string())); + self.events.push(Event::Move(point)); + Ok(()) + } + + fn wheel_button(&mut self, button: WheelButton, up: bool) -> Result<(), String> { + self.events.push(Event::Button(button, up)); + if up && std::mem::take(&mut self.fail_release) { + Err("release failed".into()) + } else { + Ok(()) + } + } + + fn wheel_focused(&self) -> bool { + self.focused + } + } + + fn config() -> ChordWheelConfigJson { + ChordWheelConfigJson { + positions: vec![ + [500, 100], + [800, 300], + [800, 700], + [500, 900], + [200, 700], + [200, 300], + ], + strum_position: [900, 650], + move_delay_ms: 5, + select_hold_ms: 7, + after_select_ms: 3, + page_count: 4, + page_keys: ["r".into(), "t".into()], + page_hold_ms: 10, + page_wait_ms: 20, + } + } + + fn processes() -> Vec { + let game: crate::input::config::GameConfig = serde_json::from_str(include_str!( + "../../../../src-tauri/resources/defaults/Games/Neverness to Everness/game.json" + )) + .unwrap(); + game.process_names + } + + fn at(start: Instant, ms: u64) -> Instant { + start + Duration::from_millis(ms) + } + fn key(binding: &str) -> Key { + parse_key_stroke(binding).unwrap().key + } + + fn prepare_first_page( + wheel: &mut ChordWheelOutput, + output: &mut Output, + start: Instant, + owner: usize, + ) { + wheel + .prepare( + output, + &config(), + &processes(), + Some(0), + 0, + Some(owner), + start, + ) + .unwrap(); + wheel.tick(output, start).unwrap(); + wheel.tick(output, at(start, 5)).unwrap(); + wheel.tick(output, at(start, 12)).unwrap(); + } + + #[test] + fn page_changes_finish_before_selector_click_and_strum_keeps_its_own_deadline() { + let start = Instant::now(); + let config = config(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + + wheel + .prepare( + &mut output, + &config, + &processes(), + Some(14), + 2, + Some(42), + start, + ) + .unwrap(); + wheel.tick(&mut output, at(start, 9)).unwrap(); + assert_eq!( + output.events, + [ + Event::Move(config.strum_position), + Event::Key(key("t"), false) + ] + ); + wheel.tick(&mut output, at(start, 10)).unwrap(); + assert_eq!(wheel.state().page, Some(1)); + wheel.tick(&mut output, at(start, 29)).unwrap(); + assert_eq!( + output.events.len(), + 3, + "page settle time cannot send another page key early" + ); + wheel.tick(&mut output, at(start, 30)).unwrap(); + wheel.tick(&mut output, at(start, 40)).unwrap(); + assert_eq!(wheel.state().page, Some(2)); + wheel.tick(&mut output, at(start, 60)).unwrap(); + wheel.tick(&mut output, at(start, 60)).unwrap(); + wheel.tick(&mut output, at(start, 65)).unwrap(); + wheel.tick(&mut output, at(start, 72)).unwrap(); + assert!(!wheel.ready(42, at(start, 74))); + assert!(wheel.ready(42, at(start, 75))); + wheel.strum(&mut output, 42, 11, at(start, 75)).unwrap(); + wheel.tick(&mut output, at(start, 85)).unwrap(); + assert!( + wheel.is_active(), + "a source NoteOff must not shorten the mouse hold" + ); + wheel.tick(&mut output, at(start, 86)).unwrap(); + + assert_eq!( + output.events, + [ + Event::Move(config.strum_position), + Event::Key(key("t"), false), + Event::Key(key("t"), true), + Event::Key(key("t"), false), + Event::Key(key("t"), true), + Event::Move(config.positions[2]), + Event::Button(WheelButton::Left, false), + Event::Button(WheelButton::Left, true), + Event::Move(config.strum_position), + Event::Button(WheelButton::Right, false), + Event::Button(WheelButton::Right, true), + ] + ); + assert!(!wheel.is_active()); + } + + #[test] + fn manual_page_changes_take_the_shortest_wrapped_path_without_clicking_or_strumming() { + let start = Instant::now(); + let config = config(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + wheel.assume_page(3); + wheel + .prepare(&mut output, &config, &processes(), None, 0, None, start) + .unwrap(); + for ms in [10, 30, 40, 60, 70, 90] { + wheel.tick(&mut output, at(start, ms)).unwrap(); + } + assert_eq!(wheel.state().page, Some(0)); + assert!(!wheel.is_active()); + assert_eq!( + output.events, + [ + Event::Move(config.strum_position), + Event::Key(key("t"), false), + Event::Key(key("t"), true), + ] + ); + } + + #[test] + fn strums_require_the_prepared_owner_and_the_full_selector_settle_time() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + prepare_first_page(&mut wheel, &mut output, start, 7); + let before = output.events.len(); + assert!(!wheel.ready(7, at(start, 14))); + assert!(!wheel.ready(8, at(start, 15))); + assert!(wheel.strum(&mut output, 7, 10, at(start, 14)).is_err()); + assert!(wheel.strum(&mut output, 8, 10, at(start, 15)).is_err()); + assert_eq!( + output.events.len(), + before, + "an early or unrelated source note cannot send mouse input" + ); + assert!(wheel.strum(&mut output, 7, 10, at(start, 15)).is_ok()); + } + + #[test] + fn cancelling_a_partial_page_releases_the_key_and_requires_page_resynchronization() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + wheel + .prepare( + &mut output, + &config(), + &processes(), + Some(18), + 3, + Some(4), + start, + ) + .unwrap(); + wheel.cancel(&mut output).unwrap(); + assert_eq!(output.events.last(), Some(&Event::Key(key("r"), true))); + assert_eq!(wheel.state().page, None); + assert!(!wheel.is_active()); + let before = output.events.len(); + assert!(wheel + .prepare( + &mut output, + &config(), + &processes(), + Some(0), + 0, + Some(5), + start + ) + .is_err()); + wheel.tick(&mut output, at(start, 1000)).unwrap(); + assert_eq!( + output.events.len(), + before, + "cancelled preparation cannot resume itself" + ); + wheel.assume_page(2); + wheel + .prepare( + &mut output, + &config(), + &processes(), + Some(12), + 2, + Some(5), + start, + ) + .unwrap(); + assert_eq!(wheel.state().page, Some(2)); + } + + #[test] + fn focus_loss_during_selection_and_stop_during_strum_release_the_owned_button() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + wheel + .prepare( + &mut output, + &config(), + &processes(), + Some(0), + 0, + Some(1), + start, + ) + .unwrap(); + wheel.tick(&mut output, start).unwrap(); + wheel.tick(&mut output, at(start, 5)).unwrap(); + output.focused = false; + assert!(wheel + .tick(&mut output, at(start, 6)) + .unwrap_err() + .contains("focus")); + wheel.cancel(&mut output).unwrap(); + assert_eq!( + output.events.last(), + Some(&Event::Button(WheelButton::Left, true)) + ); + assert_eq!(wheel.state().page, Some(0)); + output.focused = true; + prepare_first_page(&mut wheel, &mut output, at(start, 20), 2); + wheel.strum(&mut output, 2, 100, at(start, 35)).unwrap(); + wheel.cancel(&mut output).unwrap(); + assert_eq!( + output.events.last(), + Some(&Event::Button(WheelButton::Right, true)) + ); + let before = output.events.len(); + wheel.tick(&mut output, at(start, 1000)).unwrap(); + assert_eq!(output.events.len(), before); + assert!(!wheel.is_active()); + } + + #[test] + fn failed_mouse_release_stays_owned_until_cleanup_can_retry() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + prepare_first_page(&mut wheel, &mut output, start, 1); + wheel.strum(&mut output, 1, 100, at(start, 15)).unwrap(); + output.fail_release = true; + assert_eq!(wheel.cancel(&mut output).unwrap_err(), "release failed"); + assert!( + wheel.is_active(), + "failed cleanup must retain ownership for retry" + ); + wheel.cancel(&mut output).unwrap(); + assert!(!wheel.is_active()); + assert_eq!( + output + .events + .iter() + .filter(|event| **event == Event::Button(WheelButton::Right, true)) + .count(), + 2 + ); + } + + #[test] + fn late_scheduler_ticks_preserve_minimum_selector_and_mouse_holds() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + wheel + .prepare( + &mut output, + &config(), + &processes(), + Some(0), + 0, + Some(1), + start, + ) + .unwrap(); + wheel.tick(&mut output, start).unwrap(); + wheel.tick(&mut output, at(start, 100)).unwrap(); + let before = output.events.len(); + wheel.tick(&mut output, at(start, 106)).unwrap(); + assert_eq!( + output.events.len(), + before, + "late mouse-down still receives its full hold" + ); + wheel.tick(&mut output, at(start, 107)).unwrap(); + assert!(!wheel.ready(1, at(start, 109))); + wheel.strum(&mut output, 1, 20, at(start, 110)).unwrap(); + wheel.tick(&mut output, at(start, 129)).unwrap(); + assert!(wheel.is_active()); + wheel.tick(&mut output, at(start, 130)).unwrap(); + assert!(!wheel.is_active()); + } + + #[test] + fn repeated_chord_strums_reuse_the_selected_slot_without_another_click() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + prepare_first_page(&mut wheel, &mut output, start, 1); + wheel.strum(&mut output, 1, 10, at(start, 15)).unwrap(); + wheel.tick(&mut output, at(start, 25)).unwrap(); + let before = output.events.len(); + assert_eq!(wheel.preparation_ms(&config(), 0), 2); + wheel + .prepare( + &mut output, + &config(), + &processes(), + Some(0), + 0, + Some(2), + at(start, 30), + ) + .unwrap(); + assert!(wheel.ready(2, at(start, 30))); + wheel.strum(&mut output, 2, 10, at(start, 30)).unwrap(); + assert!(!output.events[before..] + .iter() + .any(|event| matches!(event, Event::Button(WheelButton::Left, _)))); + assert!(output.events[before..].contains(&Event::Button(WheelButton::Right, false))); + } + + #[test] + fn wheel_refuses_input_without_inherited_game_processes() { + let start = Instant::now(); + let mut output = Output::default(); + let mut wheel = ChordWheelOutput::default(); + assert!(wheel + .prepare(&mut output, &config(), &[], Some(0), 0, Some(1), start) + .is_err()); + assert!(output.events.is_empty()); + } +} diff --git a/crates/amp-core/src/input/config.rs b/crates/amp-core/src/input/config.rs index 4c8647ec..77ff4d55 100644 --- a/crates/amp-core/src/input/config.rs +++ b/crates/amp-core/src/input/config.rs @@ -24,12 +24,77 @@ pub struct GameConfig { pub default_layout: Option, } -/// Pre-composed chord pad definition on an instrument +/// Pre-composed chord shared by pad, wheel, and guitar presentations. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ChordPadConfigJson { +pub struct ChordConfigJson { pub name: String, pub pitch_classes: Vec, + #[serde(default)] + pub bass_pitch_class: Option, +} + +/// Guitar pitch data belongs to the instrument, not its physical controls. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GuitarConfigJson { + /// Open-string MIDI pitches, ordered from highest to lowest string. + pub tuning: Vec, + pub fret_count: u8, +} + +impl GuitarConfigJson { + pub fn is_valid(&self) -> bool { + !self.tuning.is_empty() && self.tuning.len() <= 6 && self.fret_count > 0 + && self.tuning.iter().all(|pitch| u16::from(*pitch) + u16::from(self.fret_count) <= 127) + } +} + +/// String and mode bindings reuse an existing wheel layout's calibration. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FretLayoutJson { + pub string_keys: Vec, + pub wheel_layout: String, + pub mode_key: String, +} + +impl FretLayoutJson { + pub fn is_valid(&self) -> bool { + !self.wheel_layout.trim().is_empty() && !self.string_keys.is_empty() && self.string_keys.len() <= 6 + && self.string_keys.iter().all(|binding| super::mapping::parse_key_stroke(binding).is_some()) + && super::mapping::parse_key_stroke(&self.mode_key).is_some() + } +} + +/// Mouse positions are thousandths of the game window's client area. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChordWheelConfigJson { + pub positions: Vec<[u16; 2]>, + pub strum_position: [u16; 2], + pub move_delay_ms: u16, + pub select_hold_ms: u16, + pub after_select_ms: u16, + pub page_count: usize, + pub page_keys: [String; 2], + pub page_hold_ms: u16, + pub page_wait_ms: u16, +} + +impl ChordWheelConfigJson { + pub fn is_valid(&self) -> bool { + !self.positions.is_empty() + && self.positions.iter().chain(std::iter::once(&self.strum_position)) + .flatten().all(|&coordinate| coordinate <= 1000) + && (1..=1000).contains(&self.move_delay_ms) + && (1..=1000).contains(&self.select_hold_ms) + && (1..=1000).contains(&self.after_select_ms) + && (1..=12).contains(&self.page_count) + && self.page_keys.iter().all(|key| super::mapping::parse_key_stroke(key).is_some()) + && (1..=1000).contains(&self.page_hold_ms) + && (1..=1000).contains(&self.page_wait_ms) + } } /// Visual appearance is independent of the playable pitch set and keyboard bindings. @@ -40,6 +105,7 @@ pub enum InstrumentLayoutStyle { Genshin, Heartopia, Drums, + Guitar, None, } @@ -61,9 +127,17 @@ pub struct InstrumentConfigJson { #[serde(default)] pub notes: Vec, #[serde(default)] - pub supported_layouts: Vec, + pub keyboard_layouts: Vec, + #[serde(default)] + pub chord_layouts: Vec, #[serde(default)] - pub chord_pads: Vec, + pub fret_layouts: Vec, + #[serde(default)] + pub chords: Vec, + #[serde(default)] + pub guitar: Option, + #[serde(default)] + pub chord_mode: ChordMode, #[serde(default)] pub supports_pedals: Option, #[serde(default)] @@ -77,6 +151,22 @@ pub struct InstrumentConfigJson { } impl InstrumentConfigJson { + pub fn all_layouts(&self) -> impl Iterator { + self.keyboard_layouts.iter().chain(&self.chord_layouts).chain(&self.fret_layouts) + } + + pub fn supports_keyboard_layout(&self, id: &str) -> bool { + self.keyboard_layouts.iter().any(|layout| layout.eq_ignore_ascii_case(id)) + } + + pub fn supports_chord_layout(&self, id: &str) -> bool { + self.chord_layouts.iter().any(|layout| layout.eq_ignore_ascii_case(id)) + } + + pub fn supports_fret_layout(&self, id: &str) -> bool { + self.fret_layouts.iter().any(|layout| layout.eq_ignore_ascii_case(id)) + } + pub fn normalize_keys(&mut self) { if let Some(rows) = &self.keys { self.notes = rows.iter().flatten().filter_map(|pitch| *pitch).collect(); @@ -100,9 +190,20 @@ struct InstrumentConfigSource { #[serde(default)] notes: Vec, #[serde(default)] + keyboard_layouts: Option>, + #[serde(default)] + chord_layouts: Option>, + #[serde(default)] + fret_layouts: Vec, + /// Read compatibility for existing app-data JSON; never serialized. + #[serde(default)] supported_layouts: Vec, + #[serde(default, alias = "chordPads")] + chords: Vec, + #[serde(default)] + guitar: Option, #[serde(default)] - chord_pads: Vec, + chord_mode: ChordMode, #[serde(default)] supports_pedals: Option, #[serde(default)] @@ -115,9 +216,15 @@ struct InstrumentConfigSource { impl From for InstrumentConfigJson { fn from(source: InstrumentConfigSource) -> Self { + // Old definitions used one list for melody and chords. An explicit new + // chordLayouts array, including [], is always authoritative. + let chord_layouts = source.chord_layouts.unwrap_or_else(|| { + if source.chords.is_empty() { Vec::new() } else { source.supported_layouts.clone() } + }); let mut instrument = Self { id: source.id, name: source.name, category: source.category, instrument_type: source.instrument_type, layout_style: source.layout_style, keys: source.keys, - notes: source.notes, supported_layouts: source.supported_layouts, chord_pads: source.chord_pads, + notes: source.notes, keyboard_layouts: source.keyboard_layouts.unwrap_or(source.supported_layouts), + chord_layouts, fret_layouts: source.fret_layouts, chords: source.chords, guitar: source.guitar, chord_mode: source.chord_mode, supports_pedals: source.supports_pedals, supports_chords: source.supports_chords, subfolder: source.subfolder, file_path: source.file_path }; instrument.normalize_keys(); @@ -125,6 +232,15 @@ impl From for InstrumentConfigJson { } } +/// Physical chord interaction selected by the instrument; detection is shared. +#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum ChordMode { + #[default] + Pads, + Wheel, +} + /// Modular keyboard layout stored in `KeyboardLayouts/*.json` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase", from = "KeyboardLayoutSource")] @@ -140,6 +256,10 @@ pub struct KeyboardLayoutJson { #[serde(default)] pub chord_keys: Option>, #[serde(default)] + pub chord_wheel: Option, + #[serde(default)] + pub fretboard: Option, + #[serde(default)] pub sustain_key: Option, #[serde(default)] pub sostenuto_key: Option, @@ -172,6 +292,10 @@ struct KeyboardLayoutSource { #[serde(default)] chord_keys: Option>, #[serde(default)] + chord_wheel: Option, + #[serde(default)] + fretboard: Option, + #[serde(default)] sustain_key: Option, #[serde(default)] sostenuto_key: Option, @@ -189,7 +313,7 @@ impl From for KeyboardLayoutJson { } }; Self { id: source.id, name: source.name, file_path: source.file_path, keys, key_rows, - chord_keys: source.chord_keys, sustain_key: source.sustain_key, + chord_keys: source.chord_keys, chord_wheel: source.chord_wheel, fretboard: source.fretboard, sustain_key: source.sustain_key, sostenuto_key: source.sostenuto_key, una_corda_key: source.una_corda_key } } } diff --git a/crates/amp-core/src/input/config_scan.rs b/crates/amp-core/src/input/config_scan.rs index efe86f33..ae690f47 100644 --- a/crates/amp-core/src/input/config_scan.rs +++ b/crates/amp-core/src/input/config_scan.rs @@ -74,6 +74,14 @@ pub fn scan_layouts_checked(dir: &Path) -> (HashMap, issue(&mut issues, &path, "Layout name and key bindings must not be empty"); continue; } + if layout.chord_wheel.as_ref().is_some_and(|wheel| !wheel.is_valid()) { + issue(&mut issues, &path, "Chord wheel requires positions between 0 and 1000 and delays between 1 and 1000 ms"); + continue; + } + if layout.fretboard.as_ref().is_some_and(|fret| !fret.is_valid()) { + issue(&mut issues, &path, "Fret bindings require string keys, a wheel layout reference, and a mode key"); + continue; + } let id = layout.id.to_lowercase(); for alias in [&id, &stem] { if let Some(first) = aliases.get(alias) { @@ -85,6 +93,14 @@ pub fn scan_layouts_checked(dir: &Path) -> (HashMap, layouts.insert(id, layout.clone()); layouts.entry(stem).or_insert(layout); } + for layout in layouts.values() { + if let Some(fret) = &layout.fretboard { + if !layouts.get(&fret.wheel_layout.to_lowercase()).is_some_and(|wheel| wheel.chord_wheel.is_some()) { + issue(&mut issues, Path::new(layout.file_path.as_deref().unwrap_or("")), + format!("Fret wheel layout '{}' is missing or has no chordWheel bindings", fret.wheel_layout)); + } + } + } (layouts, issues) } @@ -115,6 +131,14 @@ pub fn scan_games_checked(dir: &Path) -> (Vec, Vec(path, &mut issues) else { continue; }; + if inst.guitar.as_ref().is_some_and(|guitar| !guitar.is_valid()) { + issue(&mut issues, path, "Guitar tuning and fret count must produce valid MIDI pitches on one to six strings"); + continue; + } + if !inst.fret_layouts.is_empty() && inst.guitar.is_none() { + issue(&mut issues, path, "Fret layouts require guitar tuning and fret count"); + continue; + } if inst.keys.as_ref().is_some_and(|rows| rows.is_empty() || rows.iter().any(|row| row.is_empty()) || inst.notes.is_empty()) { issue(&mut issues, path, "Instrument keys must contain non-empty rows and at least one MIDI note"); continue; diff --git a/crates/amp-core/src/input/defaults_sync.rs b/crates/amp-core/src/input/defaults_sync.rs new file mode 100644 index 00000000..c42418b4 --- /dev/null +++ b/crates/amp-core/src/input/defaults_sync.rs @@ -0,0 +1,677 @@ +//! Install new bundled files and review replacements without overwriting local JSON. +use super::config_scan::ConfigIssue; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, HashSet}; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Component, Path, PathBuf}; +use walkdir::WalkDir; + +const MANIFEST: &str = "configuration-state.json"; +const LEGACY_MANIFEST: &str = ".bundled-defaults.json"; + +pub struct BundledDefault<'a> { + pub path: &'a Path, + pub contents: &'a [u8], +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DefaultConfigConflict { + pub id: String, + pub path: String, + pub kind: String, + pub name: String, + pub current_json: String, + pub bundled_json: String, + /// Binds consent to the exact file contents shown in the review. + pub token: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DefaultConfigUpdates { + pub added_files: Vec, + pub conflicts: Vec, + pub duplicates: Vec, + pub issues: Vec, + pub backup_directory: Option, +} + +impl DefaultConfigUpdates { + pub fn needs_review(&self) -> bool { + !self.conflicts.is_empty() || !self.duplicates.is_empty() || !self.issues.is_empty() + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DuplicateConfigFile { + pub path: String, + pub json: String, + pub modified_ms: u64, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DuplicateConfig { + pub id: String, + pub config_id: String, + pub kind: String, + pub keep: DuplicateConfigFile, + pub older_files: Vec, + pub token: String, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum DefaultConfigAction { + Keep, + Replace, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DefaultConfigChoice { + pub id: String, + pub token: String, + pub action: DefaultConfigAction, +} + +// Consent only applies to the local contents and bundled revision actually reviewed. +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum ReviewedDefault { + Current { bundled: String, local: String }, + // Older history did not bind decisions to local contents; re-review differences. + Legacy(String), +} +type Manifest = BTreeMap; + +fn reviewed(bundled: String, local: String) -> ReviewedDefault { + ReviewedDefault::Current { bundled, local } +} + +fn local_revision(bytes: &[u8]) -> String { + json_revision(bytes).unwrap_or_else(|_| digest(bytes)) +} + +fn digest(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn json_revision(bytes: &[u8]) -> Result { + let value: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?; + Ok(digest( + &serde_json::to_vec(&value).map_err(|e| e.to_string())?, + )) +} + +fn relative(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +/// Even registered destinations may have been replaced with symlinks on disk. +fn contained_path(root: &Path, relative: &Path) -> Result { + if relative.as_os_str().is_empty() + || relative + .components() + .any(|c| !matches!(c, Component::Normal(_))) + { + return Err("Invalid default configuration path".into()); + } + let base = root.canonicalize().map_err(|e| e.to_string())?; + let mut path = root.to_path_buf(); + for part in relative.components() { + path.push(part); + match fs::symlink_metadata(&path) { + Ok(meta) => { + if meta.file_type().is_symlink() + || !path + .canonicalize() + .map_err(|e| e.to_string())? + .starts_with(&base) + { + return Err(format!( + "Configuration path leaves app data or uses a symlink: {}", + path.display() + )); + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.to_string()), + } + } + Ok(path) +} + +fn stamp() -> Result { + Ok(format!( + "{}-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| e.to_string())? + .as_nanos(), + std::process::id() + )) +} + +fn write_new(path: &Path, contents: &[u8]) -> Result<(), String> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| e.to_string())?; + if let Err(e) = file.write_all(contents).and_then(|_| file.sync_all()) { + drop(file); + let _ = fs::remove_file(path); + return Err(e.to_string()); + } + Ok(()) +} + +fn write_atomic(path: &Path, contents: &[u8]) -> Result<(), String> { + let temporary = path.with_file_name(format!(".default-sync-{}.tmp", stamp()?)); + write_new(&temporary, contents)?; + let result = fs::rename(&temporary, path).map_err(|e| e.to_string()); + if result.is_err() { + let _ = fs::remove_file(temporary); + } + result +} + +fn read_manifest(root: &Path) -> Result { + let path = contained_path(root, Path::new(MANIFEST))?; + let bytes = match fs::read(path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + fs::read(contained_path(root, Path::new(LEGACY_MANIFEST))?) + } + result => result, + }; + match bytes { + Ok(bytes) => serde_json::from_slice(&bytes) + .map_err(|e| format!("Cannot read default configuration history: {e}")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Manifest::new()), + Err(e) => Err(e.to_string()), + } +} + +fn save_manifest(root: &Path, manifest: &Manifest) -> Result<(), String> { + let bytes = serde_json::to_vec_pretty(manifest).map_err(|e| e.to_string())?; + let path = contained_path(root, Path::new(MANIFEST))?; + if fs::read(&path).ok().as_deref() != Some(bytes.as_slice()) { + write_atomic(&path, &bytes)?; + } + // Remove the former filename only after the new state has been saved safely. + let legacy = contained_path(root, Path::new(LEGACY_MANIFEST))?; + match fs::remove_file(legacy) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.to_string()), + } + Ok(()) +} + +/// Only used after an explicit full configuration reset, including to recover corrupt history. +pub fn reset_default_history(root: &Path) -> Result<(), String> { + save_manifest(root, &Manifest::new()) +} + +/// An explicit in-app edit can advance an already-reviewed local baseline. +/// Do not acknowledge unrelated external edits or a pending bundled update. +pub fn record_reviewed_edit( + root: &Path, + bundled_path: &Path, + before: &[u8], + after: &[u8], +) -> Result<(), String> { + let mut manifest = read_manifest(root)?; + if let Some(ReviewedDefault::Current { local, .. }) = manifest.get_mut(&relative(bundled_path)) + { + if *local == local_revision(before) { + *local = local_revision(after); + save_manifest(root, &manifest)?; + } + } + Ok(()) +} + +fn kind(path: &Path) -> Option<(&'static str, String)> { + let parts: Vec<_> = path.iter().filter_map(|s| s.to_str()).collect(); + if !path + .extension() + .is_some_and(|s| s.eq_ignore_ascii_case("json")) + { + return None; + } + match parts.as_slice() { + ["KeyboardLayouts", _] => Some(("layout", "layouts".into())), + ["Games", _, _] => Some(("game", "games".into())), + ["Games", game, "Instruments", ..] => { + Some(("instrument", format!("instruments/{}", game.to_lowercase()))) + } + _ => None, + } +} + +struct Existing { + path: PathBuf, + document: Option, + contents: Vec, + modified_ms: u64, +} + +fn modified_ms(path: &Path) -> u64 { + fs::metadata(path) + .and_then(|meta| meta.modified()) + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|duration| duration.as_millis().min(u64::MAX as u128) as u64) + .unwrap_or(0) +} + +fn duplicate_configs(files: &[Existing]) -> Vec { + let mut groups: BTreeMap> = BTreeMap::new(); + for file in files { + let Some((category, scope)) = kind(&file.path) else { + continue; + }; + let Some(document) = &file.document else { + continue; + }; + let id = field(document, "id").or_else(|| { + (category == "layout") + .then(|| { + file.path + .file_stem() + .map(|stem| stem.to_string_lossy().to_lowercase()) + }) + .flatten() + }); + if let Some(id) = id { + groups + .entry(format!("{category}/{scope}/{id}")) + .or_default() + .push(file); + } + } + groups + .into_iter() + .filter_map(|(id, mut files)| { + if files.len() < 2 { + return None; + } + // Millisecond ties use path order deterministically. The review always names the survivor. + files.sort_by(|a, b| { + b.modified_ms + .cmp(&a.modified_ms) + .then_with(|| a.path.cmp(&b.path)) + }); + let config_id = files[0] + .document + .as_ref() + .and_then(|doc| doc.get("id")) + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| { + files[0] + .path + .file_stem() + .unwrap() + .to_string_lossy() + .into_owned() + }); + let token = digest( + &serde_json::to_vec( + &files + .iter() + .map(|file| { + ( + relative(&file.path), + digest(&file.contents), + file.modified_ms, + ) + }) + .collect::>(), + ) + .unwrap(), + ); + let convert = |file: &Existing| DuplicateConfigFile { + path: relative(&file.path), + json: String::from_utf8_lossy(&file.contents).into_owned(), + modified_ms: file.modified_ms, + }; + Some(DuplicateConfig { + id: format!("duplicate/{id}"), + config_id, + kind: kind(&files[0].path).unwrap().0.into(), + keep: convert(files[0]), + older_files: files[1..].iter().map(|file| convert(file)).collect(), + token, + }) + }) + .collect() +} + +fn existing_json(root: &Path) -> Result, String> { + let mut files = Vec::new(); + for folder in ["Games", "KeyboardLayouts"] { + let directory = contained_path(root, Path::new(folder))?; + if !directory.exists() { + continue; + } + for entry in WalkDir::new(directory).sort_by_file_name() { + let entry = entry.map_err(|e| e.to_string())?; + let path = entry.path().strip_prefix(root).map_err(|e| e.to_string())?; + if kind(path).is_none() || entry.file_type().is_dir() { + continue; + } + let full = contained_path(root, path)?; + let bytes = + fs::read(&full).map_err(|e| format!("Cannot read {}: {e}", full.display()))?; + files.push(Existing { + path: path.to_path_buf(), + document: serde_json::from_slice(&bytes).ok(), + contents: bytes, + modified_ms: modified_ms(&full), + }); + } + } + Ok(files) +} + +fn field(value: &Value, key: &str) -> Option { + value + .get(key) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_lowercase) +} + +fn aliases(path: &Path, document: &Value) -> HashSet { + [ + field(document, "id"), + path.file_stem() + .and_then(|s| s.to_str()) + .map(str::to_lowercase), + ] + .into_iter() + .flatten() + .collect() +} + +fn destination( + file: &BundledDefault<'_>, + document: &Value, + files: &[Existing], +) -> Result { + let scope = kind(file.path).ok_or("Unsupported bundled configuration path")?; + let mut candidates: Vec<_> = files + .iter() + .filter(|other| { + if other.path == file.path { + return true; + } + if kind(&other.path).as_ref() != Some(&scope) { + return false; + } + let Some(value) = &other.document else { + return false; + }; + if scope.0 == "layout" { + return !aliases(file.path, document).is_disjoint(&aliases(&other.path, value)); + } + field(document, "id").is_some_and(|id| field(value, "id") == Some(id)) + || field(document, "name") + .or_else(|| field(document, "displayName")) + .is_some_and(|name| { + field(value, "name").or_else(|| field(value, "displayName")) == Some(name) + }) + }) + .collect(); + candidates.sort_by(|a, b| { + b.modified_ms + .cmp(&a.modified_ms) + .then_with(|| a.path.cmp(&b.path)) + }); + match candidates.as_slice() { + [] => Ok(file.path.to_path_buf()), + [existing] => Ok(existing.path.clone()), + [newest, ..] if field(document, "id").is_some_and(|id| candidates.iter() + .all(|file| file.document.as_ref().and_then(|doc| field(doc, "id")) == Some(id.clone()))) => Ok(newest.path.clone()), + _ => Err(format!("Multiple existing files conflict with {}. Resolve the duplicate IDs or names before updating defaults.", file.path.display())), + } +} + +fn consent_token(id: &str, path: &str, current: &[u8], bundled: &[u8]) -> String { + digest( + &serde_json::to_vec(&(id, path, digest(current), digest(bundled))) + .expect("string tuple serialization"), + ) +} + +/// New files are installed on every launch. Existing JSON is only proposed for review. +pub fn sync_defaults( + root: &Path, + bundled: &[BundledDefault<'_>], +) -> Result { + fs::create_dir_all(root).map_err(|e| e.to_string())?; + let mut manifest = read_manifest(root)?; + let mut existing = existing_json(root)?; + // If a game folder was renamed, its new instruments and assets must still + // go beside the existing game JSON, rather than into an orphaned folder. + let game_folders: Vec<_> = bundled + .iter() + .filter(|file| kind(file.path).is_some_and(|(kind, _)| kind == "game")) + .filter_map(|file| { + let document = serde_json::from_slice::(file.contents).ok()?; + let target = destination(file, &document, &existing).ok()?; + let source_parent = file.path.parent()?; + let target_parent = target.parent()?; + (source_parent != target_parent) + .then(|| (source_parent.to_path_buf(), target_parent.to_path_buf())) + }) + .collect(); + let mut report = DefaultConfigUpdates { + added_files: Vec::new(), + conflicts: Vec::new(), + duplicates: Vec::new(), + issues: Vec::new(), + backup_directory: None, + }; + for file in bundled { + let id = relative(file.path); + let mapped_path = game_folders + .iter() + .find_map(|(source, target)| { + file.path + .strip_prefix(source) + .ok() + .map(|suffix| target.join(suffix)) + }) + .unwrap_or_else(|| file.path.to_path_buf()); + let file = &BundledDefault { + path: &mapped_path, + contents: file.contents, + }; + let Some((category, _)) = kind(file.path) else { + // Icons and other bundled assets are copied only when absent. + let path = contained_path(root, file.path)?; + if !path.exists() { + write_new(&path, file.contents)?; + } + continue; + }; + let document: Value = serde_json::from_slice(file.contents) + .map_err(|e| format!("Invalid bundled {id}: {e}"))?; + let revision = json_revision(file.contents)?; + let destination = match destination(file, &document, &existing) { + Ok(path) => path, + Err(message) => { + report.issues.push(ConfigIssue { path: id, message }); + continue; + } + }; + let path = contained_path(root, &destination)?; + if !path.exists() { + write_new(&path, file.contents).map_err(|e| format!("Cannot add {id}: {e}"))?; + existing.push(Existing { + path: destination, + document: Some(document), + contents: file.contents.to_vec(), + modified_ms: modified_ms(&path), + }); + report.added_files.push(id.clone()); + manifest.insert(id, reviewed(revision.clone(), revision)); + continue; + } + let current = fs::read(&path).map_err(|e| format!("Cannot read {id}: {e}"))?; + let local = local_revision(¤t); + if local == revision { + manifest.insert(id, reviewed(revision.clone(), revision)); + } else if !matches!(manifest.get(&id), Some(ReviewedDefault::Current { bundled, local: previous }) + if bundled == &revision && previous == &local) + { + let target = relative(&destination); + report.conflicts.push(DefaultConfigConflict { + token: consent_token(&id, &target, ¤t, file.contents), + id, + path: target, + kind: category.into(), + name: document + .get("name") + .or_else(|| document.get("displayName")) + .and_then(Value::as_str) + .unwrap_or("Configuration") + .into(), + current_json: String::from_utf8_lossy(¤t).into_owned(), + bundled_json: String::from_utf8_lossy(file.contents).into_owned(), + }); + } + } + report.duplicates = duplicate_configs(&existing); + save_manifest(root, &manifest)?; + Ok(report) +} + +pub fn resolve_default_updates( + root: &Path, + bundled: &[BundledDefault<'_>], + choices: &[DefaultConfigChoice], + duplicate_choices: &[DefaultConfigChoice], +) -> Result { + let report = sync_defaults(root, bundled)?; + let mut selected = HashSet::new(); + // Validate the entire batch before replacing anything. + for choice in choices { + if !selected.insert(&choice.id) { + return Err("Duplicate default configuration choice".into()); + } + if !report + .conflicts + .iter() + .any(|c| c.id == choice.id && c.token == choice.token) + { + return Err("Configurations changed since this review. Review the latest files before applying your choices.".into()); + } + } + for choice in duplicate_choices { + if !selected.insert(&choice.id) { + return Err("Duplicate default configuration choice".into()); + } + if !report + .duplicates + .iter() + .any(|duplicate| duplicate.id == choice.id && duplicate.token == choice.token) + { + return Err("Duplicate files changed since this review. Review the latest files before deleting older copies.".into()); + } + } + let mut manifest = read_manifest(root)?; + let mut backup_directory: Option = None; + for choice in duplicate_choices + .iter() + .filter(|choice| choice.action == DefaultConfigAction::Replace) + { + let duplicate = report + .duplicates + .iter() + .find(|duplicate| duplicate.id == choice.id) + .unwrap(); + // Recheck every copy before deleting any member of this group. + for file in std::iter::once(&duplicate.keep).chain(&duplicate.older_files) { + let path = contained_path(root, Path::new(&file.path))?; + if fs::read(&path).map_err(|e| e.to_string())? != file.json.as_bytes() { + return Err(format!( + "{} changed during review. Check the duplicate files again.", + file.path + )); + } + } + for file in &duplicate.older_files { + let directory = backup_directory.get_or_insert(format!("ConfigBackups/{}", stamp()?)); + let backup = contained_path(root, &Path::new(directory).join(&file.path))?; + write_new(&backup, file.json.as_bytes()) + .map_err(|e| format!("Cannot back up {}: {e}", file.path))?; + let path = contained_path(root, Path::new(&file.path))?; + fs::remove_file(path) + .map_err(|e| format!("Cannot delete older duplicate {}: {e}", file.path))?; + } + } + for choice in choices { + let conflict = report + .conflicts + .iter() + .find(|c| c.id == choice.id) + .expect("validated conflict"); + let file = bundled + .iter() + .find(|f| relative(f.path) == choice.id) + .expect("registered default"); + let path = contained_path(root, Path::new(&conflict.path))?; + let current = fs::read(&path).map_err(|e| e.to_string())?; + if consent_token(&conflict.id, &conflict.path, ¤t, file.contents) != choice.token { + return Err(format!( + "{} changed during review. Reload the comparison before replacing it.", + conflict.path + )); + } + if choice.action == DefaultConfigAction::Replace { + let directory = match &backup_directory { + Some(directory) => directory.clone(), + None => format!("ConfigBackups/{}", stamp()?), + }; + let backup = contained_path(root, &Path::new(&directory).join(&conflict.path))?; + write_new(&backup, ¤t) + .map_err(|e| format!("Cannot back up {}: {e}", conflict.path))?; + backup_directory = Some(directory); + write_atomic(&path, file.contents) + .map_err(|e| format!("Cannot replace {}: {e}", conflict.path))?; + } + manifest.insert( + choice.id.clone(), + reviewed( + json_revision(file.contents)?, + local_revision(if choice.action == DefaultConfigAction::Replace { + file.contents + } else { + ¤t + }), + ), + ); + // Persist each successful choice so a later failure never repeats an approved replacement. + save_manifest(root, &manifest)?; + } + let mut remaining = sync_defaults(root, bundled)?; + remaining.added_files = report.added_files; + remaining.backup_directory = backup_directory; + Ok(remaining) +} diff --git a/crates/amp-core/src/input/mapping.rs b/crates/amp-core/src/input/mapping.rs index 5bf2265f..ab0b1dba 100644 --- a/crates/amp-core/src/input/mapping.rs +++ b/crates/amp-core/src/input/mapping.rs @@ -13,7 +13,23 @@ pub struct KeyStroke { #[derive(Debug, Clone, PartialEq, Eq)] pub struct ChordPad { pub pitch_classes: Vec, - pub stroke: KeyStroke, + pub binding: ChordBinding, + pub bass_pitch_class: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChordBinding { + Key(KeyStroke), + Wheel(usize), + Frets { slot: usize, strings: u8 }, +} + +#[derive(Debug, Clone)] +pub struct FretMapping { + pub tuning: Vec, + pub fret_count: u8, + pub string_strokes: Vec, + pub mode_key: Option, } impl KeyStroke { @@ -101,6 +117,10 @@ pub struct NoteKeyMapping { playable_notes: Vec, pedal_bindings: [Option; 3], chord_pads: Vec, + chord_wheel: Option, + frets: Option, + game_process_names: Vec, + game_target_id: Option, } impl NoteKeyMapping { @@ -180,6 +200,10 @@ impl NoteKeyMapping { playable_notes, pedal_bindings: [None; 3], chord_pads: Vec::new(), + chord_wheel: None, + frets: None, + game_process_names: Vec::new(), + game_target_id: None, } } @@ -207,6 +231,10 @@ impl NoteKeyMapping { playable_notes, pedal_bindings: [None; 3], chord_pads: Vec::new(), + chord_wheel: None, + frets: None, + game_process_names: Vec::new(), + game_target_id: None, } } @@ -226,26 +254,101 @@ impl NoteKeyMapping { pub fn with_chord_bindings(mut self, pads: Vec) -> Self { self.chord_pads = pads; + self.chord_wheel = None; + self.frets = None; self } - pub fn with_chord_pads(self, instrument: &super::config::InstrumentConfigJson, layout: &super::config::KeyboardLayoutJson) -> Self { - if instrument.supports_chords == Some(false) - || (!instrument.supported_layouts.is_empty() - && !instrument.supported_layouts.iter().any(|id| id.eq_ignore_ascii_case(&layout.id))) { + pub fn with_chord_pads(mut self, instrument: &super::config::InstrumentConfigJson, layout: &super::config::KeyboardLayoutJson) -> Self { + if instrument.supports_chords == Some(false) || !instrument.supports_chord_layout(&layout.id) { return self.with_chord_bindings(Vec::new()); } - let pads = instrument.chord_pads.iter().zip(layout.chord_keys.iter().flatten()) - .filter_map(|(pad, binding)| { - let stroke = parse_key_stroke(binding)?; + let wheel = (instrument.chord_mode == super::config::ChordMode::Wheel) + .then(|| layout.chord_wheel.as_ref().filter(|wheel| wheel.is_valid())).flatten(); + if instrument.chord_mode == super::config::ChordMode::Wheel && wheel.is_none() { return self.with_chord_bindings(Vec::new()); } + let pads = instrument.chords.iter().enumerate() + .filter_map(|(index, pad)| { + let binding = if let Some(wheel) = wheel { + if index >= wheel.positions.len() * wheel.page_count { return None; } + ChordBinding::Wheel(index) + } else { + ChordBinding::Key(parse_key_stroke(layout.chord_keys.as_ref()?.get(index)?)?) + }; if pad.pitch_classes.iter().any(|&pitch| pitch > 11) - || pad.pitch_classes.iter().copied().collect::>().len() < 3 { return None; } - Some(ChordPad { pitch_classes: pad.pitch_classes.clone(), stroke }) + || pad.bass_pitch_class.is_some_and(|pitch| pitch > 11) + || pad.pitch_classes.iter().copied().collect::>().len() < 2 { return None; } + Some(ChordPad { pitch_classes: pad.pitch_classes.clone(), binding, bass_pitch_class: pad.bass_pitch_class }) }).collect(); - self.with_chord_bindings(pads) + self = self.with_chord_bindings(pads); + // Pad-only layouts still need the instrument's pitch set for chord + // detection and adapted listening, without acquiring melody key output. + if self.map.is_empty() { + self.playable_notes = instrument.notes.clone(); + self.playable_notes.sort_unstable(); + self.playable_notes.dedup(); + } + if let Some(wheel) = wheel { + self.chord_wheel = Some(wheel.clone()); + // Chord mode has no chromatic keys. Keep its pitch set for detection + // and Listen Mode without sending piano-mode keys for unmatched notes. + self.map.clear(); + self.playable_notes = instrument.notes.clone(); + self.playable_notes.sort_unstable(); + self.playable_notes.dedup(); + } + self } pub fn chord_pads(&self) -> &[ChordPad] { &self.chord_pads } + pub fn has_playable_bindings(&self) -> bool { + !self.map.is_empty() || !self.chord_pads.is_empty() || self.frets.is_some() + } + pub fn chord_wheel(&self) -> Option<&super::config::ChordWheelConfigJson> { self.chord_wheel.as_ref() } + pub fn frets(&self) -> Option<&FretMapping> { self.frets.as_ref() } + + pub fn with_frets(mut self, instrument: &super::config::InstrumentConfigJson, + layout: &super::config::KeyboardLayoutJson, wheel: &super::config::ChordWheelConfigJson) -> Self { + self = self.with_chord_bindings(Vec::new()); + self.map.clear(); + self.playable_notes.clear(); + let Some(guitar) = instrument.guitar.as_ref().filter(|guitar| guitar.is_valid()) else { return self; }; + let Some(fretboard) = layout.fretboard.as_ref().filter(|fretboard| fretboard.is_valid()) else { return self; }; + if !instrument.supports_fret_layout(&layout.id) || !wheel.is_valid() + || fretboard.string_keys.len() != guitar.tuning.len() { return self; } + let Some(strokes) = fretboard.string_keys.iter().map(|binding| parse_key_stroke(binding)) + .collect::>>() else { return self; }; + // One held selector applies to all six strings in the reference game. + // The last page contains the open-string selector; frets start at slot 0. + let mut resolved_wheel = wheel.clone(); + resolved_wheel.page_count = (guitar.fret_count as usize).div_ceil(wheel.positions.len()) + 1; + self.chord_wheel = Some(resolved_wheel); + self.playable_notes = guitar.tuning.iter().flat_map(|pitch| *pitch..=(*pitch + guitar.fret_count)).collect(); + self.playable_notes.sort_unstable(); + self.playable_notes.dedup(); + self.frets = Some(FretMapping { tuning: guitar.tuning.clone(), fret_count: guitar.fret_count, + string_strokes: strokes, mode_key: parse_key_stroke(&fretboard.mode_key) }); + self + } + + /// Runtime target inherited from the owning game's definition and preferences. + /// Layout files contain controls only, never executable metadata. + pub fn with_game_process_names(mut self, names: &[String]) -> Self { + self.game_process_names = names.to_vec(); + self + } + + pub fn game_process_names(&self) -> &[String] { &self.game_process_names } + + pub fn with_game_target(mut self, game: &super::config::GameConfig) -> Self { + self.game_target_id = Some(game.id.clone()); + self.game_process_names = game.process_names.clone(); + self + } + + pub fn wheel_context(&self) -> Option { + self.chord_wheel.as_ref().map(|wheel| format!("{}:{}:{}", self.game_target_id.as_deref().unwrap_or(""), + self.game_process_names.join("|"), serde_json::to_string(wheel).unwrap_or_default())) + } /// Resolves a MIDI note to an Enigo physical Key, if mapped. pub fn get_key(&self, note: u8) -> Option { @@ -277,7 +380,9 @@ impl NoteKeyMapping { pub fn all_keys(&self) -> Vec { let mut keys = HashSet::new(); for stroke in self.map.values().chain(self.pedal_bindings.iter().flatten()) - .chain(self.chord_pads.iter().map(|pad| &pad.stroke)) { + .chain(self.chord_pads.iter().filter_map(|pad| match &pad.binding { + ChordBinding::Key(stroke) => Some(stroke), ChordBinding::Wheel(_) | ChordBinding::Frets { .. } => None, + })).chain(self.frets.iter().flat_map(|frets| &frets.string_strokes)) { keys.insert(stroke.key); if stroke.shift { keys.insert(Key::Shift); } if stroke.control { keys.insert(Key::Control); } diff --git a/crates/amp-core/src/input/mod.rs b/crates/amp-core/src/input/mod.rs index 2122491b..c6245fd4 100644 --- a/crates/amp-core/src/input/mod.rs +++ b/crates/amp-core/src/input/mod.rs @@ -1,10 +1,12 @@ pub mod config; pub mod config_scan; +pub mod defaults_sync; pub mod mapping; pub mod simulator; +pub mod chord_wheel; pub use config::{ - scan_games, scan_keyboard_layouts, ChordPadConfigJson, GameConfig, InstrumentConfigJson, + scan_games, scan_keyboard_layouts, ChordConfigJson, FretLayoutJson, GameConfig, GuitarConfigJson, InstrumentConfigJson, KeyboardLayoutJson, LoadedGameBundle, }; pub use mapping::{char_to_key, parse_key_str, parse_key_stroke, KeyStroke, KeyboardLayout, NoteKeyMapping}; diff --git a/crates/amp-core/src/input/simulator.rs b/crates/amp-core/src/input/simulator.rs index 398e7260..77598dba 100644 --- a/crates/amp-core/src/input/simulator.rs +++ b/crates/amp-core/src/input/simulator.rs @@ -1,9 +1,22 @@ use enigo::{Direction, Enigo, Key, Keyboard, Settings}; -use std::collections::HashSet; +#[cfg(windows)] +use enigo::{Mouse, Coordinate, Button}; +use super::{chord_wheel::{ChordWheelOutput, WheelButton}, config::ChordWheelConfigJson}; +use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; use super::mapping::KeyStroke; use crate::diagnostics::{ServiceState, ServiceStatus}; +#[cfg(any(windows, test))] +fn matches_game_process(path: &str, processes: &[String]) -> bool { + fn normalized(value: &str) -> String { + let name = value.trim().trim_matches('"').rsplit(['/', '\\']).next().unwrap_or("").to_lowercase(); + name.strip_suffix(".exe").unwrap_or(&name).to_string() + } + let actual = normalized(path); + !actual.is_empty() && processes.iter().any(|process| normalized(process) == actual) +} + #[cfg(any(target_os = "linux", test))] fn wayland_session(display: Option<&std::ffi::OsStr>, session_type: Option<&std::ffi::OsStr>) -> bool { display.is_some_and(|value| !value.is_empty()) @@ -52,6 +65,9 @@ pub struct KeySimulator { pressed_keys: HashSet, last_press_time: Option, pedals: PedalOutput, + wheel: ChordWheelOutput, + wheel_context: Option, + wheel_pages: HashMap>, } /// One backend owns the physical keyboard. Wayland supplies a portal backend; @@ -60,9 +76,20 @@ pub trait KeyboardOutput: Send { fn key(&mut self, key: Key, up: bool) -> Result<(), String>; fn error(&self) -> Option { None } fn failure_state(&self) -> ServiceState { ServiceState::Unavailable } + fn wheel_move(&mut self, _processes: &[String], _point: [u16; 2]) -> Result<(), String> { + Err("Chord wheel mouse output is currently supported on Windows only.".into()) + } + fn wheel_button(&mut self, _button: WheelButton, _up: bool) -> Result<(), String> { + Err("Chord wheel mouse output is unavailable.".into()) + } + fn wheel_focused(&self) -> bool { false } } -struct EnigoOutput(Enigo); +struct EnigoOutput { + enigo: Enigo, + #[cfg(windows)] + wheel_window: Option, +} #[cfg(target_os = "macos")] #[link(name = "ApplicationServices", kind = "framework")] extern "C" { fn AXIsProcessTrusted() -> bool; } @@ -74,7 +101,51 @@ impl KeyboardOutput for EnigoOutput { ServiceState::Unavailable } fn key(&mut self, key: Key, up: bool) -> Result<(), String> { - self.0.key(key, if up { Direction::Release } else { Direction::Press }).map_err(|e| e.to_string()) + self.enigo.key(key, if up { Direction::Release } else { Direction::Press }).map_err(|e| e.to_string()) + } + #[cfg(windows)] + fn wheel_move(&mut self, processes: &[String], point: [u16; 2]) -> Result<(), String> { + use windows_sys::Win32::{Foundation::{CloseHandle, POINT, RECT}, Graphics::Gdi::ClientToScreen, + System::Threading::{OpenProcess, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION}, + UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId, GetClientRect}}; + // SAFETY: all output pointers refer to live stack buffers. Process handles + // are closed immediately; the foreground HWND is used only for this call. + let (window, x, y) = unsafe { + let window = GetForegroundWindow(); + let mut pid = 0; + GetWindowThreadProcessId(window, &mut pid); + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { return Err("Focus the game window before chord playback.".into()); } + let mut name = [0u16; 32768]; + let mut length = name.len() as u32; + let found = QueryFullProcessImageNameW(handle, 0, name.as_mut_ptr(), &mut length); + CloseHandle(handle); + let path = String::from_utf16_lossy(&name[..length.min(name.len() as u32) as usize]); + if found == 0 || !matches_game_process(&path, processes) { + return Err("Focus the selected game window before chord playback.".into()); + } + let mut rect = RECT::default(); + let mut origin = POINT::default(); + if GetClientRect(window, &mut rect) == 0 || ClientToScreen(window, &mut origin) == 0 + || rect.right <= 0 || rect.bottom <= 0 { return Err("Cannot locate the game area.".into()); } + (window as usize, origin.x + ((rect.right - 1) as i64 * point[0] as i64 / 1000) as i32, + origin.y + ((rect.bottom - 1) as i64 * point[1] as i64 / 1000) as i32) + }; + self.wheel_window = Some(window); + self.enigo.move_mouse(x, y, Coordinate::Abs).map_err(|e| e.to_string()) + } + #[cfg(windows)] + fn wheel_focused(&self) -> bool { + // SAFETY: GetForegroundWindow has no arguments or ownership transfer. + self.wheel_window.is_some_and(|window| unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::GetForegroundWindow() as usize == window + }) + } + #[cfg(windows)] + fn wheel_button(&mut self, button: WheelButton, up: bool) -> Result<(), String> { + if !up && !self.wheel_focused() { return Err("The game lost focus; chord playback was paused.".into()); } + self.enigo.button(match button { WheelButton::Left => Button::Left, WheelButton::Right => Button::Right }, + if up { Direction::Release } else { Direction::Press }).map_err(|e| e.to_string()) } fn error(&self) -> Option { #[cfg(target_os = "macos")] @@ -96,6 +167,9 @@ impl KeySimulator { pressed_keys: HashSet::new(), last_press_time: None, pedals: PedalOutput::default(), + wheel: ChordWheelOutput::default(), + wheel_context: None, + wheel_pages: HashMap::new(), } } @@ -117,14 +191,14 @@ impl KeySimulator { self.observation = ServiceStatus::new(ServiceState::PermissionRequired); return Err("Wayland keyboard output requires an authorized desktop keyboard session.".into()); } - self.output = Some(Box::new(EnigoOutput(Enigo::new(&Settings::default()).map_err(|error| { + self.output = Some(Box::new(EnigoOutput { enigo: Enigo::new(&Settings::default()).map_err(|error| { let state = if matches!(error, enigo::NewConError::NoPermission) { ServiceState::PermissionRequired } else { ServiceState::Unavailable }; self.observation = ServiceStatus::with_detail(state, &error); #[cfg(target_os = "macos")] { format!("Keyboard output is unavailable: {error}. Enable Auto MIDI Player in System Settings > Privacy & Security > Accessibility, then press Start again.") } #[cfg(not(target_os = "macos"))] { error.to_string() } - })?))); + })?, #[cfg(windows)] wheel_window: None })); self.observation = ServiceStatus::new(ServiceState::Ready); Ok(()) } @@ -132,6 +206,7 @@ impl KeySimulator { pub fn set_output(&mut self, output: Option>) { self.release_everything(); self.output = output; + self.wheel.retire(); // Failed releases belong to the retired backend. A replacement must // not inherit ownership for keys that it has never pressed. #[cfg(not(windows))] @@ -209,6 +284,7 @@ impl KeySimulator { } pub fn release_everything(&mut self) { + self.cancel_wheel(); for source in 0..5 { self.release_source(source); } self.pressed_keys.clear(); self.pedals.clear(); @@ -244,11 +320,68 @@ impl KeySimulator { /// Releases all currently held physical keys to ensure keys never get stuck pub fn release_all(&mut self, _all_keys: &[Key]) { + self.cancel_wheel(); self.release_source(0); self.release_source(1); self.pressed_keys.clear(); self.pedals.clear(); } + + pub fn prepare_wheel(&mut self, config: &ChordWheelConfigJson, processes: &[String], index: usize, owner: usize) { + let result = self.prepare().and_then(|_| self.wheel.prepare(self.output.as_mut().unwrap().as_mut(), + config, processes, Some(index), index / config.positions.len(), Some(owner), Instant::now())); + if let Err(error) = result { self.cancel_wheel(); self.error = Some(error); } + } + + pub fn strum_wheel(&mut self, owner: usize, hold_ms: u64) { + let result = self.output.as_mut().ok_or_else(|| "Mouse output is unavailable".to_string()) + .and_then(|output| self.wheel.strum(output.as_mut(), owner, hold_ms, Instant::now())); + if let Err(error) = result { self.cancel_wheel(); self.error = Some(error); } + } + pub fn pluck_wheel(&mut self, owner: usize, strokes: &[KeyStroke], hold_ms: u64) { + let result = self.output.as_mut().ok_or_else(|| "String output is unavailable".to_string()) + .and_then(|output| self.wheel.pluck(output.as_mut(), owner, strokes, hold_ms, Instant::now())); + if let Err(error) = result { self.cancel_wheel(); self.error = Some(error); } + } + + pub fn wheel_preparation_ms(&self, config: &ChordWheelConfigJson, index: usize) -> u64 { self.wheel.preparation_ms(config, index) } + pub fn wheel_ready(&self, owner: usize) -> bool { self.wheel.ready(owner, Instant::now()) } + pub fn wheel_state(&self) -> super::chord_wheel::ChordWheelState { self.wheel.state() } + pub fn set_wheel_context(&mut self, context: Option) { + if let Some(context) = context { + if self.wheel_context.as_ref().is_some_and(|previous| previous != &context) { + self.cancel_wheel(); + if let Some(previous) = &self.wheel_context { self.wheel_pages.insert(previous.clone(), self.wheel.state().page); } + if let Some(Some(page)) = self.wheel_pages.get(&context) { self.wheel.assume_page(*page); } + else { self.wheel.forget_page(); } + } + self.wheel_context = Some(context); + } + } + pub fn set_wheel_page(&mut self, config: &ChordWheelConfigJson, processes: &[String], page: usize, send: bool) -> Result<(), String> { + if page >= config.page_count { return Err("Chord page is unavailable".into()); } + if self.wheel.is_active() { return Err("The chord wheel is busy".into()); } + if !send { self.wheel.assume_page(page); return Ok(()); } + self.prepare()?; + let result = self.wheel.prepare(self.output.as_mut().unwrap().as_mut(), config, processes, None, page, None, Instant::now()); + if let Err(error) = &result { self.cancel_wheel(); self.error = Some(error.clone()); } + result + } + + pub fn tick_wheel(&mut self) { + if let Some(output) = &mut self.output { + if let Err(error) = self.wheel.tick(output.as_mut(), Instant::now()) { + self.cancel_wheel(); self.error = Some(error); + } + } + } + + pub fn wheel_active(&self) -> bool { self.wheel.is_active() } + pub fn cancel_wheel(&mut self) { + if let Some(output) = &mut self.output { + if let Err(error) = self.wheel.cancel(output.as_mut()) { self.error = Some(error); } + } + } } impl Default for KeySimulator { @@ -264,6 +397,30 @@ mod tests { fn key(c: char) -> Key { char_to_key(c).unwrap() } + #[test] + fn wheel_process_target_accepts_game_aliases_and_custom_executable_paths() { + let names = vec!["GameMain".into(), "Alternate.EXE".into(), "C:\\Games\\CustomGame.exe".into()]; + assert!(matches_game_process("C:\\Game\\GAMEMAIN.EXE", &names)); + assert!(matches_game_process("alternate.exe", &names)); + assert!(matches_game_process("D:\\Other\\CustomGame.EXE", &names)); + assert!(!matches_game_process("unrelated.exe", &names)); + assert!(!matches_game_process("GameMain.exe", &[])); + } + + #[test] + fn wheel_page_state_is_scoped_to_its_game_and_layout_context() { + let mut simulator = KeySimulator::new(); + simulator.set_wheel_context(Some("game-a/wheel".into())); + simulator.wheel.assume_page(2); + simulator.set_wheel_context(None); // The same game switches to keyboard mode. + simulator.set_wheel_context(Some("game-a/wheel".into())); + assert_eq!(simulator.wheel_state().page, Some(2)); + simulator.set_wheel_context(Some("game-b/wheel".into())); + assert_eq!(simulator.wheel_state().page, None); + simulator.set_wheel_context(Some("game-a/wheel".into())); + assert_eq!(simulator.wheel_state().page, Some(2)); + } + #[test] fn wayland_detection_ignores_empty_display_and_accepts_session_type() { use std::ffi::OsStr; diff --git a/crates/amp-core/src/lib.rs b/crates/amp-core/src/lib.rs index bbda766d..20aa2bd9 100644 --- a/crates/amp-core/src/lib.rs +++ b/crates/amp-core/src/lib.rs @@ -10,7 +10,7 @@ pub mod settings; pub use midi::{ParsedMidi, TrackInfo, TimedNoteEvent, TimedControlEvent, ControlEventKind, TempoMap, TransposeMode, detect_best_scale, build_scale_pitch_classes, process_note_pitch, parse_midi_file, parse_midi_bytes, MidiError, get_gm_instrument_name, GENERAL_MIDI_INSTRUMENTS, KeyChangeMarker, RawKeySignature, detect_key_changes}; pub use input::{ - char_to_key, parse_key_str, parse_key_stroke, KeyStroke, scan_games, scan_keyboard_layouts, ChordPadConfigJson, GameConfig, + char_to_key, parse_key_str, parse_key_stroke, KeyStroke, scan_games, scan_keyboard_layouts, ChordConfigJson, FretLayoutJson, GameConfig, GuitarConfigJson, InstrumentConfigJson, KeySimulator, KeyboardLayout, KeyboardLayoutJson, LoadedGameBundle, NoteKeyMapping, }; diff --git a/crates/amp-core/src/library/db.rs b/crates/amp-core/src/library/db.rs index 14097952..a80aac1e 100644 --- a/crates/amp-core/src/library/db.rs +++ b/crates/amp-core/src/library/db.rs @@ -15,7 +15,7 @@ const SONG_COLUMNS: &[(&str, &str)] = &[ ("Transpose", "INTEGER NOT NULL DEFAULT 0"), ("Speed", "REAL DEFAULT 1.0"), ("Bpm", "REAL"), ("DisabledTracks", "TEXT"), ("MergeNotes", "INTEGER"), ("MergeMilliseconds", "INTEGER"), ("HoldNotes", "INTEGER"), ("TapThresholdMs", "INTEGER DEFAULT 0"), ("ImagePath", "TEXT"), - ("CachedDurationMs", "INTEGER"), ("CachedNativeBpm", "REAL"), ("AutoChord", "INTEGER"), + ("CachedDurationMs", "INTEGER"), ("CachedNativeBpm", "REAL"), ("ChordDetectionMilliseconds", "INTEGER"), ("KeyChanges", "TEXT"), ("EnableKeyChangeMarkers", "INTEGER DEFAULT 1"), ]; @@ -23,9 +23,46 @@ const LEGACY_SONG_SETTINGS_MIGRATION: &str = "legacy-instrument-song-settings-v1 const MARKER_LABEL_MIGRATION: &str = "marker-label-offsets-v1"; const TECHNICAL_SONG_FIELDS: &[&str] = &[ "baseKey", "key", "transpose", "speed", "bpm", "disabledTracks", "mergeNotes", - "mergeMilliseconds", "holdNotes", "tapThresholdMs", "autoChord", + "mergeMilliseconds", "holdNotes", "tapThresholdMs", "chordDetectionMilliseconds", "keyChanges", "enableKeyChangeMarkers", ]; +const SONG_SELECT_COLUMNS: &str = + "s.Id, s.BaseKey, s.Key, s.Path, s.FileHash, s.Title, s.Artist, s.Album, s.AlbumId, s.DateAdded, + s.Transpose, s.Speed, s.Bpm, s.DisabledTracks, s.MergeNotes, s.MergeMilliseconds, s.HoldNotes, + s.ImagePath, s.CachedDurationMs, s.CachedNativeBpm, s.ChordDetectionMilliseconds, + s.KeyChanges, s.EnableKeyChangeMarkers, s.TapThresholdMs"; + +fn song_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let path_str: String = row.get(3)?; + let is_missing = !Path::new(&path_str).exists(); + Ok(SongRecord { + id: row.get(0)?, + base_key: row.get(1)?, + key: row.get(2)?, + path: path_str, + file_hash: row.get(4)?, + title: row.get(5)?, + artist: row.get(6)?, + album: row.get(7)?, + album_id: row.get(8)?, + date_added: row.get(9)?, + transpose: row.get::<_, Option>(10)?.unwrap_or(0), + speed: row.get(11)?, + bpm: row.get(12)?, + disabled_tracks: row.get(13)?, + merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), + merge_milliseconds: row.get(15)?, + hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), + tap_threshold_ms: row.get(23)?, + image_path: row.get(17)?, + cached_duration_ms: row.get(18)?, + cached_native_bpm: row.get(19)?, + chord_detection_milliseconds: row.get(20)?, + key_changes: row.get(21)?, + enable_key_change_markers: row.get::<_, Option>(22)?.map(|v| v != 0), + is_missing, + }) +} fn merge_json_object(target: &mut Value, patch: &Value) { let (Value::Object(target), Value::Object(patch)) = (target, patch) else { @@ -252,7 +289,6 @@ impl LibraryDatabase { ImagePath TEXT, CachedDurationMs INTEGER, CachedNativeBpm REAL, - AutoChord INTEGER, ChordDetectionMilliseconds INTEGER, KeyChanges TEXT, EnableKeyChangeMarkers INTEGER DEFAULT 1, @@ -267,7 +303,7 @@ impl LibraryDatabase { let rows = pragma.query_map([], |row| row.get::<_, String>(1))?; rows.collect::, _>>()? }; - for (old, new) in [("Author", "Artist"), ("DefaultKey", "BaseKey"), ("DetectChordPads", "AutoChord")] { + for (old, new) in [("Author", "Artist"), ("DefaultKey", "BaseKey")] { if let Some(index) = columns.iter().position(|c| c.eq_ignore_ascii_case(old)) { if columns.iter().any(|c| c.eq_ignore_ascii_case(new)) { // A partial older upgrade may contain both; prefer the canonical value. @@ -406,7 +442,7 @@ impl LibraryDatabase { on_migration(); let songs = { let mut stmt = transaction.prepare("SELECT Id, BaseKey, Key, Transpose, Speed, Bpm, DisabledTracks, - MergeNotes, MergeMilliseconds, HoldNotes, TapThresholdMs, AutoChord, + MergeNotes, MergeMilliseconds, HoldNotes, TapThresholdMs, ChordDetectionMilliseconds, KeyChanges, EnableKeyChangeMarkers FROM Songs")?; let rows = stmt.query_map([], |row| Ok((row.get::<_, String>(0)?, serde_json::json!({ "baseKey": row.get::<_, Option>(1)?, "key": row.get::<_, i32>(2)?, @@ -414,8 +450,8 @@ impl LibraryDatabase { "bpm": row.get::<_, Option>(5)?, "disabledTracks": row.get::<_, Option>(6)?, "mergeNotes": row.get::<_, Option>(7)?, "mergeMilliseconds": row.get::<_, Option>(8)?, "holdNotes": row.get::<_, Option>(9)?, "tapThresholdMs": row.get::<_, Option>(10)?, - "autoChord": row.get::<_, Option>(11)?, "chordDetectionMilliseconds": row.get::<_, Option>(12)?, - "keyChanges": row.get::<_, Option>(13)?, "enableKeyChangeMarkers": row.get::<_, Option>(14)?, + "chordDetectionMilliseconds": row.get::<_, Option>(11)?, + "keyChanges": row.get::<_, Option>(12)?, "enableKeyChangeMarkers": row.get::<_, Option>(13)?, }))))?; rows.collect::, _>>()? }; @@ -518,7 +554,6 @@ impl LibraryDatabase { ("speed", settings.speed.map(Value::from)), ("holdNotes", settings.hold_notes.map(Value::from)), ("tapThresholdMs", settings.tap_threshold_ms.map(Value::from)), - ("autoChord", settings.auto_chord.map(Value::from)), ("chordDetectionMilliseconds", settings.chord_detection_milliseconds.map(Value::from)), ("enableKeyChangeMarkers", settings.enable_key_change_markers.map(Value::from)), ] { @@ -542,7 +577,7 @@ impl LibraryDatabase { "bpm": details.bpm, "speed": details.speed, "mergeNotes": details.merge_notes, "mergeMilliseconds": details.merge_milliseconds, "holdNotes": details.hold_notes, "tapThresholdMs": details.tap_threshold_ms, - "autoChord": details.auto_chord, "enableKeyChangeMarkers": details.enable_key_change_markers, + "enableKeyChangeMarkers": details.enable_key_change_markers, }); Self::write_song_settings_patch(&tx, id, scope, &patch)?; tx.commit() @@ -637,201 +672,38 @@ impl LibraryDatabase { /// Retrieve all songs from database with active missing-file check pub fn get_all_songs(&self) -> Result, rusqlite::Error> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT Id, BaseKey, Key, Path, FileHash, Title, Artist, Album, AlbumId, DateAdded, - Transpose, Speed, Bpm, DisabledTracks, MergeNotes, MergeMilliseconds, HoldNotes, - ImagePath, CachedDurationMs, CachedNativeBpm, AutoChord, ChordDetectionMilliseconds, - KeyChanges, EnableKeyChangeMarkers, TapThresholdMs - FROM Songs - ORDER BY DateAdded DESC", - )?; - - let rows = stmt.query_map([], |row| { - let path_str: String = row.get(3)?; - let is_missing = !Path::new(&path_str).exists(); - - Ok(SongRecord { - id: row.get(0)?, - base_key: row.get(1)?, - key: row.get(2)?, - path: path_str, - file_hash: row.get(4)?, - title: row.get(5)?, - artist: row.get(6)?, - album: row.get(7)?, - album_id: row.get(8)?, - date_added: row.get(9)?, - transpose: row.get::<_, Option>(10)?.unwrap_or(0), - speed: row.get(11)?, - bpm: row.get(12)?, - disabled_tracks: row.get(13)?, - merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), - merge_milliseconds: row.get(15)?, - hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), - tap_threshold_ms: row.get(24)?, - image_path: row.get(17)?, - cached_duration_ms: row.get(18)?, - cached_native_bpm: row.get(19)?, - auto_chord: row.get::<_, Option>(20)?.map(|v| v != 0), - chord_detection_milliseconds: row.get(21)?, - key_changes: row.get(22)?, - enable_key_change_markers: row.get::<_, Option>(23)?.map(|v| v != 0), - is_missing, - }) - })?; - - let mut songs = Vec::new(); - for r in rows { - songs.push(r?); - } - Ok(songs) + let mut stmt = conn.prepare(&format!( + "SELECT {SONG_SELECT_COLUMNS} FROM Songs s ORDER BY s.DateAdded DESC" + ))?; + let songs = stmt.query_map([], song_from_row)?.collect(); + songs } /// Find song by ID pub fn get_song_by_id(&self, id: &str) -> Result, rusqlite::Error> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT Id, BaseKey, Key, Path, FileHash, Title, Artist, Album, AlbumId, DateAdded, - Transpose, Speed, Bpm, DisabledTracks, MergeNotes, MergeMilliseconds, HoldNotes, - ImagePath, CachedDurationMs, CachedNativeBpm, AutoChord, ChordDetectionMilliseconds, - KeyChanges, EnableKeyChangeMarkers, TapThresholdMs - FROM Songs - WHERE Id = ?1", - )?; - - let song = stmt.query_row([id], |row| { - let path_str: String = row.get(3)?; - let is_missing = !Path::new(&path_str).exists(); - - Ok(SongRecord { - id: row.get(0)?, - base_key: row.get(1)?, - key: row.get(2)?, - path: path_str, - file_hash: row.get(4)?, - title: row.get(5)?, - artist: row.get(6)?, - album: row.get(7)?, - album_id: row.get(8)?, - date_added: row.get(9)?, - transpose: row.get::<_, Option>(10)?.unwrap_or(0), - speed: row.get(11)?, - bpm: row.get(12)?, - disabled_tracks: row.get(13)?, - merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), - merge_milliseconds: row.get(15)?, - hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), - tap_threshold_ms: row.get(24)?, - image_path: row.get(17)?, - cached_duration_ms: row.get(18)?, - cached_native_bpm: row.get(19)?, - auto_chord: row.get::<_, Option>(20)?.map(|v| v != 0), - chord_detection_milliseconds: row.get(21)?, - key_changes: row.get(22)?, - enable_key_change_markers: row.get::<_, Option>(23)?.map(|v| v != 0), - is_missing, - }) - }).optional()?; - - Ok(song) + let mut stmt = conn.prepare(&format!( + "SELECT {SONG_SELECT_COLUMNS} FROM Songs s WHERE s.Id = ?1" + ))?; + stmt.query_row([id], song_from_row).optional() } /// Find song by file path pub fn get_song_by_path(&self, path: &str) -> Result, rusqlite::Error> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT Id, BaseKey, Key, Path, FileHash, Title, Artist, Album, AlbumId, DateAdded, - Transpose, Speed, Bpm, DisabledTracks, MergeNotes, MergeMilliseconds, HoldNotes, - ImagePath, CachedDurationMs, CachedNativeBpm, AutoChord, ChordDetectionMilliseconds, - KeyChanges, EnableKeyChangeMarkers, TapThresholdMs - FROM Songs - WHERE Path = ?1", - )?; - - let song = stmt.query_row([path], |row| { - let path_str: String = row.get(3)?; - let is_missing = !Path::new(&path_str).exists(); - - Ok(SongRecord { - id: row.get(0)?, - base_key: row.get(1)?, - key: row.get(2)?, - path: path_str, - file_hash: row.get(4)?, - title: row.get(5)?, - artist: row.get(6)?, - album: row.get(7)?, - album_id: row.get(8)?, - date_added: row.get(9)?, - transpose: row.get::<_, Option>(10)?.unwrap_or(0), - speed: row.get(11)?, - bpm: row.get(12)?, - disabled_tracks: row.get(13)?, - merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), - merge_milliseconds: row.get(15)?, - hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), - tap_threshold_ms: row.get(24)?, - image_path: row.get(17)?, - cached_duration_ms: row.get(18)?, - cached_native_bpm: row.get(19)?, - auto_chord: row.get::<_, Option>(20)?.map(|v| v != 0), - chord_detection_milliseconds: row.get(21)?, - key_changes: row.get(22)?, - enable_key_change_markers: row.get::<_, Option>(23)?.map(|v| v != 0), - is_missing, - }) - }).optional()?; - - Ok(song) + let mut stmt = conn.prepare(&format!( + "SELECT {SONG_SELECT_COLUMNS} FROM Songs s WHERE s.Path = ?1" + ))?; + stmt.query_row([path], song_from_row).optional() } /// Find song by SHA-256 hash pub fn get_song_by_hash(&self, hash: &str) -> Result, rusqlite::Error> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT Id, BaseKey, Key, Path, FileHash, Title, Artist, Album, AlbumId, DateAdded, - Transpose, Speed, Bpm, DisabledTracks, MergeNotes, MergeMilliseconds, HoldNotes, - ImagePath, CachedDurationMs, CachedNativeBpm, AutoChord, ChordDetectionMilliseconds, - KeyChanges, EnableKeyChangeMarkers, TapThresholdMs - FROM Songs - WHERE FileHash = ?1", - )?; - - let song = stmt.query_row([hash], |row| { - let path_str: String = row.get(3)?; - let is_missing = !Path::new(&path_str).exists(); - - Ok(SongRecord { - id: row.get(0)?, - base_key: row.get(1)?, - key: row.get(2)?, - path: path_str, - file_hash: row.get(4)?, - title: row.get(5)?, - artist: row.get(6)?, - album: row.get(7)?, - album_id: row.get(8)?, - date_added: row.get(9)?, - transpose: row.get::<_, Option>(10)?.unwrap_or(0), - speed: row.get(11)?, - bpm: row.get(12)?, - disabled_tracks: row.get(13)?, - merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), - merge_milliseconds: row.get(15)?, - hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), - tap_threshold_ms: row.get(24)?, - image_path: row.get(17)?, - cached_duration_ms: row.get(18)?, - cached_native_bpm: row.get(19)?, - auto_chord: row.get::<_, Option>(20)?.map(|v| v != 0), - chord_detection_milliseconds: row.get(21)?, - key_changes: row.get(22)?, - enable_key_change_markers: row.get::<_, Option>(23)?.map(|v| v != 0), - is_missing, - }) - }).optional()?; - - Ok(song) + let mut stmt = conn.prepare(&format!( + "SELECT {SONG_SELECT_COLUMNS} FROM Songs s WHERE s.FileHash = ?1" + ))?; + stmt.query_row([hash], song_from_row).optional() } /// Insert a new song or update an existing one @@ -844,14 +716,14 @@ impl LibraryDatabase { "INSERT INTO Songs ( Id, BaseKey, Key, Path, FileHash, Title, Artist, Album, AlbumId, DateAdded, Transpose, Speed, Bpm, DisabledTracks, MergeNotes, MergeMilliseconds, HoldNotes, - ImagePath, CachedDurationMs, CachedNativeBpm, AutoChord, ChordDetectionMilliseconds, + ImagePath, CachedDurationMs, CachedNativeBpm, ChordDetectionMilliseconds, KeyChanges, EnableKeyChangeMarkers, TapThresholdMs ) VALUES ( COALESCE((SELECT Id FROM Songs WHERE Path = ?4 LIMIT 1), ?1), ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, - ?18, ?19, ?20, ?21, ?22, - ?23, ?24, ?25 + ?18, ?19, ?20, ?21, + ?22, ?23, ?24 ) ON CONFLICT(Id) DO UPDATE SET Path = excluded.Path, @@ -883,7 +755,6 @@ impl LibraryDatabase { song.image_path, song.cached_duration_ms, song.cached_native_bpm, - song.auto_chord.map(|b| if b { 1 } else { 0 }), song.chord_detection_milliseconds, song.key_changes, song.enable_key_change_markers.map(|b| if b { 1 } else { 0 }), @@ -913,11 +784,10 @@ impl LibraryDatabase { KeyChanges = ?5, Speed = COALESCE(?6, Speed), HoldNotes = COALESCE(?7, HoldNotes), - AutoChord = COALESCE(?8, AutoChord), - EnableKeyChangeMarkers = COALESCE(?9, EnableKeyChangeMarkers), - TapThresholdMs = COALESCE(?10, TapThresholdMs), - ChordDetectionMilliseconds = COALESCE(?11, ChordDetectionMilliseconds) - WHERE Id = ?12", + EnableKeyChangeMarkers = COALESCE(?8, EnableKeyChangeMarkers), + TapThresholdMs = COALESCE(?9, TapThresholdMs), + ChordDetectionMilliseconds = COALESCE(?10, ChordDetectionMilliseconds) + WHERE Id = ?11", params![ settings.key, settings.base_key, @@ -926,7 +796,6 @@ impl LibraryDatabase { settings.key_changes, settings.speed, settings.hold_notes.map(|b| if b { 1 } else { 0 }), - settings.auto_chord.map(|b| if b { 1 } else { 0 }), settings.enable_key_change_markers.map(|b| if b { 1 } else { 0 }), settings.tap_threshold_ms, settings.chord_detection_milliseconds, @@ -966,10 +835,10 @@ impl LibraryDatabase { "UPDATE Songs SET Title = ?1, Artist = NULLIF(?2, ''), Album = NULLIF(?3, ''), AlbumId = ?4, BaseKey = ?5, Key = ?6, Transpose = ?7, Bpm = ?8, Speed = ?9, MergeNotes = ?10, MergeMilliseconds = ?11, HoldNotes = ?12, - AutoChord = ?13, EnableKeyChangeMarkers = ?14, DateAdded = ?15, TapThresholdMs = ?17 WHERE Id = ?16", + EnableKeyChangeMarkers = ?13, DateAdded = ?14, TapThresholdMs = ?16 WHERE Id = ?15", params![details.title, details.artist, details.album, album_id, details.base_key, details.key, details.transpose, details.bpm, details.speed, details.merge_notes, - details.merge_milliseconds, details.hold_notes, details.auto_chord, + details.merge_milliseconds, details.hold_notes, details.enable_key_change_markers, details.date_added, id, details.tap_threshold_ms], )?; if changed == 0 { return Err(rusqlite::Error::QueryReturnedNoRows); } @@ -1150,111 +1019,29 @@ impl LibraryDatabase { pub fn get_playlist_songs(&self, playlist_id: &str) -> Result, rusqlite::Error> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT s.Id, s.BaseKey, s.Key, s.Path, s.FileHash, s.Title, s.Artist, s.Album, s.AlbumId, s.DateAdded, - s.Transpose, s.Speed, s.Bpm, s.DisabledTracks, s.MergeNotes, s.MergeMilliseconds, s.HoldNotes, - s.ImagePath, s.CachedDurationMs, s.CachedNativeBpm, s.AutoChord, s.ChordDetectionMilliseconds, - s.KeyChanges, s.EnableKeyChangeMarkers, s.TapThresholdMs + let mut stmt = conn.prepare(&format!( + "SELECT {SONG_SELECT_COLUMNS} FROM Songs s INNER JOIN PlaylistSongs ps ON s.Id = ps.SongId WHERE ps.PlaylistId = ?1 - ORDER BY ps.SortOrder ASC", - )?; - - let rows = stmt.query_map([playlist_id], |row| { - let path_str: String = row.get(3)?; - let is_missing = !Path::new(&path_str).exists(); - - Ok(SongRecord { - id: row.get(0)?, - base_key: row.get(1)?, - key: row.get(2)?, - path: path_str, - file_hash: row.get(4)?, - title: row.get(5)?, - artist: row.get(6)?, - album: row.get(7)?, - album_id: row.get(8)?, - date_added: row.get(9)?, - transpose: row.get::<_, Option>(10)?.unwrap_or(0), - speed: row.get(11)?, - bpm: row.get(12)?, - disabled_tracks: row.get(13)?, - merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), - merge_milliseconds: row.get(15)?, - hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), - tap_threshold_ms: row.get(24)?, - image_path: row.get(17)?, - cached_duration_ms: row.get(18)?, - cached_native_bpm: row.get(19)?, - auto_chord: row.get::<_, Option>(20)?.map(|v| v != 0), - chord_detection_milliseconds: row.get(21)?, - key_changes: row.get(22)?, - enable_key_change_markers: row.get::<_, Option>(23)?.map(|v| v != 0), - is_missing, - }) - })?; - - let mut songs = Vec::new(); - for r in rows { - songs.push(r?); - } - Ok(songs) + ORDER BY ps.SortOrder ASC" + ))?; + let songs = stmt.query_map([playlist_id], song_from_row)?.collect(); + songs } // --- Queue --- pub fn get_queue_songs(&self) -> Result, rusqlite::Error> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare( - "SELECT s.Id, s.BaseKey, s.Key, s.Path, s.FileHash, s.Title, s.Artist, s.Album, s.AlbumId, s.DateAdded, - s.Transpose, s.Speed, s.Bpm, s.DisabledTracks, s.MergeNotes, s.MergeMilliseconds, s.HoldNotes, - s.ImagePath, s.CachedDurationMs, s.CachedNativeBpm, s.AutoChord, s.ChordDetectionMilliseconds, - s.KeyChanges, s.EnableKeyChangeMarkers, s.TapThresholdMs + let mut stmt = conn.prepare(&format!( + "SELECT {SONG_SELECT_COLUMNS} FROM Songs s INNER JOIN Queue q ON s.Id = q.SongId - ORDER BY q.SortOrder ASC", - )?; - - let rows = stmt.query_map([], |row| { - let path_str: String = row.get(3)?; - let is_missing = !Path::new(&path_str).exists(); - - Ok(SongRecord { - id: row.get(0)?, - base_key: row.get(1)?, - key: row.get(2)?, - path: path_str, - file_hash: row.get(4)?, - title: row.get(5)?, - artist: row.get(6)?, - album: row.get(7)?, - album_id: row.get(8)?, - date_added: row.get(9)?, - transpose: row.get::<_, Option>(10)?.unwrap_or(0), - speed: row.get(11)?, - bpm: row.get(12)?, - disabled_tracks: row.get(13)?, - merge_notes: row.get::<_, Option>(14)?.map(|v| v != 0), - merge_milliseconds: row.get(15)?, - hold_notes: row.get::<_, Option>(16)?.map(|v| v != 0), - tap_threshold_ms: row.get(24)?, - image_path: row.get(17)?, - cached_duration_ms: row.get(18)?, - cached_native_bpm: row.get(19)?, - auto_chord: row.get::<_, Option>(20)?.map(|v| v != 0), - chord_detection_milliseconds: row.get(21)?, - key_changes: row.get(22)?, - enable_key_change_markers: row.get::<_, Option>(23)?.map(|v| v != 0), - is_missing, - }) - })?; - - let mut songs = Vec::new(); - for r in rows { - songs.push(r?); - } - Ok(songs) + ORDER BY q.SortOrder ASC" + ))?; + let songs = stmt.query_map([], song_from_row)?.collect(); + songs } pub fn set_queue(&self, song_ids: &[String]) -> Result<(), rusqlite::Error> { diff --git a/crates/amp-core/src/library/models.rs b/crates/amp-core/src/library/models.rs index 988b3a0b..95f7141c 100644 --- a/crates/amp-core/src/library/models.rs +++ b/crates/amp-core/src/library/models.rs @@ -57,7 +57,6 @@ pub struct SongRecord { pub image_path: Option, pub cached_duration_ms: Option, pub cached_native_bpm: Option, - pub auto_chord: Option, pub chord_detection_milliseconds: Option, pub key_changes: Option, pub enable_key_change_markers: Option, @@ -107,8 +106,6 @@ pub struct SongSettingsUpdate { #[serde(default)] pub tap_threshold_ms: Option, #[serde(default)] - pub auto_chord: Option, - #[serde(default)] pub chord_detection_milliseconds: Option, #[serde(default)] pub enable_key_change_markers: Option, @@ -142,8 +139,6 @@ pub struct SongDetailsUpdate { pub hold_notes: bool, #[serde(default)] pub tap_threshold_ms: u32, - #[serde(default)] - pub auto_chord: bool, #[serde(default = "default_enable_key_change_markers")] pub enable_key_change_markers: bool, pub date_added: String, @@ -164,7 +159,6 @@ pub struct SongDefaults { pub default_merge_tolerance_ms: u32, pub default_hold_notes: bool, pub default_tap_threshold_ms: u32, - pub default_auto_chord: bool, pub default_chord_detection_milliseconds: u32, pub default_enable_key_change_markers: bool, } @@ -181,7 +175,6 @@ impl Default for SongDefaults { default_merge_tolerance_ms: crate::settings::defaults::value("/defaultMergeToleranceMs"), default_hold_notes: crate::settings::defaults::value("/defaultHoldNotes"), default_tap_threshold_ms: crate::settings::defaults::value("/defaultTapThresholdMs"), - default_auto_chord: crate::settings::defaults::value("/defaultAutoChord"), default_chord_detection_milliseconds: crate::settings::defaults::value("/defaultChordDetectionMilliseconds"), default_enable_key_change_markers: crate::settings::defaults::value("/defaultEnableKeyChangeMarkers"), } diff --git a/crates/amp-core/src/library/scanner.rs b/crates/amp-core/src/library/scanner.rs index 20de4557..d4d0c000 100644 --- a/crates/amp-core/src/library/scanner.rs +++ b/crates/amp-core/src/library/scanner.rs @@ -61,7 +61,6 @@ fn create_new_song_record( image_path: None, cached_duration_ms: Some(meta.duration_ms), cached_native_bpm: Some(meta.native_bpm), - auto_chord: Some(defaults.default_auto_chord), chord_detection_milliseconds: Some(defaults.default_chord_detection_milliseconds), // Timeline markers are created explicitly in Studio, independently of base-key detection. key_changes: None, diff --git a/crates/amp-core/src/library/watcher.rs b/crates/amp-core/src/library/watcher.rs index e625c665..314b88a5 100644 --- a/crates/amp-core/src/library/watcher.rs +++ b/crates/amp-core/src/library/watcher.rs @@ -41,11 +41,13 @@ impl DirectoryWatcher { pub fn watch_soundfont_file(file: &Path, on_change: F) -> Result where F: Fn() + Send + 'static, { - let file = file.to_path_buf(); - let parent = file.parent().ok_or("SoundFont path has no parent")?.to_path_buf(); - Self::watch_filtered_mode(&parent, RecursiveMode::NonRecursive, move |event| { + let parent = file.parent().ok_or("SoundFont path has no parent")?; + let name = PathBuf::from(file.file_name().ok_or("SoundFont path has no filename")?); + Self::watch_filtered_mode(parent, RecursiveMode::NonRecursive, move |root, event| { if matches!(event.kind, EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_))) { return false; } - event.need_rescan() || event.paths.iter().any(|path| path == &file) + event.need_rescan() || event.paths.iter().any(|path| { + path.strip_prefix(root).is_ok_and(|relative| relative == name) + }) }, on_change) } @@ -53,16 +55,16 @@ impl DirectoryWatcher { pub fn watch_soundfonts(folder: &Path, on_change: F) -> Result where F: Fn() + Send + 'static, { - let root = folder.to_path_buf(); let parent = folder.parent().ok_or("SoundFonts folder has no parent")?; - Self::watch_filtered(parent, move |event| { + let name = PathBuf::from(folder.file_name().ok_or("SoundFonts folder has no name")?); + Self::watch_filtered(parent, move |root, event| { if event.need_rescan() { return true; } // Reads can update access metadata; reloading in response would create a loop. if matches!(event.kind, EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_))) { return false; } - event.paths.iter().any(|path| { - (path == &root && matches!(event.kind, EventKind::Create(_) | EventKind::Remove(_) - | EventKind::Modify(ModifyKind::Name(_)) | EventKind::Any)) || (path.starts_with(&root) - && path != &root + event.paths.iter().filter_map(|path| path.strip_prefix(root).ok()).any(|path| { + (path == name && matches!(event.kind, EventKind::Create(_) | EventKind::Remove(_) + | EventKind::Modify(ModifyKind::Name(_)) | EventKind::Any)) || (path.starts_with(&name) + && path != name && (path.extension().and_then(|ext| ext.to_str()) .is_some_and(|ext| ext.eq_ignore_ascii_case("sf2")) || matches!(event.kind, EventKind::Remove(_) | EventKind::Modify(ModifyKind::Name(_))))) @@ -75,7 +77,7 @@ impl DirectoryWatcher { where F: Fn() + Send + 'static, { - Self::watch_filtered(folder, needs_scan, on_change) + Self::watch_filtered(folder, |_, event| needs_scan(event), on_change) } /// Watch the config roots through their parent, so deleting/recreating a root is detected. @@ -89,12 +91,14 @@ impl DirectoryWatcher { pub fn watch_configs_with_removals(folder: &Path, on_removal: R, on_change: F) -> Result where F: Fn() + Send + 'static, R: Fn() + Send + 'static, { - let root = folder.to_path_buf(); - Self::watch_filtered(folder, move |event| { + Self::watch_filtered(folder, move |root, event| { if matches!(event.kind, EventKind::Access(_)) { return false; } let relevant = event.need_rescan() || event.paths.iter().any(|path| { - path == &root || path.starts_with(root.join("Games")) - || path.starts_with(root.join("KeyboardLayouts")) + path.strip_prefix(root).is_ok_and(|relative| { + relative.as_os_str().is_empty() + || relative.starts_with("Games") + || relative.starts_with("KeyboardLayouts") + }) }); if relevant && (event.need_rescan() || matches!(event.kind, EventKind::Remove(_) | EventKind::Modify(ModifyKind::Name(_)))) { @@ -105,24 +109,28 @@ impl DirectoryWatcher { } fn watch_filtered(folder: &Path, needs_scan: P, on_change: F) -> Result - where F: Fn() + Send + 'static, P: Fn(&Event) -> bool + Send + 'static, + where F: Fn() + Send + 'static, P: Fn(&Path, &Event) -> bool + Send + 'static, { Self::watch_filtered_mode(folder, RecursiveMode::Recursive, needs_scan, on_change) } fn watch_filtered_mode(folder: &Path, mode: RecursiveMode, needs_scan: P, on_change: F) -> Result - where F: Fn() + Send + 'static, P: Fn(&Event) -> bool + Send + 'static, + where F: Fn() + Send + 'static, P: Fn(&Path, &Event) -> bool + Send + 'static, { if !folder.exists() || !folder.is_dir() { return Err(format!("Cannot watch non-existent directory: {}", folder.display())); } + // FSEvents reports resolved paths, including when the caller used a symlink. + // Resolve the watched directory once so events for deleted children still match. + let watch_root = folder.canonicalize() + .map_err(|e| format!("Failed to resolve watch folder {}: {}", folder.display(), e))?; let (tx, rx) = channel::>(); let mut watcher = RecommendedWatcher::new(tx, Config::default()) .map_err(|e| format!("Failed to create filesystem watcher: {}", e))?; watcher - .watch(folder, mode) + .watch(&watch_root, mode) .map_err(|e| format!("Failed to watch folder {}: {}", folder.display(), e))?; let is_active = Arc::new(AtomicBool::new(true)); @@ -141,7 +149,7 @@ impl DirectoryWatcher { }; match result { Ok(Ok(event)) => { - if needs_scan(&event) { + if needs_scan(&watch_root, &event) { deadline = Some(Instant::now() + debounce_duration); } } diff --git a/crates/amp-core/src/player/engine.rs b/crates/amp-core/src/player/engine.rs index 74823a02..f89ec649 100644 --- a/crates/amp-core/src/player/engine.rs +++ b/crates/amp-core/src/player/engine.rs @@ -11,6 +11,7 @@ use crate::midi::{ detect::KeyChangeMarker, }; use crate::input::{NoteKeyMapping, KeySimulator}; +use crate::input::mapping::ChordBinding; use crate::audio::{AudioSynth, SynthMode}; use enigo::Key; use crate::diagnostics::ServiceStatus; @@ -19,7 +20,7 @@ use crate::diagnostics::ServiceState; use super::live_input::{LiveInput, LiveInputSnapshot, LiveSettings, MidiMessage}; use crate::input::simulator::KeyboardOutput; use super::note_timing::{is_tap, note_durations, pending_note_owners, KeyReleases, KeyPressAction, OverlapBehavior}; -use super::note_processing::{NoteProcessingSettings, ChordNote, merge_notes, detect_chords}; +use super::note_processing::{NoteProcessingSettings, ChordNote, merge_notes, detect_chords, detect_frets}; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum PlaybackStatus { @@ -141,9 +142,12 @@ pub enum PlayerEvent { NoteHit { note: u8, is_on: bool }, StateChanged(PlaybackStatus), Finished, + ChordWheelChanged(crate::input::chord_wheel::ChordWheelState), } enum Command { + GetChordWheelState(Sender), + SetChordWheelPage(usize, bool, Sender>), ObserveKeyboard(ServiceStatus), Fence(Sender<()>), MidiStart(u64), @@ -152,7 +156,7 @@ enum Command { MidiGate(bool), PrepareKeyboard(Sender>), SetKeyboard(Option>), - Play, + Play(Sender>), Pause, Stop, Seek(u64, u64), @@ -200,6 +204,16 @@ pub struct PlaybackEngine { } impl PlaybackEngine { + pub fn chord_wheel_state(&self) -> Result { + let (tx, rx) = crossbeam_channel::bounded(1); + self.cmd_tx.send(Command::GetChordWheelState(tx)).map_err(|e| e.to_string())?; + rx.recv_timeout(Duration::from_secs(2)).map_err(|e| e.to_string()) + } + pub fn set_chord_wheel_page(&self, page: usize, send: bool) -> Result<(), String> { + let (tx, rx) = crossbeam_channel::bounded(1); + self.cmd_tx.send(Command::SetChordWheelPage(page, send, tx)).map_err(|e| e.to_string())?; + rx.recv_timeout(Duration::from_secs(2)).map_err(|e| e.to_string())? + } pub fn new( initial_song: Option, mapping: NoteKeyMapping, @@ -292,7 +306,14 @@ impl PlaybackEngine { pub fn set_keyboard_output(&self, output: Option>) { let _ = self.cmd_tx.send(Command::SetKeyboard(output)); } pub fn play(&self) { - let _ = self.cmd_tx.send(Command::Play); + self.request_play(); + } + + /// The worker acknowledges the request after checking the current song and mapping. + pub fn request_play(&self) -> Receiver> { + let (reply, result) = crossbeam_channel::bounded(1); + let _ = self.cmd_tx.send(Command::Play(reply)); + result } pub fn pause(&self) { @@ -474,6 +495,7 @@ fn run_playback_loop( midi_overflow: Arc, ) { let mut key_sim = KeySimulator::new(); + key_sim.set_wheel_context(mapping.wheel_context()); let mut log_played_notes = false; let mut midi = LiveInput::default(); // Keyboard failures can outlive an inactive MIDI connection. Keep them @@ -533,6 +555,9 @@ fn run_playback_loop( let mut all_keys = mapping.all_keys(); let (mut min_pitch, mut max_pitch) = mapping.pitch_range(); let mut playable_notes = mapping.playable_notes().to_vec(); + let mut wheel_attacks: Vec<(usize, u64, usize)> = Vec::new(); + let mut wheel_starting = true; + let mut wheel_state = key_sim.wheel_state(); let update_status = |new_status: PlaybackStatus, status_arc: &Arc>| { *status_arc.lock().unwrap() = new_status; @@ -549,6 +574,14 @@ fn run_playback_loop( for _ in 0..256 { let Some(cmd) = pending_command.take().or_else(|| cmd_rx.try_recv().ok()) else { break }; match cmd { + Command::GetChordWheelState(reply) => { let _ = reply.send(key_sim.wheel_state()); } + Command::SetChordWheelPage(page, send, reply) => { + let result = if !config_available.load(Ordering::Acquire) { Err("The instrument configuration is unavailable.".into()) } + else if status == PlaybackStatus::Playing { Err("Pause playback before changing the page manually.".into()) } + else if let Some(config) = mapping.chord_wheel() { key_sim.set_wheel_page(config, mapping.game_process_names(), page, send) } + else { Err("Select an instrument with a chord wheel first.".into()) }; + let _ = reply.send(result); + } Command::ObserveKeyboard(status) => key_sim.observe(status), Command::Fence(reply) => { #[cfg(windows)] @@ -588,8 +621,16 @@ fn run_playback_loop( #[cfg(not(windows))] if key_sim.is_ready() { keyboard_error = None; } } - Command::Play => { - if config_available.load(Ordering::Acquire) && status != PlaybackStatus::Playing && current_song.is_some() { + Command::Play(reply) => { + if !config_available.load(Ordering::Acquire) { + let _ = reply.send(Err("Choose an instrument with a valid layout in Instrument View.".into())); + continue; + } + if current_song.is_none() { + let _ = reply.send(Err("Choose a song to play.".into())); + continue; + } + if status != PlaybackStatus::Playing { if current_song.as_ref().is_some_and(|song| event_idx >= song.events.len() && control_idx >= song.control_events.len()) { rebuild_chords = true; triggered_chords.clear(); @@ -609,10 +650,12 @@ fn run_playback_loop( callback(PlayerEvent::PedalsChanged(pedals.state())); } status = PlaybackStatus::Playing; + wheel_starting = true; restore_notes = true; last_instant = Instant::now(); update_status(status, &status_arc); } + let _ = reply.send(Ok(())); } Command::Pause => { if status == PlaybackStatus::Playing { @@ -659,6 +702,7 @@ fn run_playback_loop( update_status(status, &status_arc); } Command::Seek(target_us, request_id) => { + wheel_starting = true; if request_id < seek_id { continue; } @@ -716,6 +760,7 @@ fn run_playback_loop( } Command::SetTrackMuted(track_idx, muted) => { rebuild_chords = true; + key_sim.cancel_wheel(); if muted { muted_tracks.insert(track_idx); let owners: Vec<_> = live_notes.iter() @@ -770,6 +815,7 @@ fn run_playback_loop( || ((note_processing.merge_notes || settings.merge_notes) && note_processing.merge_tolerance_ms != settings.merge_tolerance_ms); rebuild_chords = true; + key_sim.cancel_wheel(); note_processing = settings; } } @@ -806,6 +852,7 @@ fn run_playback_loop( } } Command::LoadSong(new_song) => { + wheel_starting = true; chord_notes.clear(); triggered_chords.clear(); rebuild_notes = note_processing.merge_notes; @@ -878,6 +925,7 @@ fn run_playback_loop( return; } Command::SetListenMode(enabled) => { + wheel_starting = true; if listen_mode != enabled { midi.clear(&mut key_sim, &audio_synth); } listen_mode = enabled; if let Some(ref synth) = audio_synth { @@ -926,6 +974,7 @@ fn run_playback_loop( } Command::SetTrackVolume(track_idx, vol) => { rebuild_chords = true; + key_sim.cancel_wheel(); track_volumes.insert(track_idx, vol.clamp(0.0, 1.0)); if let Some(ref synth) = audio_synth { synth.set_track_volume(track_idx, vol); @@ -939,9 +988,11 @@ fn run_playback_loop( } } Command::SetMapping(new_mapping) => { + wheel_starting = true; rebuild_chords = true; midi.clear(&mut key_sim, &audio_synth); key_sim.release_all(&all_keys); + key_sim.set_wheel_context(new_mapping.wheel_context()); key_releases.clear(); active_held_notes.clear(); live_notes.clear(); @@ -1020,26 +1071,29 @@ fn run_playback_loop( } } if rebuild_chords { + key_sim.cancel_wheel(); rebuild_chords = false; // A pad attack replaces the whole chord. Keep its remaining members // suppressed if controls change between their staggered onsets. let frozen: Vec<_> = chord_notes.iter().map(|note| note.filter(|note| triggered_chords.contains(¬e.chord_id))).collect(); let next_chord_id = frozen.iter().flatten().map(|note| note.chord_id + 1).max().unwrap_or(0); - let mut planned = if note_processing.auto_chord && !mapping.chord_pads().is_empty() { - current_song.as_ref().map(|song| detect_chords( - &song.events, mapping.chord_pads(), note_processing.chord_detection_milliseconds, - |index, event| frozen.get(index).is_none_or(Option::is_none) + let mut planned = current_song.as_ref().map(|song| { + let enabled = |index: usize, event: &crate::midi::TimedNoteEvent| frozen.get(index).is_none_or(Option::is_none) && !muted_tracks.contains(&event.track_index) - && ((event.velocity as f32) * track_volumes.get(&event.track_index).copied().unwrap_or(1.0)).round() > 0.0, - |pitch, time_us| { + && ((event.velocity as f32) * track_volumes.get(&event.track_index).copied().unwrap_or(1.0)).round() > 0.0; + let transform = |pitch, time_us: u64| { let marker = key_markers_enabled.then(|| get_active_marker(&key_markers, (time_us + 10_000) / 1000)).flatten(); process_note_pitch(pitch, marker.map(|m| m.key_offset).unwrap_or(key_offset), marker.and_then(|m| m.transpose).unwrap_or(transpose_mode), min_pitch, max_pitch, &playable_notes) - }, - )).unwrap_or_default() - } else { Vec::new() }; + }; + if let (Some(frets), Some(wheel)) = (mapping.frets(), mapping.chord_wheel()) { + detect_frets(&song.events, frets, wheel.positions.len(), 0, enabled, transform) + } else if !mapping.chord_pads().is_empty() { + detect_chords(&song.events, mapping.chord_pads(), note_processing.chord_detection_milliseconds, enabled, transform) + } else { Vec::new() } + }).unwrap_or_default(); for note in planned.iter_mut().flatten() { note.chord_id += next_chord_id; } if frozen.iter().any(Option::is_some) { planned.resize(frozen.len(), None); @@ -1048,6 +1102,10 @@ fn run_playback_loop( } } chord_notes = planned; + wheel_attacks = current_song.as_ref().map(|song| chord_notes.iter().enumerate().filter_map(|(index, note)| { + match note { Some(ChordNote { binding: ChordBinding::Wheel(slot) | ChordBinding::Frets { slot, .. }, trigger: true, .. }) => + Some((index, song.events[index].time_us, *slot)), _ => None } + }).collect()).unwrap_or_default(); } midi.snapshot.listen_mode = listen_mode; @@ -1058,10 +1116,16 @@ fn run_playback_loop( .is_some_and(|synth| synth.output_status().state == ServiceState::Ready); } if !config_available.load(Ordering::Acquire) { midi.gate(false, &mut key_sim, &audio_synth); } midi.tick(Instant::now(), &mut key_sim, &audio_synth, repress_gap_ms); + key_sim.tick_wheel(); if let Some(error) = key_sim.take_error() { + if mapping.chord_wheel().is_some() { + let mut state = key_sim.wheel_state(); + state.error = Some(error.clone()); + callback(PlayerEvent::ChordWheelChanged(state)); + } midi.stop(&mut key_sim, &audio_synth); - #[cfg(not(windows))] - if send_input && !listen_mode && status == PlaybackStatus::Playing { + if (cfg!(not(windows)) || mapping.chord_wheel().is_some()) + && send_input && !listen_mode && status == PlaybackStatus::Playing { // A missing keyboard backend cannot play the remaining game // notes. Keep the current position available for permission // recovery instead of silently advancing through the song. @@ -1091,6 +1155,11 @@ fn run_playback_loop( #[cfg(not(windows))] { keyboard_error = Some(error); } } + let next_wheel_state = key_sim.wheel_state(); + if wheel_state != next_wheel_state { + wheel_state = next_wheel_state; + callback(PlayerEvent::ChordWheelChanged(wheel_state.clone())); + } #[cfg(windows)] { midi.snapshot.keyboard_available = key_sim.is_ready() && midi.snapshot.error.is_none(); } #[cfg(not(windows))] @@ -1160,6 +1229,10 @@ fn run_playback_loop( // 2. If not playing, sleep coarse and continue if status != PlaybackStatus::Playing { + if key_sim.wheel_active() { + sleeper.sleep(Duration::from_millis(1)); + continue; + } let wait = key_releases.next_deadline() .map(|deadline| deadline.saturating_duration_since(Instant::now())) .unwrap_or(Duration::from_millis(15)); @@ -1177,6 +1250,27 @@ fn run_playback_loop( } }; + if send_input && !listen_mode && (!mapping.chord_pads().is_empty() || mapping.frets().is_some()) { + if let Some(config) = mapping.chord_wheel() { + let next = wheel_attacks.get(wheel_attacks.partition_point(|(index, _, _)| *index < event_idx)); + if let Some(&(owner, at_us, slot)) = next { + let budget_us = key_sim.wheel_preparation_ms(config, slot) * 1000; + let until_us = (at_us.saturating_sub(current_us) as f64 / speed) as u64; + if until_us <= budget_us && !key_sim.wheel_active() { + key_sim.prepare_wheel(config, mapping.game_process_names(), slot, owner); + } + // Starting and seeking get preparation time before the song + // clock runs. Later page changes must fit between attacks. + if wheel_starting && until_us <= budget_us && !key_sim.wheel_ready(owner) { + sleeper.sleep(Duration::from_millis(1)); + last_instant = Instant::now(); + continue; + } + } + } + } + wheel_starting = false; + // Chase held source notes only once playback is running. A stopped or // paused seek remains silent, and ordinary ticks never scan old events. let mut restored_owners: VecDeque<_> = if restore_notes { @@ -1186,6 +1280,10 @@ fn run_playback_loop( // 3. Check if song finished if event_idx >= song.events.len() && control_idx >= song.control_events.len() { + if key_sim.wheel_active() { + sleeper.sleep(Duration::from_millis(1)); + continue; + } // A tap may outlast its MIDI note, including the final note in the song. if let Some(deadline) = next_note_deadline(&key_releases, &live_notes) { pending_command = cmd_rx.recv_timeout(deadline.saturating_duration_since(Instant::now()).min(Duration::from_millis(10))).ok(); @@ -1225,8 +1323,15 @@ fn run_playback_loop( let release_wait = next_note_deadline(&key_releases, &live_notes) .map(|deadline| deadline.saturating_duration_since(Instant::now()).as_micros() as u64) .unwrap_or(10_000); - let chunk_us = real_wait_us.min(10_000).min(release_wait); - pending_command = cmd_rx.recv_timeout(Duration::from_micros(chunk_us)).ok(); + let chunk_us = real_wait_us.min(if key_sim.wheel_active() { 1_000 } else { 10_000 }).min(release_wait); + if key_sim.wheel_active() { + // Windows channel timeouts can round a 1ms wait up to a + // system timer tick. Use the transport's precise sleeper + // while preparing the shared mouse so waits do not pile up. + sleeper.sleep(Duration::from_micros(chunk_us)); + } else { + pending_command = cmd_rx.recv_timeout(Duration::from_micros(chunk_us)).ok(); + } let elapsed = last_instant.elapsed(); last_instant = Instant::now(); current_us += (elapsed.as_micros() as f64 * speed).round() as u64; @@ -1323,7 +1428,10 @@ fn run_playback_loop( let chord_pad = chord.is_some_and(|note| note.trigger && !restoring); let mapped_stroke = match chord { // Pads are one timed attack, never retriggered by a historical seek/resume. - Some(note) => (note.trigger && !restoring).then_some(note.stroke), + Some(note) => match note.binding { + ChordBinding::Key(stroke) => (note.trigger && !restoring).then_some(stroke), + ChordBinding::Wheel(_) | ChordBinding::Frets { .. } => None, + }, None => mapped_note.and_then(|n| mapping.get_stroke(n)), }; let mapped_key = mapped_stroke.map(|stroke| stroke.key); @@ -1363,6 +1471,16 @@ fn run_playback_loop( } } } else if send_input { + if let Some(chord) = chord.filter(|note| note.trigger && !restoring) { + triggered_chords.insert(chord.chord_id); + if matches!(chord.binding, ChordBinding::Wheel(_)) { + key_sim.strum_wheel(owner_index, tap_duration_ms); + } else if let (ChordBinding::Frets { strings, .. }, Some(frets)) = (chord.binding, mapping.frets()) { + let strokes: Vec<_> = frets.string_strokes.iter().enumerate() + .filter_map(|(index, &stroke)| (strings & (1 << index) != 0).then_some(stroke)).collect(); + key_sim.pluck_wheel(owner_index, &strokes, tap_duration_ms); + } + } if let Some(stroke) = mapped_stroke { if let Some(chord) = chord.filter(|note| note.trigger && !restoring) { triggered_chords.insert(chord.chord_id); diff --git a/crates/amp-core/src/player/note_processing.rs b/crates/amp-core/src/player/note_processing.rs index c4aa6510..66e2eb73 100644 --- a/crates/amp-core/src/player/note_processing.rs +++ b/crates/amp-core/src/player/note_processing.rs @@ -1,13 +1,12 @@ //! Song-only note preparation. The source MIDI and its control events remain unchanged. use std::collections::{HashMap, VecDeque}; -use crate::{input::{KeyStroke, mapping::ChordPad}, midi::TimedNoteEvent}; +use crate::{input::mapping::{ChordBinding, ChordPad, FretMapping}, midi::TimedNoteEvent}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct NoteProcessingSettings { pub merge_notes: bool, pub merge_tolerance_ms: u64, - pub auto_chord: bool, pub chord_detection_milliseconds: u64, } @@ -16,7 +15,6 @@ impl Default for NoteProcessingSettings { Self { merge_notes: crate::settings::defaults::value("/defaultMergeNotes"), merge_tolerance_ms: crate::settings::defaults::value("/defaultMergeToleranceMs"), - auto_chord: crate::settings::defaults::value("/defaultAutoChord"), chord_detection_milliseconds: crate::settings::defaults::value("/defaultChordDetectionMilliseconds"), } } @@ -25,7 +23,7 @@ impl Default for NoteProcessingSettings { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct ChordNote { pub chord_id: usize, - pub stroke: KeyStroke, + pub binding: ChordBinding, /// Only the first NoteOn presses the pad. Every other member is suppressed. pub trigger: bool, } @@ -103,6 +101,52 @@ fn pitch_classes(notes: impl IntoIterator) -> u16 { notes.into_iter().fold(0, |mask, pitch| mask | (1 << (pitch % 12))) } +/// The game selects one common fret for all strings. Find an exact voicing for +/// each onset group; unsupported groups remain silent rather than arpeggiated. +pub(super) fn detect_frets(events: &[TimedNoteEvent], frets: &FretMapping, + slots: usize, tolerance_ms: u64, enabled: F, transform: G) -> Vec> +where F: Fn(usize, &TimedNoteEvent) -> bool, G: Fn(u8, u64) -> Option { + let mut result = vec![None; events.len()]; + if slots == 0 { return result; } + let partners = partners(events); + let candidates: Vec<_> = events.iter().enumerate().filter_map(|(index, event)| { + (event.is_note_on && event.velocity > 0 && partners[index].is_some() && enabled(index, event)).then_some(index) + }).collect(); + let tolerance_us = tolerance_ms.saturating_mul(1000); + let mut cursor = 0; + let mut previous_fret = 0; + let mut group_id = 0; + while cursor < candidates.len() { + let first = cursor; + let at = events[candidates[first]].time_us; + cursor += 1; + while cursor < candidates.len() && events[candidates[cursor]].time_us <= at.saturating_add(tolerance_us) { cursor += 1; } + let members = &candidates[first..cursor]; + let Some(pitches) = members.iter().map(|&index| transform(events[index].note, at)).collect::>>() else { continue }; + let mut choices = Vec::new(); + for fret in 0..=frets.fret_count { + let mut strings = 0u8; + let valid = pitches.iter().all(|&pitch| { + if let Some(string) = frets.tuning.iter().position(|&open| open.checked_add(fret) == Some(pitch)) { + strings |= 1 << string; + true + } else { false } + }); + if valid { choices.push((fret, strings)); } + } + let Some((fret, strings)) = choices.into_iter().min_by_key(|&(fret, _)| (fret.abs_diff(previous_fret), fret)) else { continue }; + previous_fret = fret; + let slot = if fret == 0 { usize::from(frets.fret_count).div_ceil(slots) * slots } else { usize::from(fret - 1) }; + for (member, &index) in members.iter().enumerate() { + let assignment = ChordNote { chord_id: group_id, binding: ChordBinding::Frets { slot, strings }, trigger: member == 0 }; + result[index] = Some(assignment); + result[partners[index].expect("Complete fret candidate")] = Some(ChordNote { trigger: false, ..assignment }); + } + group_id += 1; + } + result +} + /// Plan pad replacement without modifying events used by the synthesizer or UI. /// Chord membership spans enabled tracks, but only note starts within the first /// member's tolerance form a group. Transposition/markers are evaluated at that @@ -138,13 +182,21 @@ where cursor += 1; } let members = &candidates[first..cursor]; - if members.len() < 3 { continue; } + if members.len() < 2 { continue; } let Some(transformed) = members.iter().map(|index| transform(events[*index].note, start_us)) .collect::>>() else { continue }; + // Octave folding can put an accompaniment voice below the source bass. + // Keep the original voice ordering when choosing a slash chord. + let bass = members.iter().zip(&transformed).min_by_key(|(index, _)| events[**index].note) + .map(|(_, pitch)| pitch % 12); let mask = pitch_classes(transformed); - let Some(pad) = pad_masks.iter().position(|pad_mask| *pad_mask == mask && mask != 0) else { continue }; + let Some(pad) = pad_masks.iter().enumerate() + .filter(|(index, pad_mask)| **pad_mask == mask && mask != 0 + && pads[*index].bass_pitch_class.is_none_or(|pitch| Some(pitch) == bass)) + .max_by_key(|(index, _)| (pads[*index].bass_pitch_class.is_some(), std::cmp::Reverse(*index))) + .map(|(index, _)| index) else { continue }; for (member, &index) in members.iter().enumerate() { - let assignment = ChordNote { chord_id, stroke: pads[pad].stroke, trigger: member == 0 }; + let assignment = ChordNote { chord_id, binding: pads[pad].binding, trigger: member == 0 }; result[index] = Some(assignment); result[partners[index].expect("Complete candidate note")] = Some(ChordNote { trigger: false, ..assignment }); } @@ -170,7 +222,7 @@ mod tests { fn sorted(mut events: Vec) -> Vec { events.sort(); events } fn pad(pitches: &[u8]) -> ChordPad { - ChordPad { pitch_classes: pitches.to_vec(), stroke: parse_key_stroke("q").unwrap() } + ChordPad { pitch_classes: pitches.to_vec(), binding: ChordBinding::Key(parse_key_stroke("q").unwrap()), bass_pitch_class: None } } #[test] diff --git a/crates/amp-core/src/settings/defaults.json b/crates/amp-core/src/settings/defaults.json index 2c2a4619..db38c1d5 100644 --- a/crates/amp-core/src/settings/defaults.json +++ b/crates/amp-core/src/settings/defaults.json @@ -131,7 +131,6 @@ "pageCaching": true, "cacheAutoClean": "weekly", "cacheMaxSizeMb": 500, - "defaultAutoChord": false, "defaultChordDetectionMilliseconds": 30, "defaultEnableKeyChangeMarkers": true } diff --git a/crates/amp-core/src/settings/legacy.rs b/crates/amp-core/src/settings/legacy.rs index e0fdda2f..d57f2aa3 100644 --- a/crates/amp-core/src/settings/legacy.rs +++ b/crates/amp-core/src/settings/legacy.rs @@ -392,8 +392,7 @@ pub(super) fn selections( settings["selectedInstrumentIds"][&game.config.id] = json!(instrument.id); if let Some(selected) = raw.get("SelectedLayoutName") { if let Some(layout) = instrument - .supported_layouts - .iter() + .all_layouts() .filter_map(|id| { layouts .values() diff --git a/crates/amp-core/tests/chord_mapping_tests.rs b/crates/amp-core/tests/chord_mapping_tests.rs index 16a6f640..d8dd856e 100644 --- a/crates/amp-core/tests/chord_mapping_tests.rs +++ b/crates/amp-core/tests/chord_mapping_tests.rs @@ -8,13 +8,17 @@ fn bundled() -> (InstrumentConfigJson, KeyboardLayoutJson) { "../../../src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json" )).unwrap(); let layout = serde_json::from_str(include_str!( - "../../../src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json" + "../../../src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Chords.json" )).unwrap(); (instrument, layout) } fn melody_mapping(instrument: &InstrumentConfigJson, layout: &KeyboardLayoutJson) -> NoteKeyMapping { - let pairs: Vec<_> = instrument.notes.iter().copied().zip(layout.keys.iter().cloned()).collect(); + // Retain coverage of custom combined mappings independently of the split mode layouts. + let melody: KeyboardLayoutJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json" + )).unwrap(); + let pairs: Vec<_> = instrument.notes.iter().copied().zip(melody.keys).collect(); NoteKeyMapping::from_key_pairs(KeyboardLayout::Diatonic21, &pairs).with_pedal_bindings(layout) } @@ -35,7 +39,7 @@ fn bundled_ukulele_maps_all_seven_pads_without_changing_notes_or_pedals() { for ((pad, pitches), binding) in mapping.chord_pads().iter() .zip(expected_pitch_classes).zip(["q", "w", "e", "r", "t", "y", "u"]) { assert_eq!(pad.pitch_classes, pitches); - assert_eq!(pad.stroke, parse_key_stroke(binding).unwrap()); + assert_eq!(pad.binding, amp_core::input::mapping::ChordBinding::Key(parse_key_stroke(binding).unwrap())); } assert_eq!(mapping.playable_notes(), original.playable_notes()); assert_eq!(mapping.pitch_range(), original.pitch_range()); @@ -46,6 +50,33 @@ fn bundled_ukulele_maps_all_seven_pads_without_changing_notes_or_pedals() { } } +#[test] +fn genshin_chord_layout_preserves_detection_pitches_without_melody_output() { + let layout: KeyboardLayoutJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Chords.json" + )).unwrap(); + let melody: KeyboardLayoutJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json" + )).unwrap(); + assert!(layout.keys.is_empty()); + assert!(melody.chord_keys.is_none()); + for source in [include_str!("../../../src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json"), + include_str!("../../../src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/LingeringEuphonia.json")] { + let instrument: InstrumentConfigJson = serde_json::from_str(source).unwrap(); + assert_eq!(instrument.keyboard_layouts, [melody.id.clone()]); + assert_eq!(instrument.chord_layouts, [layout.id.clone()]); + assert!(instrument.keys.is_some()); + let chord_mapping = NoteKeyMapping::from_pairs(KeyboardLayout::Diatonic21, &[]).with_chord_pads(&instrument, &layout); + assert_eq!(chord_mapping.chord_pads().len(), 7); + assert_eq!(chord_mapping.pitch_range(), (48, 71)); + assert_eq!(chord_mapping.playable_notes().len(), 14); + assert!(instrument.notes.iter().all(|pitch| chord_mapping.get_stroke(*pitch).is_none())); + let melody_only = melody_mapping(&instrument, &melody).with_chord_pads(&instrument, &melody); + assert!(melody_only.chord_pads().is_empty()); + assert!(instrument.notes.iter().all(|pitch| melody_only.get_stroke(*pitch).is_some())); + } +} + #[test] fn unsupported_layout_does_not_acquire_pads_or_retain_previous_bindings() { let (instrument, layout) = bundled(); @@ -80,22 +111,22 @@ fn invalid_and_missing_bindings_do_not_shift_pad_associations() { let expected = [(0, "q"), (2, "^A"), (4, "u")]; assert_eq!(mapping.chord_pads().len(), expected.len()); for (pad, (index, binding)) in mapping.chord_pads().iter().zip(expected) { - assert_eq!(pad.pitch_classes, instrument.chord_pads[index].pitch_classes); - assert_eq!(pad.stroke, parse_key_stroke(binding).unwrap()); + assert_eq!(pad.pitch_classes, instrument.chords[index].pitch_classes); + assert_eq!(pad.binding, amp_core::input::mapping::ChordBinding::Key(parse_key_stroke(binding).unwrap())); } } #[test] fn invalid_pitch_classes_do_not_shift_later_pad_bindings() { let (mut instrument, layout) = bundled(); - instrument.chord_pads[1].pitch_classes = vec![2, 5]; - instrument.chord_pads[3].pitch_classes = vec![0, 5, 12]; + instrument.chords[1].pitch_classes = vec![2]; + instrument.chords[3].pitch_classes = vec![0, 5, 12]; let mapping = melody_mapping(&instrument, &layout).with_chord_pads(&instrument, &layout); let expected = [(0, "q"), (2, "e"), (4, "t"), (5, "y"), (6, "u")]; assert_eq!(mapping.chord_pads().len(), expected.len()); for (pad, (index, binding)) in mapping.chord_pads().iter().zip(expected) { - assert_eq!(pad.pitch_classes, instrument.chord_pads[index].pitch_classes); - assert_eq!(pad.stroke, parse_key_stroke(binding).unwrap()); + assert_eq!(pad.pitch_classes, instrument.chords[index].pitch_classes); + assert_eq!(pad.binding, amp_core::input::mapping::ChordBinding::Key(parse_key_stroke(binding).unwrap())); } } @@ -119,3 +150,48 @@ fn panic_release_keys_include_pad_only_keys_and_modifiers() { assert!(!cleared.all_keys().contains(&OutputKey::Shift)); assert!(!cleared.all_keys().contains(&OutputKey::Space)); } + +#[test] +fn nte_wheel_maps_all_pages_without_acquiring_piano_keys() { + use amp_core::input::mapping::ChordBinding; + let instrument: InstrumentConfigJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Strings/Guitar.json" + )).unwrap(); + let layout: KeyboardLayoutJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/NTE_Chord_Wheel.json" + )).unwrap(); + let mapping = NoteKeyMapping::from_pairs(KeyboardLayout::Chromatic36, &[]).with_chord_pads(&instrument, &layout); + assert_eq!(mapping.chord_pads().len(), 24); + assert_eq!(mapping.pitch_range(), (52, 87)); + assert_eq!(mapping.playable_notes().len(), 36); + assert!(mapping.all_keys().is_empty()); + for (index, pad) in mapping.chord_pads().iter().enumerate() { + assert_eq!(pad.binding, ChordBinding::Wheel(index)); + assert_eq!(pad.pitch_classes, instrument.chords[index].pitch_classes); + } + assert!(mapping.chord_pads()[12].pitch_classes.len() == 2); + assert_eq!(mapping.chord_pads()[18].bass_pitch_class, Some(11)); + assert!(instrument.notes.iter().all(|pitch| mapping.get_stroke(*pitch).is_none())); +} + +#[test] +fn configured_chord_mode_selects_existing_pad_or_wheel_bindings() { + use amp_core::input::{config::ChordMode, mapping::ChordBinding}; + let (mut instrument, mut layout) = bundled(); + let wheel: KeyboardLayoutJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/NTE_Chord_Wheel.json" + )).unwrap(); + layout.chord_wheel = wheel.chord_wheel; + let pads = melody_mapping(&instrument, &layout).with_chord_pads(&instrument, &layout); + assert!(pads.chord_wheel().is_none()); + assert!(matches!(pads.chord_pads()[0].binding, ChordBinding::Key(_))); + assert!(pads.get_stroke(60).is_some()); + instrument.chord_mode = ChordMode::Wheel; + let radial = melody_mapping(&instrument, &layout).with_chord_pads(&instrument, &layout); + assert!(radial.chord_wheel().is_some()); + assert!(matches!(radial.chord_pads()[0].binding, ChordBinding::Wheel(0))); + assert!(radial.get_stroke(60).is_none()); + layout.chord_wheel = None; + let invalid = melody_mapping(&instrument, &layout).with_chord_pads(&instrument, &layout); + assert!(invalid.chord_pads().is_empty(), "wheel mode must not fall back to pad keys"); +} diff --git a/crates/amp-core/tests/config_sync_tests.rs b/crates/amp-core/tests/config_sync_tests.rs index afb60c9a..06165bf3 100644 --- a/crates/amp-core/tests/config_sync_tests.rs +++ b/crates/amp-core/tests/config_sync_tests.rs @@ -24,7 +24,7 @@ impl Drop for TestDirectory { } const GAME: &str = r#"{"id":"NTE","displayName":"Neverness to Everness"}"#; -const INSTRUMENT: &str = r#"{"id":"guitar","name":"Guitar","notes":[60,61],"supportedLayouts":["qwerty"]}"#; +const INSTRUMENT: &str = r#"{"id":"guitar","name":"Guitar","notes":[60,61],"keyboardLayouts":["qwerty"]}"#; const LAYOUT: &str = r#"{"id":"qwerty","name":"QWERTY","keys":["a","Enter"]}"#; #[test] @@ -89,13 +89,13 @@ fn all_bundled_defaults_pass_validation() { assert!(game_issues.is_empty(), "{game_issues:#?}"); assert!(layout_issues.is_empty(), "{layout_issues:#?}"); assert!(!games.is_empty() && !layouts.is_empty()); - assert_eq!(layouts.len(), 23); + assert_eq!(layouts.len(), 26); for game in &games { if let Some(id) = &game.config.default_layout { assert!(layouts.contains_key(&id.to_lowercase()), "missing game default {id}"); } for instrument in &game.instruments { - for id in &instrument.supported_layouts { + for id in instrument.all_layouts() { assert!(layouts.contains_key(&id.to_lowercase()), "missing instrument layout {id}"); } } @@ -108,22 +108,22 @@ fn watches_config_bursts_and_root_recreation_but_ignores_other_appdata() { let (tx, rx) = mpsc::channel(); let _watcher = DirectoryWatcher::watch_configs(&temp.0, move || { let _ = tx.send(()); }).unwrap(); temp.write("settings.json", "{}"); - assert!(rx.recv_timeout(Duration::from_millis(750)).is_err()); + assert!(rx.recv_timeout(Duration::from_millis(750)).is_err(), "Unrelated app data should not trigger a reload"); for _ in 0..5 { temp.write("Games/NTE/game.json", GAME); std::thread::sleep(Duration::from_millis(80)); } - rx.recv_timeout(Duration::from_secs(5)).unwrap(); + rx.recv_timeout(Duration::from_secs(5)).expect("config burst should trigger a reload"); assert!(rx.recv_timeout(Duration::from_millis(750)).is_err(), "Burst should trigger one reload"); // Remove only the verified test root's Games child; the watcher stays attached to its parent. let games = temp.0.join("Games"); assert_eq!(games.parent(), Some(temp.0.as_path())); fs::remove_dir_all(&games).unwrap(); - rx.recv_timeout(Duration::from_secs(5)).unwrap(); + rx.recv_timeout(Duration::from_secs(5)).expect("Games removal should trigger a reload"); temp.write("Games/NTE/game.json", GAME); - rx.recv_timeout(Duration::from_secs(5)).unwrap(); + rx.recv_timeout(Duration::from_secs(5)).expect("Games recreation should trigger a reload"); temp.write("KeyboardLayouts/qwerty.json", LAYOUT); - rx.recv_timeout(Duration::from_secs(5)).unwrap(); + rx.recv_timeout(Duration::from_secs(5)).expect("layout creation should trigger a reload"); } #[test] @@ -132,13 +132,15 @@ fn config_removal_is_reported_before_the_debounced_reload() { let path = temp.write("Games/NTE/Instruments/Guitar.json", INSTRUMENT); let (tx, rx) = mpsc::channel(); let removed = tx.clone(); - let _watcher = DirectoryWatcher::watch_configs_with_removals(&temp.0, + // Event paths may use a different spelling of the watched directory. + let watch_root = temp.0.join("Games").join(".."); + let _watcher = DirectoryWatcher::watch_configs_with_removals(&watch_root, move || { let _ = removed.send("removed"); }, move || { let _ = tx.send("reloaded"); }).unwrap(); fs::remove_file(path).unwrap(); - assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), "removed"); + assert_eq!(rx.recv_timeout(Duration::from_secs(3)).expect("removal notification"), "removed"); loop { - if rx.recv_timeout(Duration::from_secs(3)).unwrap() == "reloaded" { break; } + if rx.recv_timeout(Duration::from_secs(3)).expect("reload after removal") == "reloaded" { break; } } } @@ -160,10 +162,12 @@ fn unavailable_config_stops_playback_and_blocks_native_restarts_until_replaced() assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), PlaybackStatus::Playing); engine.set_config_available(false); assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), PlaybackStatus::Stopped); - engine.play(); + let rejected = engine.request_play().recv_timeout(Duration::from_secs(2)).unwrap(); + assert!(rejected.unwrap_err().contains("valid layout")); assert!(rx.recv_timeout(Duration::from_millis(150)).is_err()); + engine.set_mapping(NoteKeyMapping::from_pairs(KeyboardLayout::Diatonic21, &[(60, 'a')])); engine.set_config_available(true); assert!(rx.recv_timeout(Duration::from_millis(150)).is_err(), "Restoring a file must not resume automatically"); - engine.play(); + engine.request_play().recv_timeout(Duration::from_secs(2)).unwrap().unwrap(); assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), PlaybackStatus::Playing); } diff --git a/crates/amp-core/tests/config_tests.rs b/crates/amp-core/tests/config_tests.rs index 163424a4..1a79948d 100644 --- a/crates/amp-core/tests/config_tests.rs +++ b/crates/amp-core/tests/config_tests.rs @@ -25,7 +25,7 @@ fn matrix_configs_preserve_rows_and_normalize_legacy_playback_fields() { use amp_core::{InstrumentConfigJson, KeyboardLayoutJson}; let instrument: InstrumentConfigJson = serde_json::from_str(r#"{ "id":"piano", "name":"Piano", "layoutStyle":"heartopia", - "keys":[[72,null,73],[60,61]], "supportedLayouts":["qwerty"] + "keys":[[72,null,73],[60,61]], "keyboardLayouts":["qwerty"] }"#).unwrap(); assert_eq!(instrument.notes, [72, 73, 60, 61]); assert_eq!(instrument.keys.as_ref().unwrap()[0], [Some(72), None, Some(73)]); @@ -41,6 +41,61 @@ fn matrix_configs_preserve_rows_and_normalize_legacy_playback_fields() { assert!(serde_json::from_str::(r#"{"id":"x","name":"X","layoutStyle":"unknown"}"#).is_err()); } +#[test] +fn instrument_layout_groups_and_chords_serialize_canonically() { + use amp_core::InstrumentConfigJson; + let instrument: InstrumentConfigJson = serde_json::from_str(r#"{ + "id":"guitar", "name":"Guitar", "layoutStyle":"guitar", "notes":[60], + "keyboardLayouts":["keyboard"], "chordLayouts":["wheel"], "fretLayouts":["frets"], + "chords":[{"name":"C","pitchClasses":[0,4,7]}], + "guitar":{"tuning":[64,59,55,50,45,40],"fretCount":24} + }"#).unwrap(); + assert!(instrument.supports_keyboard_layout("KEYBOARD")); + assert!(instrument.supports_chord_layout("wheel")); + assert!(instrument.supports_fret_layout("frets")); + assert!(!instrument.supports_chord_layout("keyboard")); + assert_eq!(instrument.all_layouts().map(String::as_str).collect::>(), ["keyboard", "wheel", "frets"]); + assert!(instrument.guitar.as_ref().unwrap().is_valid()); + let json = serde_json::to_value(instrument).unwrap(); + assert_eq!(json["layoutStyle"], "guitar"); + assert_eq!(json["chords"][0]["name"], "C"); + assert!(json.get("supportedLayouts").is_none()); + assert!(json.get("chordPads").is_none()); +} + +#[test] +fn legacy_chord_definitions_remain_readable_but_explicit_layout_groups_win() { + use amp_core::InstrumentConfigJson; + let legacy: InstrumentConfigJson = serde_json::from_str(r#"{ + "id":"ukulele","name":"Ukulele", "supportedLayouts":["qwerty"], + "chordPads":[{"name":"C","pitchClasses":[0,4,7]}] + }"#).unwrap(); + assert_eq!(legacy.keyboard_layouts, ["qwerty"]); + assert_eq!(legacy.chord_layouts, ["qwerty"]); + assert_eq!(legacy.chords.len(), 1); + let explicit: InstrumentConfigJson = serde_json::from_str(r#"{ + "id":"ukulele","name":"Ukulele", "supportedLayouts":["old"], + "keyboardLayouts":["new"], "chordLayouts":[], + "chords":[{"name":"C","pitchClasses":[0,4,7]}] + }"#).unwrap(); + assert_eq!(explicit.keyboard_layouts, ["new"]); + assert!(explicit.chord_layouts.is_empty()); +} + +#[test] +fn guitar_pitch_and_binding_configuration_rejects_unplayable_input() { + use amp_core::{FretLayoutJson, GuitarConfigJson}; + let mut guitar = GuitarConfigJson { tuning: vec![64, 59, 55, 50, 45, 40], fret_count: 24 }; + assert!(guitar.is_valid()); + guitar.tuning[0] = 120; + assert!(!guitar.is_valid()); + let mut layout = FretLayoutJson { string_keys: vec!["6".into(), "5".into(), "4".into(), "3".into(), "2".into(), "1".into()], + wheel_layout: "NTE_Chord_Wheel".into(), mode_key: "z".into() }; + assert!(layout.is_valid()); + layout.string_keys[0] = "NotAKey".into(); + assert!(!layout.is_valid()); +} + #[test] fn test_scan_keyboard_layouts() { let temp_dir = std::env::temp_dir().join(format!("amp_cfg_test_{}", uuid::Uuid::new_v4())); @@ -96,7 +151,7 @@ fn test_scan_games_recursive_instruments() { "name": "Leaping Spirit Piano", "type": "diatonic21", "notes": [72, 74, 76, 77, 79, 81, 83, 60, 62, 64, 65, 67, 69, 71, 48, 50, 52, 53, 55, 57, 59], - "supportedLayouts": ["genshin_qwerty"] + "keyboardLayouts": ["genshin_qwerty"] }"#; fs::write(instruments_pianos.join("LeapingSpiritPiano.json"), piano_json).unwrap(); @@ -106,7 +161,7 @@ fn test_scan_games_recursive_instruments() { "name": "Djem Djem Drum", "type": "drum8", "notes": [60, 62, 64, 65, 67, 69, 71, 72], - "supportedLayouts": ["genshin_qwerty_drums"] + "keyboardLayouts": ["genshin_qwerty_drums"] }"#; fs::write(instruments_drums.join("DjemDjemDrum.json"), drum_json).unwrap(); diff --git a/crates/amp-core/tests/defaults_sync_tests.rs b/crates/amp-core/tests/defaults_sync_tests.rs new file mode 100644 index 00000000..a983e846 --- /dev/null +++ b/crates/amp-core/tests/defaults_sync_tests.rs @@ -0,0 +1,564 @@ +use amp_core::input::defaults_sync::*; +use std::fs; +use std::path::{Path, PathBuf}; + +struct Profile(PathBuf); +impl Profile { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "amp-defaults-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + fn write(&self, path: &str, value: &[u8]) { + let path = self.0.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, value).unwrap(); + } + fn read(&self, path: &str) -> Vec { + fs::read(self.0.join(path)).unwrap() + } +} +impl Drop for Profile { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +const LAYOUT_PATH: &str = "KeyboardLayouts/keys.json"; +const OLD: &[u8] = br#"{"id":"keys","name":"Keys","keys":["q"]}"#; +const NEW: &[u8] = br#"{"id":"keys","name":"Keys","keys":["w"]}"#; +const LOCAL: &[u8] = br#"{"id":"keys","name":"My keys","keys":["a"],"custom":true}"#; +const INSTRUMENT_PATH: &str = "Games/Test/Instruments/Strings/UkuleleChords.json"; +const INSTRUMENT: &[u8] = br#"{"id":"ukulele-chords","name":"Ukulele (Chords)","chordLayouts":["keys"],"chords":[{"name":"C","pitchClasses":[0,4,7]}]}"#; + +fn bundled<'a>(path: &'a str, contents: &'a [u8]) -> BundledDefault<'a> { + BundledDefault { + path: Path::new(path), + contents, + } +} +fn choice(conflict: &DefaultConfigConflict, action: DefaultConfigAction) -> DefaultConfigChoice { + DefaultConfigChoice { + id: conflict.id.clone(), + token: conflict.token.clone(), + action, + } +} + +#[test] +fn first_install_and_new_release_install_missing_defaults_without_touching_local_files() { + let profile = Profile::new(); + let old = [bundled(LAYOUT_PATH, OLD)]; + let first = sync_defaults(&profile.0, &old).unwrap(); + assert_eq!(first.added_files, [LAYOUT_PATH]); + assert!(first.conflicts.is_empty()); + profile.write(LAYOUT_PATH, LOCAL); + profile.write("settings.json", b"keep settings"); + let updated = [ + bundled(LAYOUT_PATH, OLD), + bundled(INSTRUMENT_PATH, INSTRUMENT), + ]; + let report = sync_defaults(&profile.0, &updated).unwrap(); + assert_eq!(report.added_files, [INSTRUMENT_PATH]); + assert_eq!( + report.conflicts.len(), + 1, + "changed local content needs fresh review" + ); + assert_eq!(profile.read(LAYOUT_PATH), LOCAL); + assert_eq!(profile.read(INSTRUMENT_PATH), INSTRUMENT); + assert_eq!(profile.read("settings.json"), b"keep settings"); + fs::remove_file(profile.0.join(INSTRUMENT_PATH)).unwrap(); + assert_eq!( + sync_defaults(&profile.0, &updated).unwrap().added_files, + [INSTRUMENT_PATH] + ); +} + +#[test] +fn legacy_profiles_review_existing_differences_and_ignore_json_formatting() { + let profile = Profile::new(); + profile.write( + LAYOUT_PATH, + b"{\n \"keys\": [\"q\"], \"name\": \"Keys\", \"id\": \"keys\"\n}", + ); + assert!(sync_defaults(&profile.0, &[bundled(LAYOUT_PATH, OLD)]) + .unwrap() + .conflicts + .is_empty()); + // A pre-history installation cannot establish an old baseline from local content. + fs::remove_file(profile.0.join("configuration-state.json")).unwrap(); + profile.write(LAYOUT_PATH, LOCAL); + let report = sync_defaults(&profile.0, &[bundled(LAYOUT_PATH, NEW)]).unwrap(); + assert_eq!(report.conflicts.len(), 1); + assert_eq!(report.conflicts[0].current_json.as_bytes(), LOCAL); + assert_eq!(report.conflicts[0].bundled_json.as_bytes(), NEW); + assert_eq!(profile.read(LAYOUT_PATH), LOCAL); + assert_eq!( + sync_defaults(&profile.0, &[bundled(LAYOUT_PATH, NEW)]) + .unwrap() + .conflicts + .len(), + 1, + "deferring the dialog does not accept a revision" + ); +} + +#[test] +fn older_app_clear_data_cannot_reuse_the_new_apps_review_decision() { + let profile = Profile::new(); + profile.write(LAYOUT_PATH, OLD); + let new = [bundled(LAYOUT_PATH, NEW)]; + let pending = sync_defaults(&profile.0, &new).unwrap(); + resolve_default_updates( + &profile.0, + &new, + &[choice(&pending.conflicts[0], DefaultConfigAction::Replace)], + &[], + ) + .unwrap(); + assert!(sync_defaults(&profile.0, &new) + .unwrap() + .conflicts + .is_empty()); + // An old build resets its JSON but does not know about the new history file. + profile.write(LAYOUT_PATH, OLD); + assert_eq!(sync_defaults(&profile.0, &new).unwrap().conflicts.len(), 1); + assert_eq!( + profile.read(LAYOUT_PATH), + OLD, + "review never overwrites without consent" + ); +} + +#[test] +fn keep_is_bound_to_local_content_and_legacy_history_cannot_suppress_differences() { + let profile = Profile::new(); + profile.write(LAYOUT_PATH, LOCAL); + let defaults = [bundled(LAYOUT_PATH, NEW)]; + let pending = sync_defaults(&profile.0, &defaults).unwrap(); + resolve_default_updates( + &profile.0, + &defaults, + &[choice(&pending.conflicts[0], DefaultConfigAction::Keep)], + &[], + ) + .unwrap(); + assert!(sync_defaults(&profile.0, &defaults) + .unwrap() + .conflicts + .is_empty()); + profile.write(LAYOUT_PATH, OLD); + assert_eq!( + sync_defaults(&profile.0, &defaults) + .unwrap() + .conflicts + .len(), + 1 + ); + let mut history: serde_json::Value = + serde_json::from_slice(&profile.read("configuration-state.json")).unwrap(); + history[LAYOUT_PATH] = history[LAYOUT_PATH]["bundled"].clone(); + profile.write( + "configuration-state.json", + &serde_json::to_vec(&history).unwrap(), + ); + assert_eq!( + sync_defaults(&profile.0, &defaults) + .unwrap() + .conflicts + .len(), + 1 + ); +} + +#[test] +fn explicit_in_app_edits_advance_only_the_local_content_already_reviewed() { + let profile = Profile::new(); + let defaults = [bundled(LAYOUT_PATH, OLD)]; + sync_defaults(&profile.0, &defaults).unwrap(); + profile.write(LAYOUT_PATH, LOCAL); + record_reviewed_edit(&profile.0, Path::new(LAYOUT_PATH), OLD, LOCAL).unwrap(); + assert!(sync_defaults(&profile.0, &defaults) + .unwrap() + .conflicts + .is_empty()); + profile.write(LAYOUT_PATH, NEW); + record_reviewed_edit(&profile.0, Path::new(LAYOUT_PATH), NEW, LOCAL).unwrap(); + assert_eq!( + sync_defaults(&profile.0, &defaults) + .unwrap() + .conflicts + .len(), + 1, + "an unrelated external edit cannot inherit earlier consent" + ); +} + +#[test] +fn review_state_filename_change_preserves_decisions_and_prefers_the_new_file() { + let profile = Profile::new(); + profile.write(LAYOUT_PATH, LOCAL); + let defaults = [bundled(LAYOUT_PATH, NEW)]; + let pending = sync_defaults(&profile.0, &defaults).unwrap(); + resolve_default_updates( + &profile.0, + &defaults, + &[choice(&pending.conflicts[0], DefaultConfigAction::Keep)], + &[], + ) + .unwrap(); + let saved = profile.read("configuration-state.json"); + fs::rename( + profile.0.join("configuration-state.json"), + profile.0.join(".bundled-defaults.json"), + ) + .unwrap(); + assert!(!sync_defaults(&profile.0, &defaults).unwrap().needs_review()); + assert_eq!(profile.read("configuration-state.json"), saved); + assert!(!profile.0.join(".bundled-defaults.json").exists()); + profile.write(".bundled-defaults.json", b"{}"); + assert!(!sync_defaults(&profile.0, &defaults).unwrap().needs_review()); + assert_eq!(profile.read("configuration-state.json"), saved); + assert!(!profile.0.join(".bundled-defaults.json").exists()); +} + +#[test] +fn keep_remembers_only_this_revision_and_replace_backs_up_the_original_bytes() { + let profile = Profile::new(); + let old = [bundled(LAYOUT_PATH, OLD)]; + sync_defaults(&profile.0, &old).unwrap(); + profile.write(LAYOUT_PATH, LOCAL); + let new = [bundled(LAYOUT_PATH, NEW)]; + let pending = sync_defaults(&profile.0, &new).unwrap(); + let kept = resolve_default_updates( + &profile.0, + &new, + &[choice(&pending.conflicts[0], DefaultConfigAction::Keep)], + &[], + ) + .unwrap(); + assert!(kept.conflicts.is_empty()); + assert!(kept.backup_directory.is_none()); + assert_eq!(profile.read(LAYOUT_PATH), LOCAL); + assert!(sync_defaults(&profile.0, &new) + .unwrap() + .conflicts + .is_empty()); + let later = [bundled(LAYOUT_PATH, OLD)]; + let pending = sync_defaults(&profile.0, &later).unwrap(); + let replaced = resolve_default_updates( + &profile.0, + &later, + &[choice(&pending.conflicts[0], DefaultConfigAction::Replace)], + &[], + ) + .unwrap(); + assert!(replaced.conflicts.is_empty()); + let backup = profile + .0 + .join(replaced.backup_directory.unwrap()) + .join(LAYOUT_PATH); + assert_eq!(fs::read(backup).unwrap(), LOCAL); + assert_eq!(profile.read(LAYOUT_PATH), OLD); +} + +#[test] +fn changed_files_invalidate_the_entire_consent_batch_before_any_replacement() { + let profile = Profile::new(); + profile.write(LAYOUT_PATH, OLD); + profile.write(INSTRUMENT_PATH, b"{"); + let defaults = [ + bundled(LAYOUT_PATH, NEW), + bundled(INSTRUMENT_PATH, INSTRUMENT), + ]; + let report = sync_defaults(&profile.0, &defaults).unwrap(); + let choices: Vec<_> = report + .conflicts + .iter() + .map(|c| choice(c, DefaultConfigAction::Replace)) + .collect(); + profile.write(INSTRUMENT_PATH, b"edited during review"); + assert!( + resolve_default_updates(&profile.0, &defaults, &choices, &[]) + .unwrap_err() + .contains("changed") + ); + assert_eq!(profile.read(LAYOUT_PATH), OLD); + assert_eq!(profile.read(INSTRUMENT_PATH), b"edited during review"); + assert!(!profile.0.join("ConfigBackups").exists()); +} + +#[test] +fn renamed_files_and_layout_aliases_are_reviewed_in_place_without_duplicate_ids() { + let profile = Profile::new(); + let renamed = "KeyboardLayouts/custom-name.json"; + profile.write(renamed, LOCAL); + let defaults = [bundled(LAYOUT_PATH, NEW)]; + let pending = sync_defaults(&profile.0, &defaults).unwrap(); + assert_eq!(pending.conflicts[0].path, renamed); + assert!(!profile.0.join(LAYOUT_PATH).exists()); + resolve_default_updates( + &profile.0, + &defaults, + &[choice(&pending.conflicts[0], DefaultConfigAction::Replace)], + &[], + ) + .unwrap(); + assert_eq!(profile.read(renamed), NEW); + assert!(sync_defaults(&profile.0, &defaults) + .unwrap() + .conflicts + .is_empty()); + assert!(!profile.0.join(LAYOUT_PATH).exists()); + profile.write( + "KeyboardLayouts/keys.json", + br#"{"id":"other","name":"Other","keys":["a"]}"#, + ); + assert!(sync_defaults(&profile.0, &defaults).unwrap().issues[0] + .message + .contains("Multiple existing files")); +} + +#[test] +fn relocated_instruments_are_not_duplicated_and_other_games_do_not_conflict() { + let profile = Profile::new(); + let moved = "Games/Test/Instruments/Custom/Ukulele.json"; + profile.write(moved, INSTRUMENT); + profile.write("Games/Other/Instruments/Ukulele.json", INSTRUMENT); + let report = sync_defaults(&profile.0, &[bundled(INSTRUMENT_PATH, INSTRUMENT)]).unwrap(); + assert!(report.added_files.is_empty()); + assert!(report.conflicts.is_empty()); + assert!(!profile.0.join(INSTRUMENT_PATH).exists()); +} + +#[test] +fn renamed_game_folders_receive_new_instruments_and_assets_beside_their_game_json() { + let profile = Profile::new(); + let game = br#"{"id":"test","displayName":"Test"}"#; + profile.write("Games/Renamed/game.json", game); + let report = sync_defaults( + &profile.0, + &[ + bundled("Games/Test/game.json", game), + bundled(INSTRUMENT_PATH, INSTRUMENT), + bundled("Games/Test/icon.png", b"icon"), + ], + ) + .unwrap(); + assert!(report.conflicts.is_empty()); + assert_eq!( + profile.read("Games/Renamed/Instruments/Strings/UkuleleChords.json"), + INSTRUMENT + ); + assert_eq!(profile.read("Games/Renamed/icon.png"), b"icon"); + assert!(!profile.0.join("Games/Test").exists()); +} + +#[test] +fn malformed_json_is_a_reviewable_conflict_and_unknown_decisions_are_rejected() { + let profile = Profile::new(); + profile.write(LAYOUT_PATH, b"{ invalid json"); + let defaults = [bundled(LAYOUT_PATH, OLD)]; + let pending = sync_defaults(&profile.0, &defaults).unwrap(); + assert_eq!(pending.conflicts.len(), 1); + let invalid = DefaultConfigChoice { + id: "../outside.json".into(), + token: pending.conflicts[0].token.clone(), + action: DefaultConfigAction::Replace, + }; + assert!(resolve_default_updates(&profile.0, &defaults, &[invalid], &[]).is_err()); + assert_eq!(profile.read(LAYOUT_PATH), b"{ invalid json"); + let duplicate = [ + choice(&pending.conflicts[0], DefaultConfigAction::Keep), + choice(&pending.conflicts[0], DefaultConfigAction::Replace), + ]; + assert!( + resolve_default_updates(&profile.0, &defaults, &duplicate, &[]) + .unwrap_err() + .contains("Duplicate") + ); + assert_eq!(profile.read(LAYOUT_PATH), b"{ invalid json"); +} + +#[test] +fn bundled_paths_cannot_escape_appdata_and_assets_never_replace_local_files() { + let profile = Profile::new(); + let bad = [bundled("../outside.json", OLD)]; + assert!(sync_defaults(&profile.0, &bad).is_err()); + profile.write("Games/Test/icon.png", b"custom icon"); + let defaults = [bundled("Games/Test/icon.png", b"bundled icon")]; + sync_defaults(&profile.0, &defaults).unwrap(); + assert_eq!(profile.read("Games/Test/icon.png"), b"custom icon"); +} + +fn set_time(profile: &Profile, path: &str, seconds: u64) { + fs::File::options() + .write(true) + .open(profile.0.join(path)) + .unwrap() + .set_times( + fs::FileTimes::new() + .set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(seconds)), + ) + .unwrap(); +} + +#[test] +fn duplicate_id_replacement_deletes_only_older_files_and_does_not_recreate_them() { + let profile = Profile::new(); + let newer = "KeyboardLayouts/renamed-keys.json"; + profile.write(LAYOUT_PATH, OLD); + profile.write(newer, LOCAL); + profile.write( + "KeyboardLayouts/unrelated.json", + br#"{"id":"unrelated","name":"Other","keys":["z"]}"#, + ); + set_time(&profile, LAYOUT_PATH, 1_600_000_000); + set_time(&profile, newer, 1_700_000_000); + let defaults = [bundled(LAYOUT_PATH, NEW)]; + let report = sync_defaults(&profile.0, &defaults).unwrap(); + assert_eq!(report.duplicates.len(), 1); + assert_eq!(report.duplicates[0].keep.path, newer); + assert_eq!(report.duplicates[0].older_files[0].path, LAYOUT_PATH); + assert!(report.needs_review()); + let duplicate = DefaultConfigChoice { + id: report.duplicates[0].id.clone(), + token: report.duplicates[0].token.clone(), + action: DefaultConfigAction::Replace, + }; + let kept = resolve_default_updates( + &profile.0, + &defaults, + &[choice(&report.conflicts[0], DefaultConfigAction::Keep)], + &[duplicate], + ) + .unwrap(); + assert!(kept.duplicates.is_empty()); + assert!(!profile.0.join(LAYOUT_PATH).exists()); + assert_eq!(profile.read(newer), LOCAL); + assert!(profile.0.join("KeyboardLayouts/unrelated.json").exists()); + assert_eq!( + profile.read(&format!("{}/{LAYOUT_PATH}", kept.backup_directory.unwrap())), + OLD + ); + let next_launch = sync_defaults(&profile.0, &defaults).unwrap(); + assert!(!next_launch.needs_review()); + assert!(next_launch.added_files.is_empty()); + assert!(!profile.0.join(LAYOUT_PATH).exists()); +} + +#[test] +fn bundle_replacement_and_duplicate_cleanup_can_be_approved_together() { + let profile = Profile::new(); + let newer = "KeyboardLayouts/newer.json"; + profile.write(LAYOUT_PATH, OLD); + profile.write(newer, LOCAL); + set_time(&profile, LAYOUT_PATH, 1_600_000_000); + set_time(&profile, newer, 1_700_000_000); + let defaults = [bundled(LAYOUT_PATH, NEW)]; + let report = sync_defaults(&profile.0, &defaults).unwrap(); + let duplicate = DefaultConfigChoice { + id: report.duplicates[0].id.clone(), + token: report.duplicates[0].token.clone(), + action: DefaultConfigAction::Replace, + }; + let updated = resolve_default_updates( + &profile.0, + &defaults, + &[choice(&report.conflicts[0], DefaultConfigAction::Replace)], + &[duplicate], + ) + .unwrap(); + assert!(!updated.needs_review()); + assert!(!profile.0.join(LAYOUT_PATH).exists()); + assert_eq!(profile.read(newer), NEW); + let backups = updated.backup_directory.unwrap(); + assert_eq!(profile.read(&format!("{backups}/{LAYOUT_PATH}")), OLD); + assert_eq!(profile.read(&format!("{backups}/{newer}")), LOCAL); +} + +#[test] +fn duplicate_ids_are_case_insensitive_scoped_by_game_and_preserved_without_consent() { + let profile = Profile::new(); + profile.write( + "Games/A/Instruments/one.json", + br#"{"id":"STRINGS","name":"First","notes":[60]}"#, + ); + profile.write( + "Games/A/Instruments/two.json", + br#"{"id":"strings","name":"Second","notes":[62]}"#, + ); + profile.write( + "Games/B/Instruments/one.json", + br#"{"id":"strings","name":"Other game","notes":[64]}"#, + ); + let report = sync_defaults(&profile.0, &[]).unwrap(); + assert_eq!(report.duplicates.len(), 1); + let duplicate = &report.duplicates[0]; + let kept = resolve_default_updates( + &profile.0, + &[], + &[], + &[DefaultConfigChoice { + id: duplicate.id.clone(), + token: duplicate.token.clone(), + action: DefaultConfigAction::Keep, + }], + ) + .unwrap(); + assert_eq!( + kept.duplicates.len(), + 1, + "unresolved duplicates remain reviewable on the next launch" + ); + assert!(profile.0.join("Games/A/Instruments/one.json").exists()); + assert!(profile.0.join("Games/A/Instruments/two.json").exists()); + assert!(profile.0.join("Games/B/Instruments/one.json").exists()); +} + +#[test] +fn changing_a_duplicate_during_review_or_failing_backup_prevents_its_deletion() { + let profile = Profile::new(); + profile.write(LAYOUT_PATH, OLD); + profile.write("KeyboardLayouts/newer.json", LOCAL); + set_time(&profile, LAYOUT_PATH, 1_600_000_000); + set_time(&profile, "KeyboardLayouts/newer.json", 1_700_000_000); + let report = sync_defaults(&profile.0, &[]).unwrap(); + let duplicate = &report.duplicates[0]; + let choices = [DefaultConfigChoice { + id: duplicate.id.clone(), + token: duplicate.token.clone(), + action: DefaultConfigAction::Replace, + }]; + profile.write(LAYOUT_PATH, NEW); + assert!(resolve_default_updates(&profile.0, &[], &[], &choices) + .unwrap_err() + .contains("changed")); + assert_eq!(profile.read(LAYOUT_PATH), NEW); + let report = sync_defaults(&profile.0, &[]).unwrap(); + let duplicate = &report.duplicates[0]; + let choices = [DefaultConfigChoice { + id: duplicate.id.clone(), + token: duplicate.token.clone(), + action: DefaultConfigAction::Replace, + }]; + profile.write("ConfigBackups", b"a file blocks the backup directory"); + assert!(resolve_default_updates(&profile.0, &[], &[], &choices).is_err()); + assert!(profile.0.join(LAYOUT_PATH).exists()); + assert!(profile.0.join("KeyboardLayouts/newer.json").exists()); +} + +#[cfg(unix)] +#[test] +fn symlinked_configuration_directories_are_never_written_through() { + let profile = Profile::new(); + let outside = Profile::new(); + std::os::unix::fs::symlink(&outside.0, profile.0.join("KeyboardLayouts")).unwrap(); + assert!(sync_defaults(&profile.0, &[bundled(LAYOUT_PATH, OLD)]).is_err()); + assert!(!outside.0.join("keys.json").exists()); +} diff --git a/crates/amp-core/tests/legacy_song_settings_migration_tests.rs b/crates/amp-core/tests/legacy_song_settings_migration_tests.rs index 496f5289..bcf03c8f 100644 --- a/crates/amp-core/tests/legacy_song_settings_migration_tests.rs +++ b/crates/amp-core/tests/legacy_song_settings_migration_tests.rs @@ -38,45 +38,39 @@ fn context(game: &str, instrument: &str) -> SongSettingsContext { } #[test] -fn canonical_auto_chord_libraries_need_no_detect_chord_pads_column() { - let f = Fixture::legacy("AutoChord INTEGER, Transpose INTEGER"); - f.conn().execute("UPDATE Songs SET AutoChord = 1", []).unwrap(); +fn legacy_transpose_and_removed_chord_columns_open_cleanly() { + let f = Fixture::legacy("AutoChord INTEGER, DetectChordPads INTEGER, Transpose INTEGER"); + f.conn().execute("UPDATE Songs SET AutoChord = 1, DetectChordPads = 1", []).unwrap(); let reported = Cell::new(0); for _ in 0..2 { let db = LibraryDatabase::new_with_migration_callback(Some(f.path.clone()), || reported.set(reported.get() + 1)).unwrap(); let song = db.get_song_by_id("song").unwrap().unwrap(); - assert_eq!(song.auto_chord, Some(true)); assert_eq!(song.transpose, 0, "Legacy null transpose means Ignore"); assert_eq!(song.tap_threshold_ms, Some(0)); assert_eq!(db.get_all_songs().unwrap().len(), 1); assert_eq!(db.get_song_by_path("song.mid").unwrap().unwrap().id, "song"); db.set_queue(&["song".to_string()]).unwrap(); - assert_eq!(db.get_queue_songs().unwrap()[0].auto_chord, Some(true)); + assert_eq!(db.get_queue_songs().unwrap().len(), 1); assert_eq!(reported.get(), 1); } - let columns: Vec = f.conn().prepare("PRAGMA table_info(Songs)").unwrap() - .query_map([], |row| row.get(1)).unwrap().map(Result::unwrap).collect(); - assert!(!columns.iter().any(|c| c == "DetectChordPads")); } #[test] fn old_column_aliases_are_preserved_under_the_current_names() { - let f = Fixture::legacy("Author TEXT, DefaultKey INTEGER, DetectChordPads INTEGER"); - f.conn().execute("UPDATE Songs SET Author = 'Artist', DefaultKey = -3, DetectChordPads = 1", []).unwrap(); + let f = Fixture::legacy("Author TEXT, DefaultKey INTEGER"); + f.conn().execute("UPDATE Songs SET Author = 'Artist', DefaultKey = -3", []).unwrap(); let db = f.open(); let song = db.get_song_by_id("song").unwrap().unwrap(); assert_eq!(song.artist.as_deref(), Some("Artist")); assert_eq!(song.base_key, Some(-3)); - assert_eq!(song.auto_chord, Some(true)); } #[test] fn partial_alias_upgrades_fill_only_missing_values_and_do_not_restore_cleared_values() { - let f = Fixture::legacy("AutoChord INTEGER, DetectChordPads INTEGER, Artist TEXT, Author TEXT, BaseKey INTEGER, DefaultKey INTEGER"); - f.conn().execute("UPDATE Songs SET AutoChord = 0, DetectChordPads = 1, Author = 'Old', DefaultKey = 3", []).unwrap(); + let f = Fixture::legacy("Artist TEXT, Author TEXT, BaseKey INTEGER, DefaultKey INTEGER"); + f.conn().execute("UPDATE Songs SET Author = 'Old', DefaultKey = 3", []).unwrap(); drop(f.open()); let song = f.open().get_song_by_id("song").unwrap().unwrap(); - assert_eq!(song.auto_chord, Some(false)); assert_eq!(song.artist.as_deref(), Some("Old")); assert_eq!(song.base_key, Some(3)); f.conn().execute("UPDATE Songs SET BaseKey = NULL, Artist = NULL", []).unwrap(); @@ -87,22 +81,22 @@ fn partial_alias_upgrades_fill_only_missing_values_and_do_not_restore_cleared_va #[test] fn every_existing_instrument_gets_technical_settings_with_newer_overrides_preserved() { - let f = Fixture::legacy("AutoChord INTEGER"); + let f = Fixture::legacy("ChordDetectionMilliseconds INTEGER"); let db = f.open(); let markers = r#"[{"TimeMs":1200,"KeyOffset":3,"Transpose":2,"Label":"Chorus"}]"#; f.conn().execute("UPDATE Songs SET Title = 'Shared title', Artist = 'Shared artist', Album = 'Shared album', BaseKey = 2, Key = -1, Transpose = 3, Speed = 1.25, Bpm = 110, DisabledTracks = '0,2', - MergeNotes = 1, MergeMilliseconds = 40, HoldNotes = 1, TapThresholdMs = 60, AutoChord = 1, + MergeNotes = 1, MergeMilliseconds = 40, HoldNotes = 1, TapThresholdMs = 60, ChordDetectionMilliseconds = 45, KeyChanges = ?1, EnableKeyChangeMarkers = 0", [markers]).unwrap(); f.conn().execute("INSERT INTO SongSettings VALUES ('song', 'a', '', ?1)", [json!({"speed": 1.5, "bpm": null}).to_string()]).unwrap(); f.conn().execute("INSERT INTO SongSettings VALUES ('song', 'a', 'piano', ?1)", - [json!({"key": 7, "keyChanges": null, "disabledTracks": null, "autoChord": false}).to_string()]).unwrap(); + [json!({"key": 7, "keyChanges": null, "disabledTracks": null, "chordDetectionMilliseconds": 15}).to_string()]).unwrap(); let contexts = vec![context("a", "lyre"), context("a", "piano"), context("b", "piano")]; assert_eq!(db.migrate_legacy_song_settings(&contexts, || {}).unwrap(), 3); let baseline = json!({ "baseKey": 2, "key": -1, "transpose": 3, "speed": 1.25, "bpm": 110.0, "disabledTracks": "0,2", "mergeNotes": true, "mergeMilliseconds": 40, "holdNotes": true, - "tapThresholdMs": 60, "autoChord": true, "chordDetectionMilliseconds": 45, + "tapThresholdMs": 60, "chordDetectionMilliseconds": 45, "keyChanges": markers, "enableKeyChangeMarkers": false, }); assert_eq!(f.profile(&contexts[2]), baseline); @@ -113,7 +107,7 @@ fn every_existing_instrument_gets_technical_settings_with_newer_overrides_preser inherited["key"] = json!(7); inherited["keyChanges"] = Value::Null; inherited["disabledTracks"] = Value::Null; - inherited["autoChord"] = json!(false); + inherited["chordDetectionMilliseconds"] = json!(15); assert_eq!(f.profile(&contexts[1]), inherited); let resolved = db.resolve_song_settings(db.get_all_songs().unwrap(), Some(&contexts[0])).unwrap(); assert_eq!(resolved[0].title.as_deref(), Some("Shared title")); @@ -131,7 +125,7 @@ fn every_existing_instrument_gets_technical_settings_with_newer_overrides_preser #[test] fn unavailable_targets_and_failed_copies_remain_retryable_without_partial_writes() { - let f = Fixture::legacy("AutoChord INTEGER"); + let f = Fixture::legacy("ChordDetectionMilliseconds INTEGER"); let db = f.open(); assert_eq!(db.migrate_legacy_song_settings(&[], || panic!("no targets")).unwrap(), 0); let contexts = vec![context("a", "lyre"), context("a", "piano")]; diff --git a/crates/amp-core/tests/library_sync_tests.rs b/crates/amp-core/tests/library_sync_tests.rs index 73d015c3..27473c0e 100644 --- a/crates/amp-core/tests/library_sync_tests.rs +++ b/crates/amp-core/tests/library_sync_tests.rs @@ -64,7 +64,6 @@ fn imports_with_missing_options_use_the_shared_json_defaults() { assert_eq!(song.speed, expected["defaultSpeed"].as_f64()); assert_eq!(song.merge_milliseconds.map(u64::from), expected["defaultMergeToleranceMs"].as_u64()); assert_eq!(song.tap_threshold_ms.map(u64::from), expected["defaultTapThresholdMs"].as_u64()); - assert_eq!(song.auto_chord, expected["defaultAutoChord"].as_bool()); assert_eq!(song.chord_detection_milliseconds.map(u64::from), expected["defaultChordDetectionMilliseconds"].as_u64()); assert_eq!(song.enable_key_change_markers, expected["defaultEnableKeyChangeMarkers"].as_bool()); } diff --git a/crates/amp-core/tests/library_tests.rs b/crates/amp-core/tests/library_tests.rs index ee03336e..3f5d0278 100644 --- a/crates/amp-core/tests/library_tests.rs +++ b/crates/amp-core/tests/library_tests.rs @@ -39,7 +39,6 @@ fn test_library_schema_and_crud() { image_path: None, cached_duration_ms: Some(60000), cached_native_bpm: Some(120.0), - auto_chord: None, chord_detection_milliseconds: None, key_changes: None, enable_key_change_markers: Some(true), @@ -67,7 +66,6 @@ fn test_library_schema_and_crud() { speed: Some(1.25), hold_notes: Some(true), tap_threshold_ms: Some(100), - auto_chord: Some(true), chord_detection_milliseconds: Some(45), enable_key_change_markers: Some(true), }; @@ -104,7 +102,7 @@ fn test_library_schema_and_crud() { title: "Edited details".into(), artist: "".into(), album: "".into(), base_key: None, key: -3, transpose: 3, bpm: None, speed: 1.5, merge_notes: true, merge_milliseconds: 175, hold_notes: true, tap_threshold_ms: 0, - auto_chord: false, enable_key_change_markers: true, + enable_key_change_markers: true, date_added: "2026-10-22T02:00:00Z".into(), }; db.update_song_details("test-song-1", &details, None).unwrap(); @@ -182,10 +180,8 @@ fn test_legacy_database_migration() { ImagePath TEXT, CachedDurationMs INTEGER, CachedNativeBpm REAL, - AutoChord INTEGER, ChordDetectionMilliseconds INTEGER, KeyChanges TEXT, - DetectChordPads INTEGER, EnableKeyChangeMarkers INTEGER );", [], @@ -320,7 +316,6 @@ fn test_queue_persistence_and_reorder() { image_path: None, cached_duration_ms: Some(60000), cached_native_bpm: Some(120.0), - auto_chord: None, chord_detection_milliseconds: None, key_changes: None, enable_key_change_markers: Some(true), diff --git a/crates/amp-core/tests/onboarding_song_defaults_tests.rs b/crates/amp-core/tests/onboarding_song_defaults_tests.rs index 66b723a8..4efaa4f2 100644 --- a/crates/amp-core/tests/onboarding_song_defaults_tests.rs +++ b/crates/amp-core/tests/onboarding_song_defaults_tests.rs @@ -16,10 +16,10 @@ impl Fixture { conn.execute_batch("ALTER TABLE Songs ADD COLUMN Description TEXT; INSERT INTO Songs (Id, Path, Title, Artist, Album, DateAdded, BaseKey, Key, Transpose, Speed, Bpm, DisabledTracks, MergeNotes, MergeMilliseconds, HoldNotes, TapThresholdMs, - AutoChord, ChordDetectionMilliseconds, KeyChanges, EnableKeyChangeMarkers, + ChordDetectionMilliseconds, KeyChanges, EnableKeyChangeMarkers, ImagePath, CachedDurationMs, CachedNativeBpm, FileHash, Description) VALUES ('song', 'missing.mid', 'My title', 'My artist', 'My album', '2026-01-01', 5, -2, 3, - 1.75, 143, '1,3', 1, 87, 0, 300, 1, 45, + 1.75, 143, '1,3', 1, 87, 0, 300, 45, '[{\"TimeMs\":1200,\"KeyOffset\":3,\"Label\":\"Chorus\"}]', 0, 'cover.png', 90000, 144, 'hash', 'My description');").unwrap(); // Include the instrument copies made during legacy migration, plus a @@ -58,7 +58,7 @@ fn defaults() -> SongDefaults { default_hold_notes: true, default_tap_threshold_ms: 50, default_merge_notes: false, default_merge_tolerance_ms: 25, // Options absent from these onboarding pages must remain untouched. - default_auto_chord: false, default_enable_key_change_markers: true, + default_enable_key_change_markers: true, ..SongDefaults::default() } } diff --git a/crates/amp-core/tests/playback_chord_wheel_tests.rs b/crates/amp-core/tests/playback_chord_wheel_tests.rs new file mode 100644 index 00000000..36f8329b --- /dev/null +++ b/crates/amp-core/tests/playback_chord_wheel_tests.rs @@ -0,0 +1,408 @@ +use amp_core::{ + input::{chord_wheel::WheelButton, simulator::KeyboardOutput}, + parse_key_stroke, + player::NoteProcessingSettings, + InstrumentConfigJson, KeyboardLayout, KeyboardLayoutJson, NoteKeyMapping, OutputKey, + ParsedMidi, PlaybackEngine, PlaybackStatus, PlayerEvent, TempoMap, TimedNoteEvent, +}; +use std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, + }, + time::{Duration, Instant}, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Input { + Key(OutputKey, bool), + Move([u16; 2]), + Button(WheelButton, bool), +} + +type Inputs = Arc>>; + +struct Output { + inputs: Inputs, + focused: Arc, +} + +impl Output { + fn record(&self, input: Input) { + self.inputs.lock().unwrap().push((Instant::now(), input)); + } +} + +impl KeyboardOutput for Output { + fn key(&mut self, key: OutputKey, up: bool) -> Result<(), String> { + self.record(Input::Key(key, up)); + Ok(()) + } + fn wheel_move(&mut self, processes: &[String], point: [u16; 2]) -> Result<(), String> { + assert!(processes.contains(&"HTGame".to_string())); + self.record(Input::Move(point)); + Ok(()) + } + fn wheel_button(&mut self, button: WheelButton, up: bool) -> Result<(), String> { + self.record(Input::Button(button, up)); + Ok(()) + } + fn wheel_focused(&self) -> bool { + self.focused.load(Ordering::Acquire) + } +} + +fn notes(at: u64, pitches: &[u8]) -> Vec { + pitches + .iter() + .flat_map(|¬e| { + [ + TimedNoteEvent { + time_us: at, + note, + velocity: 90, + is_note_on: true, + channel: 0, + track_index: 0, + }, + TimedNoteEvent { + time_us: at + 100_000, + note, + velocity: 0, + is_note_on: false, + channel: 0, + track_index: 0, + }, + ] + }) + .collect() +} + +struct Harness { + engine: PlaybackEngine, + inputs: Inputs, + focused: Arc, + errors: Arc>>, + layout: KeyboardLayoutJson, +} + +impl Harness { + fn wait(&self, description: &str, mut predicate: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(5); + while !predicate() { + assert!( + Instant::now() < deadline, + "timed out waiting for {description}; status: {:?}; errors: {:?}; inputs: {:?}", + self.engine.get_status(), + self.errors.lock().unwrap(), + self.events() + ); + std::thread::sleep(Duration::from_millis(2)); + } + } + + fn new(events: Vec) -> Self { Self::new_mode(events, false) } + + fn new_mode(mut events: Vec, fret_mode: bool) -> Self { + let instrument: InstrumentConfigJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Strings/Guitar.json" + )).unwrap(); + let layout: KeyboardLayoutJson = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/NTE_Chord_Wheel.json" + )) + .unwrap(); + let base = NoteKeyMapping::from_pairs(KeyboardLayout::Chromatic36, &[]); + let mapping = if fret_mode { + let fret_layout = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/NTE_Fret_Wheel.json" + )).unwrap(); + base.with_frets(&instrument, &fret_layout, layout.chord_wheel.as_ref().unwrap()) + } else { base.with_chord_pads(&instrument, &layout) }.with_game_target( + &serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/Games/Neverness to Everness/game.json" + )) + .unwrap(), + ); + if fret_mode { assert!(mapping.frets().is_some()); } + else { assert_eq!(mapping.chord_pads().len(), 24); } + events.sort(); + let song = ParsedMidi { + title: "Wheel playback regression".into(), + duration_us: events + .last() + .map_or(1_000_000, |event| event.time_us + 50_000), + bpm: 120.0, + ppqn: 480, + tracks: vec![], + events, + control_events: vec![], + tempo_map: TempoMap::new(480, &[]), + key_signatures: vec![], + }; + let inputs = Arc::new(Mutex::new(Vec::new())); + let focused = Arc::new(AtomicBool::new(true)); + let errors = Arc::new(Mutex::new(Vec::new())); + let captured_errors = errors.clone(); + let engine = PlaybackEngine::new(Some(song), mapping, true, None, move |event| { + if let PlayerEvent::ChordWheelChanged(state) = event { + if let Some(error) = state.error { + captured_errors.lock().unwrap().push(error); + } + } + }); + engine.set_keyboard_output(Some(Box::new(Output { + inputs: inputs.clone(), + focused: focused.clone(), + }))); + engine.set_listen_mode(false); + engine.set_note_timing(true, 0); + engine.set_hold_delay_ms(20); + engine.set_note_processing(NoteProcessingSettings { + merge_notes: false, + merge_tolerance_ms: 25, + chord_detection_milliseconds: 30, + }); + engine.flush().unwrap(); + Self { + engine, + inputs, + focused, + errors, + layout, + } + } + + fn events(&self) -> Vec { + self.inputs + .lock() + .unwrap() + .iter() + .map(|(_, input)| input.clone()) + .collect() + } + fn count(&self, expected: Input) -> usize { + self.events() + .iter() + .filter(|input| **input == expected) + .count() + } + fn strums(&self) -> Vec { + self.inputs + .lock() + .unwrap() + .iter() + .filter_map(|(at, input)| { + (*input == Input::Button(WheelButton::Right, false)).then_some(*at) + }) + .collect() + } + fn finish(&self, expected_strums: usize) { + self.engine.play(); + self.wait("strums", || { + self.strums().len() == expected_strums + || self.engine.get_status() == PlaybackStatus::Paused + }); + assert_ne!( + self.engine.get_status(), + PlaybackStatus::Paused, + "wheel playback paused: {:?}; inputs: {:?}", + self.errors.lock().unwrap(), + self.events() + ); + self.wait("playback completion", || { + self.engine.get_status() == PlaybackStatus::Stopped + }); + let errors = self.errors.lock().unwrap().clone(); + assert!(errors.is_empty(), "{errors:?}"); + } +} + +#[test] +fn first_chord_selects_and_releases_before_strumming_without_piano_keys() { + let h = Harness::new(notes(0, &[55, 59, 62])); // G, root-position bass. + h.finish(1); + let events = h.events(); + let wheel = h.layout.chord_wheel.as_ref().unwrap(); + let selector = events + .iter() + .position(|event| *event == Input::Move(wheel.positions[0])) + .unwrap(); + let select_down = events + .iter() + .position(|event| *event == Input::Button(WheelButton::Left, false)) + .unwrap(); + let select_up = events + .iter() + .position(|event| *event == Input::Button(WheelButton::Left, true)) + .unwrap(); + let strum_down = events + .iter() + .position(|event| *event == Input::Button(WheelButton::Right, false)) + .unwrap(); + let strum_up = events + .iter() + .position(|event| *event == Input::Button(WheelButton::Right, true)) + .unwrap(); + assert!( + selector < select_down + && select_down < select_up + && select_up < strum_down + && strum_down < strum_up + ); + assert_eq!(events[strum_down - 1], Input::Move(wheel.strum_position)); + assert!(!events.iter().any(|event| matches!(event, Input::Key(_, _)))); +} + +#[test] +fn fret_mode_plucks_exact_strings_at_open_twelfth_and_twenty_fourth_frets() { + for (pitches, bindings, page) in [(&[40, 45][..], &["1", "2"][..], 4), + (&[71, 76][..], &["5", "6"][..], 1), (&[88][..], &["6"][..], 3)] { + let h = Harness::new_mode(notes(0, pitches), true); + h.engine.play(); + h.wait("fret plucks", || bindings.iter().all(|binding| h.count(Input::Key(parse_key_stroke(binding).unwrap().key, false)) == 1)); + h.wait("fret completion", || h.engine.get_status() == PlaybackStatus::Stopped); + assert!(h.errors.lock().unwrap().is_empty()); + assert_eq!(h.engine.chord_wheel_state().unwrap().page, Some(page)); + for binding in bindings { assert_eq!(h.count(Input::Key(parse_key_stroke(binding).unwrap().key, true)), 1); } + assert!(h.strums().is_empty(), "fret playback must use string keys, not mouse strums"); + } +} + +#[test] +fn pausing_fret_playback_releases_all_plucked_strings() { + let h = Harness::new_mode(notes(0, &[40, 45]), true); + h.engine.set_hold_delay_ms(200); + h.engine.play(); + let key = parse_key_stroke("1").unwrap().key; + h.wait("string key down", || h.count(Input::Key(key, false)) == 1); + h.engine.pause(); h.engine.flush().unwrap(); + assert_eq!(h.count(Input::Key(key, true)), 1); + assert_eq!(h.count(Input::Key(parse_key_stroke("2").unwrap().key, true)), 1); + assert!(!h.engine.chord_wheel_state().unwrap().busy); +} + +#[test] +fn fret_groups_requiring_different_selectors_do_not_send_approximate_notes() { + let h = Harness::new_mode(notes(0, &[60, 61]), true); + h.engine.play(); + h.wait("unsupported group completion", || h.engine.get_status() == PlaybackStatus::Stopped); + assert!(h.events().is_empty()); +} + +#[test] +fn repeated_chords_reuse_the_selection_and_keep_each_strum_attack() { + let h = Harness::new([notes(0, &[55, 59, 62]), notes(100_000, &[55, 59, 62])].concat()); + h.finish(2); + assert_eq!(h.count(Input::Button(WheelButton::Left, false)), 1); + assert_eq!(h.count(Input::Button(WheelButton::Right, false)), 2); +} + +#[test] +fn automatic_pages_prepare_early_and_preserve_source_attack_intervals() { + let events = [ + notes(0, &[55, 59, 62]), + notes(800_000, &[60, 64, 67, 71]), + notes(1_600_000, &[55, 59, 62]), + ] + .concat(); + let h = Harness::new(events); + h.finish(3); + let next = parse_key_stroke("t").unwrap().key; + let previous = parse_key_stroke("r").unwrap().key; + assert_eq!(h.count(Input::Key(next, false)), 1); + assert_eq!(h.count(Input::Key(next, true)), 1); + assert_eq!(h.count(Input::Key(previous, false)), 1); + assert_eq!(h.count(Input::Key(previous, true)), 1); + assert_eq!(h.engine.chord_wheel_state().unwrap().page, Some(0)); + for pair in h.strums().windows(2) { + let interval = pair[1].duration_since(pair[0]); + assert!( + (Duration::from_millis(700)..=Duration::from_millis(900)).contains(&interval), + "page preparation changed the 800ms musical interval: {interval:?}" + ); + } +} + +#[test] +fn power_dyads_and_slash_chords_select_their_later_pages() { + for (pitches, expected_page) in [ + (&[60, 67][..], 2), + (&[59, 62, 67][..], 3), + (&[47, 50, 55][..], 3), + ] { + let h = Harness::new(notes(0, pitches)); + h.finish(1); + assert_eq!( + h.engine.chord_wheel_state().unwrap().page, + Some(expected_page) + ); + assert_eq!( + h.count(Input::Key( + parse_key_stroke(if expected_page == 3 { "r" } else { "t" }) + .unwrap() + .key, + false + )), + if expected_page == 3 { 1 } else { expected_page } + ); + let point = h.layout.chord_wheel.as_ref().unwrap().positions[0]; + assert_eq!( + h.count(Input::Move(point)), + 1, + "the selected chord is the first slot of its page" + ); + } +} + +#[test] +fn pause_and_stop_cancel_prepared_attacks_and_release_selector_buttons() { + for pause in [false, true] { + let h = Harness::new(notes(0, &[55, 59, 62])); + h.engine.play(); + h.wait("selector press", || { + h.count(Input::Button(WheelButton::Left, false)) == 1 + }); + if pause { + h.engine.pause(); + } else { + h.engine.stop(); + } + h.engine.flush().unwrap(); + assert_eq!( + h.engine.get_status(), + if pause { + PlaybackStatus::Paused + } else { + PlaybackStatus::Stopped + } + ); + assert_eq!(h.count(Input::Button(WheelButton::Left, true)), 1); + std::thread::sleep(Duration::from_millis(100)); + assert!( + h.strums().is_empty(), + "a cancelled selector must never produce a delayed strum" + ); + assert!(!h.engine.chord_wheel_state().unwrap().busy); + } +} + +#[test] +fn focus_loss_during_selection_pauses_and_releases_mouse_ownership() { + let h = Harness::new(notes(0, &[55, 59, 62])); + h.engine.play(); + h.wait("selector press", || { + h.count(Input::Button(WheelButton::Left, false)) == 1 + }); + h.focused.store(false, Ordering::Release); + h.wait("focus-loss pause", || { + h.engine.get_status() == PlaybackStatus::Paused + }); + assert_eq!(h.count(Input::Button(WheelButton::Left, true)), 1); + assert!(h.strums().is_empty()); + assert!(h + .errors + .lock() + .unwrap() + .iter() + .any(|error| error.contains("focus"))); +} diff --git a/crates/amp-core/tests/playback_note_processing_tests.rs b/crates/amp-core/tests/playback_note_processing_tests.rs index 057d23d6..9cd34e1f 100644 --- a/crates/amp-core/tests/playback_note_processing_tests.rs +++ b/crates/amp-core/tests/playback_note_processing_tests.rs @@ -53,7 +53,7 @@ fn mapping() -> NoteKeyMapping { NoteKeyMapping::from_pairs(KeyboardLayout::Diatonic21, &[(60, 'a'), (64, 'd'), (65, 'f'), (67, 'g'), (69, 'h')]) .with_chord_bindings(vec![ChordPad { - pitch_classes: vec![0, 4, 7], stroke: parse_key_stroke("q").unwrap(), + pitch_classes: vec![0, 4, 7], binding: amp_core::input::mapping::ChordBinding::Key(parse_key_stroke("q").unwrap()), bass_pitch_class: None, }]) } @@ -92,9 +92,13 @@ impl Harness { } } -fn settings(merge_notes: bool, auto_chord: bool) -> NoteProcessingSettings { +fn melody_mapping() -> NoteKeyMapping { + NoteKeyMapping::from_pairs(KeyboardLayout::Diatonic21, &[(60, 'a'), (64, 'd'), (65, 'f'), (67, 'g'), (69, 'h')]) +} + +fn settings(merge_notes: bool) -> NoteProcessingSettings { NoteProcessingSettings { - merge_notes, merge_tolerance_ms: 25, auto_chord, + merge_notes, merge_tolerance_ms: 25, chord_detection_milliseconds: 30, } } @@ -114,7 +118,7 @@ fn disabled_processing_preserves_repeated_note_attacks_and_releases() { event(0, 0, 60, true), event(60_000, 0, 60, false), event(80_000, 0, 60, true), event(140_000, 0, 60, false), ]); - h.engine.set_note_processing(settings(false, false)); + h.engine.set_note_processing(settings(false)); h.run_to_end(); assert_eq!(*h.output.lock().unwrap(), vec![ (key("a"), false), (key("a"), true), (key("a"), false), (key("a"), true), @@ -127,13 +131,13 @@ fn merging_bridges_the_gap_without_retrigger_and_disabling_restores_original_not event(0, 0, 60, true), event(60_000, 0, 60, false), event(80_000, 0, 60, true), event(140_000, 0, 60, false), ]); - h.engine.set_note_processing(settings(true, false)); + h.engine.set_note_processing(settings(true)); h.run_to_end(); assert_eq!(*h.output.lock().unwrap(), vec![(key("a"), false), (key("a"), true)]); assert_eq!(*h.hits.lock().unwrap(), vec![(60, true), (60, false)]); h.engine.stop(); - h.engine.set_note_processing(settings(false, false)); + h.engine.set_note_processing(settings(false)); h.engine.flush().unwrap(); h.output.lock().unwrap().clear(); h.hits.lock().unwrap().clear(); @@ -148,7 +152,7 @@ fn disabling_merge_during_a_bridged_gap_releases_the_hold_and_keeps_playback_pos event(0, 0, 60, true), event(60_000, 0, 60, false), event(500_000, 0, 60, true), event(560_000, 0, 60, false), ]); - let mut processing = settings(true, false); + let mut processing = settings(true); processing.merge_tolerance_ms = 500; h.engine.set_note_processing(processing); h.engine.play(); @@ -167,7 +171,7 @@ fn disabling_merge_during_a_bridged_gap_releases_the_hold_and_keeps_playback_pos #[test] fn a_cross_track_chord_taps_one_pad_and_keeps_constituent_note_glow() { let h = Harness::new(triad(67, 0, 300_000)); - h.engine.set_note_processing(settings(false, true)); + h.engine.set_note_processing(settings(false)); h.engine.play(); wait(|| h.count("q", true) == 1); wait(|| h.hits.lock().unwrap().iter().filter(|(_, on)| *on).count() == 3); @@ -185,11 +189,28 @@ fn a_cross_track_chord_taps_one_pad_and_keeps_constituent_note_glow() { assert_eq!(h.count("q", false), 1, "source note offs cannot retrigger a pad"); } +#[test] +fn separate_genshin_chord_layout_detects_midi_chords_without_note_bindings() { + let h = Harness::new(triad(67, 0, 300_000)); + let instrument = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json" + )).unwrap(); + let layout = serde_json::from_str(include_str!( + "../../../src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Chords.json" + )).unwrap(); + h.engine.set_mapping(NoteKeyMapping::from_pairs(KeyboardLayout::Diatonic21, &[]).with_chord_pads(&instrument, &layout)); + h.engine.set_note_processing(settings(false)); + h.run_to_end(); + assert_eq!(h.count("q", false), 1); + assert_eq!(h.count("q", true), 1); + for binding in ["a", "d", "g"] { assert_eq!(h.count(binding, false), 0); } +} + #[test] fn a_short_source_chord_does_not_cut_off_its_longer_pad_tap() { let h = Harness::new(triad(67, 0, 40_000)); h.engine.set_hold_delay_ms(200); - h.engine.set_note_processing(settings(false, true)); + h.engine.set_note_processing(settings(false)); h.engine.play(); wait(|| h.count("q", false) == 1); let started = Instant::now(); @@ -206,7 +227,8 @@ fn disabled_unmatched_and_muted_chords_keep_individual_melody_output() { for scenario in ["disabled", "unmatched", "muted", "zero_volume"] { let unmatched = scenario == "unmatched"; let h = Harness::new(triad(if unmatched { 69 } else { 67 }, 0, 160_000)); - h.engine.set_note_processing(settings(false, scenario != "disabled")); + h.engine.set_note_processing(settings(false)); + if scenario == "disabled" { h.engine.set_mapping(melody_mapping()); } if scenario == "muted" { h.engine.set_track_muted(1, true); } if scenario == "zero_volume" { h.engine.set_track_volume(1, 0.0); } h.run_to_end(); @@ -224,12 +246,12 @@ fn mid_chord_processing_and_track_changes_do_not_mix_pad_and_melody_output() { event(0, 0, 60, true), event(60_000, 1, 64, true), event(120_000, 2, 67, true), event(180_000, 0, 60, false), event(180_000, 1, 64, false), event(180_000, 2, 67, false), ]); - let processing = NoteProcessingSettings { chord_detection_milliseconds: 150, ..settings(false, true) }; + let processing = NoteProcessingSettings { chord_detection_milliseconds: 150, ..settings(false) }; h.engine.set_note_processing(processing); h.engine.play(); wait(|| h.count("q", false) == 1 && h.engine.get_current_time_us() >= 30_000); match change { - "disable" => h.engine.set_note_processing(settings(false, false)), + "disable" => h.engine.set_mapping(melody_mapping()), "mute" => h.engine.set_track_muted(2, true), _ => h.engine.set_track_volume(2, 0.0), } @@ -242,7 +264,7 @@ fn mid_chord_processing_and_track_changes_do_not_mix_pad_and_melody_output() { } h.engine.stop(); - h.engine.set_note_processing(settings(false, false)); + h.engine.set_mapping(melody_mapping()); h.engine.set_track_muted(2, false); h.engine.set_track_volume(2, 1.0); h.engine.flush().unwrap(); @@ -257,10 +279,10 @@ fn mid_chord_processing_and_track_changes_do_not_mix_pad_and_melody_output() { } #[test] -fn auto_chord_preserves_raw_and_adapted_listen_note_glow_without_keyboard_output() { +fn chord_pads_preserve_raw_and_adapted_listen_note_glow_without_keyboard_output() { for mode in [SynthMode::Raw, SynthMode::Adapted] { let h = Harness::new(triad(67, 0, 120_000)); - h.engine.set_note_processing(settings(false, true)); + h.engine.set_note_processing(settings(false)); h.engine.set_listen_mode(true); h.engine.set_synth_mode(mode); h.engine.play(); @@ -270,24 +292,24 @@ fn auto_chord_preserves_raw_and_adapted_listen_note_glow_without_keyboard_output let mut hits = h.hits.lock().unwrap().clone(); hits.sort_unstable(); assert_eq!(hits, vec![(60, false), (60, true), (64, false), (64, true), (67, false), (67, true)], - "Auto Chord must preserve every source note's existing listen/glow lifecycle"); + "Chord detection must preserve every source note's existing listen/glow lifecycle"); } } #[test] -fn a_chord_heard_in_listen_mode_does_not_freeze_later_game_notes_after_disabling_auto_chord() { +fn a_chord_heard_in_listen_mode_does_not_freeze_later_game_notes_after_switching_to_melody_mapping() { let h = Harness::new(vec![ event(0, 0, 60, true), event(60_000, 1, 64, true), event(120_000, 2, 67, true), event(180_000, 0, 60, false), event(180_000, 1, 64, false), event(180_000, 2, 67, false), ]); h.engine.set_note_processing(NoteProcessingSettings { - chord_detection_milliseconds: 150, ..settings(false, true) + chord_detection_milliseconds: 150, ..settings(false) }); h.engine.set_listen_mode(true); h.engine.play(); wait(|| h.engine.get_current_time_us() >= 30_000); assert!(h.output.lock().unwrap().is_empty()); - h.engine.set_note_processing(settings(false, false)); + h.engine.set_mapping(melody_mapping()); h.engine.set_listen_mode(false); h.engine.flush().unwrap(); wait(|| h.engine.get_status() == PlaybackStatus::Stopped); @@ -301,7 +323,7 @@ fn pad_cleanup_on_pause_stop_and_seek_does_not_restore_historical_taps() { for action in ["pause", "stop", "seek"] { let h = Harness::new(triad(67, 0, 1_000_000)); h.engine.set_hold_delay_ms(500); - h.engine.set_note_processing(settings(false, true)); + h.engine.set_note_processing(settings(false)); h.engine.play(); wait(|| h.count("q", false) == 1); match action { @@ -322,7 +344,7 @@ fn pad_cleanup_on_pause_stop_and_seek_does_not_restore_historical_taps() { #[test] fn seeking_to_the_exact_chord_onset_still_dispatches_the_pad() { let h = Harness::new(triad(67, 100_000, 350_000)); - h.engine.set_note_processing(settings(false, true)); + h.engine.set_note_processing(settings(false)); h.engine.seek(100_000, 1); h.engine.flush().unwrap(); assert!(h.output.lock().unwrap().is_empty(), "stopped seeks must remain silent"); @@ -338,7 +360,7 @@ fn processing_setting_changes_leave_live_midi_notes_and_their_ownership_intact() h.engine.midi_gate(true); h.engine.midi_message(3, MidiMessage::On { channel: 0, pitch: 60, velocity: 100 }); wait(|| h.engine.midi_snapshot().pitches == [60]); - for processing in [settings(true, false), settings(true, true), settings(false, false)] { + for processing in [settings(true), settings(false)] { h.engine.set_note_processing(processing); h.engine.flush().unwrap(); } @@ -351,9 +373,9 @@ fn processing_setting_changes_leave_live_midi_notes_and_their_ownership_intact() } #[test] -fn auto_chord_does_not_replace_live_midi_input_with_song_chord_pads() { +fn chord_pads_do_not_replace_live_midi_input_with_song_chord_pads() { let h = Harness::new(vec![]); - h.engine.set_note_processing(settings(true, true)); + h.engine.set_note_processing(settings(true)); h.engine.midi_start(4); h.engine.midi_gate(true); for pitch in [60, 64, 67] { diff --git a/crates/amp-core/tests/song_settings_tests.rs b/crates/amp-core/tests/song_settings_tests.rs index 54832160..ffad7439 100644 --- a/crates/amp-core/tests/song_settings_tests.rs +++ b/crates/amp-core/tests/song_settings_tests.rs @@ -37,7 +37,7 @@ fn settings(key: i32) -> SongSettingsUpdate { SongSettingsUpdate { key, base_key: Some(2), transpose: 1, disabled_tracks: Some("0,2".into()), key_changes: Some("[]".into()), speed: Some(1.5), hold_notes: Some(true), tap_threshold_ms: Some(100), - auto_chord: Some(true), chord_detection_milliseconds: Some(45), enable_key_change_markers: Some(false), + chord_detection_milliseconds: Some(45), enable_key_change_markers: Some(false), } } @@ -46,7 +46,7 @@ fn details(key: i32) -> SongDetailsUpdate { title: "Edited".into(), artist: "Artist".into(), album: "".into(), base_key: None, key, transpose: 3, bpm: None, speed: 0.75, merge_notes: true, merge_milliseconds: 50, hold_notes: false, tap_threshold_ms: 0, - auto_chord: true, enable_key_change_markers: true, + enable_key_change_markers: true, date_added: "2026-10-23T00:00:00Z".into(), } } @@ -59,7 +59,6 @@ fn instrument_settings_are_isolated_by_both_game_and_instrument() { assert_eq!(saved.key, 5); assert_eq!(saved.speed, Some(1.5)); assert_eq!(saved.disabled_tracks.as_deref(), Some("0,2")); - assert_eq!(saved.auto_chord, Some(true)); assert_eq!(saved.chord_detection_milliseconds, Some(45)); assert_eq!(saved.enable_key_change_markers, Some(false)); assert_eq!(f.resolved("game-a", "piano").key, 1); @@ -86,7 +85,6 @@ fn game_save_applies_to_its_instruments_and_preserves_studio_only_fields() { let lyre = f.resolved("a", "lyre"); assert_eq!(lyre.disabled_tracks.as_deref(), Some("0,2")); assert_eq!(lyre.key_changes.as_deref(), Some("[]")); - assert_eq!(lyre.auto_chord, Some(true)); assert_eq!(f.resolved("b", "lyre").key, 5); let global = f.db.get_song_by_id("song").unwrap().unwrap(); assert_eq!(global.key, 1); diff --git a/crates/amp-core/tests/soundfont_sync_tests.rs b/crates/amp-core/tests/soundfont_sync_tests.rs index 9db5d66f..229ae1f7 100644 --- a/crates/amp-core/tests/soundfont_sync_tests.rs +++ b/crates/amp-core/tests/soundfont_sync_tests.rs @@ -19,7 +19,7 @@ impl Drop for TestDirectory { #[test] fn soundfont_watcher_detects_deletions_renames_and_directory_recreation() { let temp = TestDirectory::new(); - let root = temp.0.canonicalize().unwrap().join("SoundFonts"); + let root = temp.0.join("SoundFonts"); fs::create_dir(&root).unwrap(); let font = root.join("Stock.sf2"); fs::write(&font, b"test font").unwrap(); @@ -57,7 +57,7 @@ fn soundfont_watcher_can_start_with_a_missing_directory() { #[test] fn source_file_watcher_ignores_other_fonts_and_detects_removal_and_restoration() { let temp = TestDirectory::new(); - let root = temp.0.canonicalize().unwrap(); + let root = &temp.0; let font = root.join("Source.sf2"); fs::write(&font, b"source").unwrap(); let (tx, rx) = mpsc::channel(); diff --git a/docs/instrument-configuration.md b/docs/instrument-configuration.md new file mode 100644 index 00000000..22f4976b --- /dev/null +++ b/docs/instrument-configuration.md @@ -0,0 +1,78 @@ +# Instrument and input layouts + +Game definitions own process/window names and default selections. Instrument definitions own pitches, chords, guitar tuning, supported input groups, and their visual style. Layout definitions own keyboard/mouse bindings and calibration. + +## Layout groups + +An instrument declares three separate lists: + +```json +{ + "keyboardLayouts": ["NTE_QWERTY_Guitar"], + "chordLayouts": ["NTE_Chord_Wheel"], + "fretLayouts": ["NTE_Fret_Wheel"] +} +``` + +| Field | Purpose | +| --- | --- | +| `keyboardLayouts` | Chromatic/diatonic note keys, including the existing NTE piano-style guitar controls | +| `chordLayouts` | Chord pad keys or a calibrated chord wheel, selected by the instrument's `chordMode` | +| `fretLayouts` | Guitar string bindings and a fret selector | + +An empty list means that input group is unavailable. A layout may appear in more than one list: Genshin's melody layout provides both individual note keys and chord pad keys. Instrument view retains a layout choice for each available input group. + +## Chords + +Use `chords` for the instrument's musical definitions: + +```json +{ + "chordMode": "wheel", + "chords": [ + { "name": "G", "pitchClasses": [2, 7, 11] }, + { "name": "G/B", "pitchClasses": [2, 7, 11], "bassPitchClass": 11 } + ] +} +``` + +Pitch classes use C = 0 through B = 11. `bassPitchClass` distinguishes slash-chord inversions. The existing Auto Chord detector is shared by `"pads"` (the default) and `"wheel"` modes. Pad layouts supply `chordKeys`; wheel layouts supply `chordWheel`. The musical definitions are independent of those physical controls. + +## Guitar geometry and display + +```json +{ + "layoutStyle": "guitar", + "guitar": { + "tuning": [64, 59, 55, 50, 45, 40], + "fretCount": 24 + } +} +``` + +Tuning is ordered from string 1 (high E) to string 6 (low E), using MIDI pitches for the open strings. A fretted pitch is its open-string pitch plus the fret number. The guitar style presents chord and string/fret information without treating the guitar controls as a piano grid. A string/fret display is a visualization of current notes; it does not add TAB or Guitar Pro file import. + +The instrument's existing `keys` matrix remains the pitch set for keyboard playback. Fret playback derives its playable range from `guitar.tuning` and `guitar.fretCount`. + +## Fret bindings + +```json +{ + "id": "NTE_Fret_Wheel", + "name": "Fret Wheel", + "keys": [], + "fretboard": { + "stringKeys": ["6", "5", "4", "3", "2", "1"], + "wheelLayout": "NTE_Chord_Wheel", + "modeKey": "z" + } +} +``` + +`stringKeys` follows the same high-to-low string order as tuning. `wheelLayout` references the existing calibrated selector positions, page keys, and timing instead of copying them. `modeKey` switches the game's chord/fret sub-mode. NTE's frets 1–24 occupy four six-slot pages; open strings use the fifth page's Zero selector. + +## Existing configurations + +Bundled instruments use the new names. Older `supportedLayouts` and `chordPads` fields can still be read for existing user configurations; native serialization emits the canonical layout groups and `chords`. Existing app-data JSON is preserved during app updates. Restore bundled defaults or edit your current definitions to adopt newly added bindings. + +See [NTE guitar setup](nte-guitar.md) for playback controls, mode/page synchronization, calibration, and limitations. diff --git a/docs/nte-guitar.md b/docs/nte-guitar.md new file mode 100644 index 00000000..008e3ad4 --- /dev/null +++ b/docs/nte-guitar.md @@ -0,0 +1,46 @@ +# NTE guitar keyboard, chord, and fret playback + +On Windows, select **Neverness to Everness → Guitar**, then choose **Keyboard**, **Chords**, or **Frets** in Instrument view. Each input group has its own layout selection. Chords uses **Chord Wheel** with **Auto Chord** enabled; Frets uses **Fret Wheel** and does not require Auto Chord. The lower **Frets** toggle switches between chord and fret controls. + +Open the matching guitar controls in NTE before playback. Selecting Keyboard uses the game's chromatic piano mode; entering or leaving that mode still requires the game's mode button. Switching directly between Chords and Frets while NTE is running focuses the game and sends its configured `Z` binding. Selecting a mode while the game is closed changes AMP's configuration without sending input. Pause playback before switching modes. + +The existing Auto Chord detector handles both chord output types. The instrument JSON selects `chordMode`: `"pads"` uses the selected layout's `chordKeys` (the default for Genshin's Ukulele), while `"wheel"` uses its `chordWheel` selector/page/strum bindings. Musical definitions are stored in `chords`. The separate `keyboardLayouts`, `chordLayouts`, and `fretLayouts` lists declare the input groups available for the instrument. See the [instrument configuration guide](instrument-configuration.md) for the schema and examples. + +Existing app-data JSON files are preserved when updating the app. To use the new bundled Guitar definition with an older configuration, restore the bundled game/layout defaults or add its chord settings to your existing JSON. + +Use **Sync game page** to declare the page currently visible in NTE. It changes AMP's page tracking without sending input. AMP initially assumes page 1. Synchronize again after changing pages directly in the game, reopening its instrument, or an interrupted page change. + +Chord and fret pages are tracked separately. On first entering an unfamiliar layout, set its page before playing. Returning to a previously synchronized layout restores its tracked page; AMP cannot detect changes made directly in the game. + +**Previous** and **Next** focus the selected game and send its configured `R` / `T` bindings, wrapping at the first/last page. Pause playback before using these buttons. During MIDI playback, AMP takes the shorter wrapped route to the required page and reuses the selected chord for repeated strums, following the reference player's interaction. + +| Page | Clockwise from the top | +| --- | --- | +| 1 | G, Am, Bm, C, D, Em | +| 2 | Cmaj7, C7, Cm7, G7, C9, Cm9 | +| 3 | C5, D5, G5, A5, Cmaj9, Cadd9 | +| 4 | G/B, Am7/G, D/F#, F/A, A, Dm | + +The detector matches the pitch classes of note starts inside the Auto Chord tolerance. Power chords can match two distinct pitches. Slash chords also require the indicated lowest pitch class. Unsupported groups and individual melody notes are silent with the wheel layout; choose Guitar's keyboard layout to play chromatic melodies. Listen Mode still previews MIDI notes through the synthesizer. + +## Fret playback and guitar view + +Fret mode selects one fret shared by all six strings, then plucks the configured string keys. It supports frets 1–24 across four pages and open strings on the fifth page. String 1 is high E, bound to key `6`; string 6 is low E, bound to key `1`. The playable fret range comes from the instrument's tuning and fret count (E2–E6 for the bundled NTE guitar), independently of its piano-mode keyboard range. + +Notes at the same MIDI onset must have an exact voicing using distinct strings at one common fret. Unsupported groups stay silent; the player does not approximate their pitches or spread them into an arpeggio. Separate onsets retain their own timing. Selection/page preparation and held string-key cleanup use the same transport as wheel chords. + +`layoutStyle: "guitar"` adds a six-string fretboard, current chord names, and a string/fret readout. The board scrolls horizontally in a narrow window. This is a visualization of the current notes, not a TAB editor or imported score. An unsupported simultaneous fret group is indicated in the view. + +AMP prepares the page and selector click ahead of the musical onset, then sends a right-button down-strum at the note's scheduled time. The first attack, seeks, and resumes may need a brief preparation interval while the playhead remains stationary. Page changes must fit between attacks at the chosen playback speed. If preparation cannot finish in time, playback pauses with an error instead of delaying that chord. Reduce speed or adjust timing for dense passages. + +Pausing, stopping, switching instruments, disabling output, or losing focus cancels pending mouse actions and releases held inputs. A partially interrupted page key leaves the current page unknown; use Sync game page before resuming. There is no automatic visual recognition of the in-game mode or page. + +## Positions and timing + +The app-data layout file `KeyboardLayouts/NTE_Chord_Wheel.json` defines six selector positions, a separate strum position, page keys, and timing. `NTE_Fret_Wheel.json` references those controls through `fretboard.wheelLayout` and adds its string/mode bindings. Coordinates are thousandths of the foreground game's client width and height, excluding window borders. Defaults follow the supplied 16:9 screenshot; adjust them for a different UI arrangement or aspect ratio. For example, `[693, 255]` means 69.3% across and 25.5% down the game area. Changes reload through the existing configuration watcher. + +The game process must match the selected game's `processNames` from `game.json` or its configured executable preference before any selector movement or mouse press. Layouts contain input controls only. Mouse output is currently Windows-only. Input holds and waits are configurable host timings; they are not measurements of NTE's response. + +The page order, fret/string controls, and click/strum interaction were checked against the [reference player's game profile](https://github.com/DIEtype/Guitarplayer-For-NTE/blob/aa0ce3d183ef0745e6960a7bdc031bc3e2bb52e3/guitar_player/game_profile.py). This implementation does not import that application's code. TAB/Guitar Pro import, timbre switching, and live MIDI chord/fret arrangement are outside this change. + +Mock backend tests cover page keys, selection, strums, scheduling, cancellation, focus loss, and cleanup failures. Actual NTE input acceptance, chord voicings, cursor calibration, and timing still require in-game testing. diff --git a/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano61Key.json b/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano61Key.json index 94bb6c49..61dccc7f 100644 --- a/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano61Key.json +++ b/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano61Key.json @@ -7,6 +7,8 @@ "keys": [ [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96] ], - "supportedLayouts": ["QWERTY_61Keys"], + "keyboardLayouts": ["QWERTY_61Keys"], + "chordLayouts": [], + "fretLayouts": [], "supportsPedals": true } diff --git a/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano88Key.json b/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano88Key.json index 3475e3ab..aa78e22c 100644 --- a/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano88Key.json +++ b/src-tauri/resources/defaults/Games/Blue Protocol Star Resonance/Instruments/Pianos/Piano88Key.json @@ -7,6 +7,8 @@ "keys": [ [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108] ], - "supportedLayouts": ["QWERTY_88Keys"], + "keyboardLayouts": ["QWERTY_88Keys"], + "chordLayouts": [], + "fretLayouts": [], "supportsPedals": true } diff --git a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Keyboard/PocketPiano.json b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Keyboard/PocketPiano.json index 69dfceb4..3b766711 100644 --- a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Keyboard/PocketPiano.json +++ b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Keyboard/PocketPiano.json @@ -8,5 +8,7 @@ [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] ], - "supportedLayouts": ["CoreKeeper_QWERTY"] + "keyboardLayouts": ["CoreKeeper_QWERTY"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Percussion/Drumkit.json b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Percussion/Drumkit.json index 4ee83d0f..aed7b3af 100644 --- a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Percussion/Drumkit.json +++ b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Percussion/Drumkit.json @@ -12,5 +12,7 @@ [40, 41, 42, 43], [44, 45, 46, 47] ], - "supportedLayouts": ["CoreKeeper_QWERTY"] + "keyboardLayouts": ["CoreKeeper_QWERTY"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Cello.json b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Cello.json index f673216e..c97084ca 100644 --- a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Cello.json +++ b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Cello.json @@ -8,5 +8,7 @@ [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47] ], - "supportedLayouts": ["CoreKeeper_QWERTY"] + "keyboardLayouts": ["CoreKeeper_QWERTY"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Harp.json b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Harp.json index 27a89740..2f7cec35 100644 --- a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Harp.json +++ b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Strings/Harp.json @@ -8,5 +8,7 @@ [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] ], - "supportedLayouts": ["CoreKeeper_QWERTY"] + "keyboardLayouts": ["CoreKeeper_QWERTY"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Flute.json b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Flute.json index 81cb3ec2..73780373 100644 --- a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Flute.json +++ b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Flute.json @@ -8,5 +8,7 @@ [72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71] ], - "supportedLayouts": ["CoreKeeper_QWERTY"] + "keyboardLayouts": ["CoreKeeper_QWERTY"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Ocarina.json b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Ocarina.json index 74c37c61..b4940308 100644 --- a/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Ocarina.json +++ b/src-tauri/resources/defaults/Games/Core Keeper/Instruments/Winds/Ocarina.json @@ -8,5 +8,7 @@ [84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95], [72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83] ], - "supportedLayouts": ["CoreKeeper_QWERTY"] + "keyboardLayouts": ["CoreKeeper_QWERTY"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Horns/NightwindHorn.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Horns/NightwindHorn.json index 575d4081..74010713 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Horns/NightwindHorn.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Horns/NightwindHorn.json @@ -8,5 +8,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["Genshin_QWERTY_Two_Octaves"] + "keyboardLayouts": ["Genshin_QWERTY_Two_Octaves"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/VintageLyre.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/VintageLyre.json index 49917634..08ffd503 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/VintageLyre.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/VintageLyre.json @@ -9,5 +9,7 @@ [60, 62, 63, 65, 67, 69, 70], [48, 50, 51, 53, 55, 57, 58] ], - "supportedLayouts": ["QWERTY_21Keys", "Genshin_QWERTZ", "Genshin_AZERTY", "Genshin_DVORAK", "Genshin_DVORAKLeft", "Genshin_DVORAKRight", "Genshin_Colemak"] + "keyboardLayouts": ["QWERTY_21Keys","Genshin_QWERTZ","Genshin_AZERTY","Genshin_DVORAK","Genshin_DVORAKLeft","Genshin_DVORAKRight","Genshin_Colemak"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/WindsongLyre.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/WindsongLyre.json index ae42af67..23eeea6d 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/WindsongLyre.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Lyres/WindsongLyre.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["QWERTY_21Keys", "Genshin_QWERTZ", "Genshin_AZERTY", "Genshin_DVORAK", "Genshin_DVORAKLeft", "Genshin_DVORAKRight", "Genshin_Colemak"] + "keyboardLayouts": ["QWERTY_21Keys","Genshin_QWERTZ","Genshin_AZERTY","Genshin_DVORAK","Genshin_DVORAKLeft","Genshin_DVORAKRight","Genshin_Colemak"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DjemDjemDrum.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DjemDjemDrum.json index 5490fe3f..56e08959 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DjemDjemDrum.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DjemDjemDrum.json @@ -8,5 +8,7 @@ [60, 62, 64, 65], [67, 69, 71, 72] ], - "supportedLayouts": ["Genshin_QWERTY_Drums"] + "keyboardLayouts": ["Genshin_QWERTY_Drums"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DunDun.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DunDun.json index 61295003..029496ea 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DunDun.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Percussion/DunDun.json @@ -8,5 +8,7 @@ [60, 62, 64, 65], [67, 69, 71, 72] ], - "supportedLayouts": ["Genshin_QWERTY_Drums"] + "keyboardLayouts": ["Genshin_QWERTY_Drums"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/HarmonicKey.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/HarmonicKey.json index 597025bf..873b2eb9 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/HarmonicKey.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/HarmonicKey.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["QWERTY_21Keys", "Genshin_QWERTZ", "Genshin_AZERTY", "Genshin_DVORAK", "Genshin_DVORAKLeft", "Genshin_DVORAKRight", "Genshin_Colemak"] + "keyboardLayouts": ["QWERTY_21Keys","Genshin_QWERTZ","Genshin_AZERTY","Genshin_DVORAK","Genshin_DVORAKLeft","Genshin_DVORAKRight","Genshin_Colemak"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/LeapingSpiritPiano.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/LeapingSpiritPiano.json index 419b67ec..65987f90 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/LeapingSpiritPiano.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Pianos/LeapingSpiritPiano.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["QWERTY_21Keys", "Genshin_QWERTZ", "Genshin_AZERTY", "Genshin_DVORAK", "Genshin_DVORAKLeft", "Genshin_DVORAKRight", "Genshin_Colemak"] + "keyboardLayouts": ["QWERTY_21Keys","Genshin_QWERTZ","Genshin_AZERTY","Genshin_DVORAK","Genshin_DVORAKLeft","Genshin_DVORAKRight","Genshin_Colemak"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/LingeringEuphonia.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/LingeringEuphonia.json index e520c80f..cc5f33cc 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/LingeringEuphonia.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/LingeringEuphonia.json @@ -8,8 +8,11 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["Genshin_QWERTY_Melody"], - "chordPads": [ + "keyboardLayouts": ["Genshin_QWERTY_Melody"], + "chordLayouts": ["Genshin_QWERTY_Chords"], + "fretLayouts": [], + "chordMode": "pads", + "chords": [ { "name": "C", "pitchClasses": [0, 4, 7] }, { "name": "Dm", "pitchClasses": [2, 5, 9] }, { "name": "Em", "pitchClasses": [4, 7, 11] }, diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json index f40aeb86..1b396c7d 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Strings/Ukulele.json @@ -8,8 +8,11 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["Genshin_QWERTY_Melody"], - "chordPads": [ + "keyboardLayouts": ["Genshin_QWERTY_Melody"], + "chordLayouts": ["Genshin_QWERTY_Chords"], + "fretLayouts": [], + "chordMode": "pads", + "chords": [ { "name": "C", "pitchClasses": [0, 4, 7] }, { "name": "Dm", "pitchClasses": [2, 5, 9] }, { "name": "Em", "pitchClasses": [4, 7, 11] }, diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/FloralZither.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/FloralZither.json index ec28fac1..f932202a 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/FloralZither.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/FloralZither.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["QWERTY_21Keys", "Genshin_QWERTZ", "Genshin_AZERTY", "Genshin_DVORAK", "Genshin_DVORAKLeft", "Genshin_DVORAKRight", "Genshin_Colemak"] + "keyboardLayouts": ["QWERTY_21Keys","Genshin_QWERTZ","Genshin_AZERTY","Genshin_DVORAK","Genshin_DVORAKLeft","Genshin_DVORAKRight","Genshin_Colemak"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/OldZither.json b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/OldZither.json index d925e9df..6d5f36f1 100644 --- a/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/OldZither.json +++ b/src-tauri/resources/defaults/Games/Genshin Impact/Instruments/Zithers/OldZither.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["QWERTY_21Keys", "Genshin_QWERTZ", "Genshin_AZERTY", "Genshin_DVORAK", "Genshin_DVORAKLeft", "Genshin_DVORAKRight", "Genshin_Colemak"] + "keyboardLayouts": ["QWERTY_21Keys","Genshin_QWERTZ","Genshin_AZERTY","Genshin_DVORAK","Genshin_DVORAKLeft","Genshin_DVORAKRight","Genshin_Colemak"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano14Key.json b/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano14Key.json index 3299b315..51e47bee 100644 --- a/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano14Key.json +++ b/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano14Key.json @@ -8,5 +8,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["HPMA_QWERTY_14Key"] + "keyboardLayouts": ["HPMA_QWERTY_14Key"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano36Key.json b/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano36Key.json index 7d099cea..9355dc07 100644 --- a/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano36Key.json +++ b/src-tauri/resources/defaults/Games/Harry Potter Magic Awakened/Instruments/Pianos/Piano36Key.json @@ -9,5 +9,7 @@ [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] ], - "supportedLayouts": ["HPMA_QWERTY_36Key"] + "keyboardLayouts": ["HPMA_QWERTY_36Key"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon2Row.json index 98039eb2..5066d633 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon3Row.json index d3b24fae..c4726242 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Cajon3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga2Row.json index f6a109f6..bcc08ff2 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga3Row.json index d7de2839..1b17f645 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Conga3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira2Row.json index 8144468f..ce94328f 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira3Row.json index 18e526e5..b6cbe9ad 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Percussion/Mbira3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano22Key.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano22Key.json index c6fd8524..9fbffd84 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano22Key.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano22Key.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["Heartopia_QWERTY_22Key"] + "keyboardLayouts": ["Heartopia_QWERTY_22Key"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano2Row.json index 2cba4476..9578d11e 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano37Key.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano37Key.json index 2088a8e2..996df804 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano37Key.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano37Key.json @@ -9,5 +9,7 @@ [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] ], - "supportedLayouts": ["Heartopia_QWERTY_37Key"] + "keyboardLayouts": ["Heartopia_QWERTY_37Key"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano3Row.json index 230f737c..69887128 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Pianos/Piano3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello2Row.json index eab91b03..deeb19d7 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello3Row.json index 373eea46..1241e88f 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Cello3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute2Row.json index b1dadbf6..4a950397 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute3Row.json index 1a67c498..58647b43 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lute3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre2Row.json index 9dcf04b1..94919d16 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre3Row.json index 08c763e5..d38b198e 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Lyre3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin2Row.json index 8c7eb281..5df7b524 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin3Row.json index 7e09b7a2..e7708476 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/Violin3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass2Row.json index e3776441..dadc9616 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass3Row.json index 696db31c..dd357324 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Strings/WoodenBass3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe2Row.json index 6e5d0933..84bacbf0 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe3Row.json index cce9e9f7..df5f5443 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Bagpipe3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao2Row.json index e7c51a06..c8aef8bd 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao3Row.json index 91d7b9fb..afd5fa12 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/BambooXiao3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina2Row.json index 5d2a1ff2..9f02b930 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina3Row.json index cbf5d853..cb7287bf 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Concertina3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder2Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder2Row.json index 7ef734fc..d718f14d 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder2Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder2Row.json @@ -8,5 +8,7 @@ [72, 74, 76, 77, 79, 81, 83, 84], [60, 62, 64, 65, 67, 69, 71] ], - "supportedLayouts": ["Heartopia_QWERTY_2Row"] + "keyboardLayouts": ["Heartopia_QWERTY_2Row"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder3Row.json b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder3Row.json index ca0a6e69..dacffc0e 100644 --- a/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder3Row.json +++ b/src-tauri/resources/defaults/Games/Heartopia/Instruments/Winds/Recorder3Row.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano21Key.json b/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano21Key.json index d04332e2..1c7b72e7 100644 --- a/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano21Key.json +++ b/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano21Key.json @@ -9,5 +9,7 @@ [48, 50, 52, 53, 55, 57, 59], [36, 38, 40, 41, 43, 45, 47] ], - "supportedLayouts": ["QWERTY_21Keys"] + "keyboardLayouts": ["QWERTY_21Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano36Key.json b/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano36Key.json index e0a8bb18..8eab30ae 100644 --- a/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano36Key.json +++ b/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Pianos/Piano36Key.json @@ -9,5 +9,7 @@ [72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71] ], - "supportedLayouts": ["QWERTY_36Keys"] + "keyboardLayouts": ["QWERTY_36Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Strings/Guitar.json b/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Strings/Guitar.json index 26b1f733..340ef8b3 100644 --- a/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Strings/Guitar.json +++ b/src-tauri/resources/defaults/Games/Neverness to Everness/Instruments/Strings/Guitar.json @@ -3,11 +3,41 @@ "name": "Guitar", "category": "Strings", "type": "chromatic36", - "layoutStyle": "genshin", + "layoutStyle": "guitar", + "guitar": { "tuning": [64, 59, 55, 50, 45, 40], "fretCount": 24 }, "keys": [ [76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87], [64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75], [52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] ], - "supportedLayouts": ["NTE_QWERTY_Guitar"] + "keyboardLayouts": ["NTE_QWERTY_Guitar"], + "chordLayouts": ["NTE_Chord_Wheel"], + "fretLayouts": ["NTE_Fret_Wheel"], + "chordMode": "wheel", + "chords": [ + {"name":"G","pitchClasses":[2,7,11]}, + {"name":"Am","pitchClasses":[0,4,9]}, + {"name":"Bm","pitchClasses":[2,6,11]}, + {"name":"C","pitchClasses":[0,4,7]}, + {"name":"D","pitchClasses":[2,6,9]}, + {"name":"Em","pitchClasses":[4,7,11]}, + {"name":"Cmaj7","pitchClasses":[0,4,7,11]}, + {"name":"C7","pitchClasses":[0,4,7,10]}, + {"name":"Cm7","pitchClasses":[0,3,7,10]}, + {"name":"G7","pitchClasses":[2,5,7,11]}, + {"name":"C9","pitchClasses":[0,2,4,7,10]}, + {"name":"Cm9","pitchClasses":[0,2,3,7,10]}, + {"name":"C5","pitchClasses":[0,7]}, + {"name":"D5","pitchClasses":[2,9]}, + {"name":"G5","pitchClasses":[2,7]}, + {"name":"A5","pitchClasses":[4,9]}, + {"name":"Cmaj9","pitchClasses":[0,2,4,7,11]}, + {"name":"Cadd9","pitchClasses":[0,2,4,7]}, + {"name":"G/B","pitchClasses":[2,7,11],"bassPitchClass":11}, + {"name":"Am7/G","pitchClasses":[0,4,7,9],"bassPitchClass":7}, + {"name":"D/F#","pitchClasses":[2,6,9],"bassPitchClass":6}, + {"name":"F/A","pitchClasses":[0,5,9],"bassPitchClass":9}, + {"name":"A","pitchClasses":[1,4,9]}, + {"name":"Dm","pitchClasses":[2,5,9]} + ] } diff --git a/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano61Key.json b/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano61Key.json index 5d183b4a..c8977d83 100644 --- a/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano61Key.json +++ b/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano61Key.json @@ -7,6 +7,8 @@ "keys": [ [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96] ], - "supportedLayouts": ["QWERTY_61Keys"], + "keyboardLayouts": ["QWERTY_61Keys"], + "chordLayouts": [], + "fretLayouts": [], "supportsPedals": true } diff --git a/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano88Key.json b/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano88Key.json index 86f55ea3..2f193ce8 100644 --- a/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano88Key.json +++ b/src-tauri/resources/defaults/Games/Roblox/Instruments/Pianos/Piano88Key.json @@ -7,6 +7,8 @@ "keys": [ [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108] ], - "supportedLayouts": ["QWERTY_88Keys"], + "keyboardLayouts": ["QWERTY_88Keys"], + "chordLayouts": [], + "fretLayouts": [], "supportsPedals": true } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Cello.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Cello.json index fcab414f..e06862c7 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Cello.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Cello.json @@ -9,5 +9,7 @@ [45, 47, 48, 50, 52], [53, 55, 57, 59, 60] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Contrabass.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Contrabass.json index f72461c4..45912cdc 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Contrabass.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/Contrabass.json @@ -9,5 +9,7 @@ [33, 35, 36, 38, 40], [41, 43, 45, 47, 48] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/DuetsCello.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/DuetsCello.json index 4b669da3..8969ceab 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/DuetsCello.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Bass/DuetsCello.json @@ -9,5 +9,7 @@ [45, 47, 48, 50, 52], [53, 55, 57, 59, 60] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/BlueElectricGuitar.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/BlueElectricGuitar.json index cfb2dea7..1ca9bc45 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/BlueElectricGuitar.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/BlueElectricGuitar.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/DuetsGrandPiano.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/DuetsGrandPiano.json index 523f953d..5597de35 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/DuetsGrandPiano.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/DuetsGrandPiano.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/ElectricGuitar.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/ElectricGuitar.json index dec17363..d7a343bd 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/ElectricGuitar.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/ElectricGuitar.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingHarp.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingHarp.json index 75300a8d..cef75e44 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingHarp.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingHarp.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingUprightPiano.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingUprightPiano.json index e09d2df4..f8ea5bc9 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingUprightPiano.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/FledglingUprightPiano.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/GrandPiano.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/GrandPiano.json index 63f4fbd0..7a74a7d2 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/GrandPiano.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/GrandPiano.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Guitar.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Guitar.json index 1c032977..d479eecf 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Guitar.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Guitar.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Harp.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Harp.json index 8e9e2a0d..a7c76a95 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Harp.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Harp.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Kalimba.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Kalimba.json index 32379f64..d5a69694 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Kalimba.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Kalimba.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Lute.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Lute.json index ab546b2d..e6fd28a4 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Lute.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Lute.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Piano.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Piano.json index 3044e561..08cb454b 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Piano.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Piano.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/RhythmGuitar.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/RhythmGuitar.json index 1d056dd5..0519ea38 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/RhythmGuitar.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/RhythmGuitar.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/TriumphViolin.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/TriumphViolin.json index 5cdffba2..7d13a963 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/TriumphViolin.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/TriumphViolin.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Ukulele.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Ukulele.json index b79c0da9..1275d137 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Ukulele.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Ukulele.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/VoiceOfAURORA.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/VoiceOfAURORA.json index f3fcd13e..6ab61f30 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/VoiceOfAURORA.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/VoiceOfAURORA.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/WinterPiano.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/WinterPiano.json index bddf7d50..0fbc3395 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/WinterPiano.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/WinterPiano.json @@ -9,5 +9,7 @@ [81, 83, 84, 86, 88], [89, 91, 93, 95, 96] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Xylophone.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Xylophone.json index 2af99543..94bf2aee 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Xylophone.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Melody/Xylophone.json @@ -9,5 +9,7 @@ [81, 83, 84, 86, 88], [89, 91, 93, 95, 96] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Cymbals.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Cymbals.json index 376bd326..f2508ee6 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Cymbals.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Cymbals.json @@ -8,5 +8,7 @@ [60, 62, 64, 65], [67, 69, 71, 72] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Drum.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Drum.json index f808c6f2..1c1ca848 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Drum.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/Drum.json @@ -8,5 +8,7 @@ [60, 62, 64, 65], [67, 69, 71, 72] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/FortuneDrum.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/FortuneDrum.json index 21d5a3aa..cb67e59a 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/FortuneDrum.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/FortuneDrum.json @@ -8,5 +8,7 @@ [60, 62, 64, 65], [67, 69, 71, 72] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/LargeBell.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/LargeBell.json index 7a285f4b..dfcedf4b 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/LargeBell.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/LargeBell.json @@ -8,5 +8,7 @@ [60, 62, 67, 69], [72, 74, 79, 81] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/ProphecyDrum.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/ProphecyDrum.json index 00dae33d..3002fe64 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/ProphecyDrum.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/ProphecyDrum.json @@ -8,5 +8,7 @@ [60, 62, 64, 65], [67, 69, 71, 72] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SanctuaryHandpan.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SanctuaryHandpan.json index f7d26c46..1cac8bb3 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SanctuaryHandpan.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SanctuaryHandpan.json @@ -8,5 +8,7 @@ [50, 57, 60, 62], [65, 67, 69, 72] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SmallBell.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SmallBell.json index 28f6b952..dc2b5ea2 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SmallBell.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/SmallBell.json @@ -8,5 +8,7 @@ [60, 62, 67, 69], [72, 74, 79, 81] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/TriumphHandpan.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/TriumphHandpan.json index 5f0df76a..ed09acc9 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/TriumphHandpan.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Percussion/TriumphHandpan.json @@ -8,5 +8,7 @@ [50, 57, 60, 62], [65, 67, 69, 72] ], - "supportedLayouts": ["Sky_QWERTY_8"] + "keyboardLayouts": ["Sky_QWERTY_8"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Bugle.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Bugle.json index 523a7cae..e33ab2ac 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Bugle.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Bugle.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Flute.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Flute.json index 221fce9f..64af3b7c 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Flute.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Flute.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Harmonica.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Harmonica.json index b2cd42de..9b7e0e4c 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Harmonica.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Harmonica.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Horn.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Horn.json index ee39cee8..8b968850 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Horn.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Horn.json @@ -9,5 +9,7 @@ [45, 47, 48, 50, 52], [53, 55, 57, 59, 60] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/MantaOcarina.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/MantaOcarina.json index 8f0f572e..b8def828 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/MantaOcarina.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/MantaOcarina.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Panflute.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Panflute.json index 6aa566d2..f9660098 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Panflute.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/Panflute.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/TriumphSaxophone.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/TriumphSaxophone.json index 84d6e7b1..8a32c897 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/TriumphSaxophone.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/TriumphSaxophone.json @@ -9,5 +9,7 @@ [57, 59, 60, 62, 64], [65, 67, 69, 71, 72] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/VesselFlute.json b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/VesselFlute.json index 3d4ab8d6..5209cab6 100644 --- a/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/VesselFlute.json +++ b/src-tauri/resources/defaults/Games/Sky/Instruments/Winds/VesselFlute.json @@ -9,5 +9,7 @@ [69, 71, 72, 74, 76], [77, 79, 81, 83, 84] ], - "supportedLayouts": ["QWERTY_15Keys"] + "keyboardLayouts": ["QWERTY_15Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Where Winds Meet/Instruments/Zithers/Guqin.json b/src-tauri/resources/defaults/Games/Where Winds Meet/Instruments/Zithers/Guqin.json index 61424f23..f5700483 100644 --- a/src-tauri/resources/defaults/Games/Where Winds Meet/Instruments/Zithers/Guqin.json +++ b/src-tauri/resources/defaults/Games/Where Winds Meet/Instruments/Zithers/Guqin.json @@ -9,5 +9,7 @@ [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47] ], - "supportedLayouts": ["QWERTY_36Keys"] + "keyboardLayouts": ["QWERTY_36Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/Games/Wuthering Waves/Instruments/Instruments/Instrument21Key.json b/src-tauri/resources/defaults/Games/Wuthering Waves/Instruments/Instruments/Instrument21Key.json index 5d6ae649..366884a3 100644 --- a/src-tauri/resources/defaults/Games/Wuthering Waves/Instruments/Instruments/Instrument21Key.json +++ b/src-tauri/resources/defaults/Games/Wuthering Waves/Instruments/Instruments/Instrument21Key.json @@ -9,5 +9,7 @@ [60, 62, 64, 65, 67, 69, 71], [48, 50, 52, 53, 55, 57, 59] ], - "supportedLayouts": ["QWERTY_21Keys"] + "keyboardLayouts": ["QWERTY_21Keys"], + "chordLayouts": [], + "fretLayouts": [] } diff --git a/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Chords.json b/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Chords.json new file mode 100644 index 00000000..dac0f45d --- /dev/null +++ b/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Chords.json @@ -0,0 +1,6 @@ +{ + "id": "Genshin_QWERTY_Chords", + "name": "QWERTY (Chords)", + "keys": [], + "chordKeys": ["q", "w", "e", "r", "t", "y", "u"] +} diff --git a/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json b/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json index a6f8af59..cda77000 100644 --- a/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json +++ b/src-tauri/resources/defaults/KeyboardLayouts/Genshin_QWERTY_Melody.json @@ -4,8 +4,5 @@ "keys": [ ["a", "s", "d", "f", "g", "h", "j"], ["z", "x", "c", "v", "b", "n", "m"] - ], - "chordKeys": [ - "q", "w", "e", "r", "t", "y", "u" ] } diff --git a/src-tauri/resources/defaults/KeyboardLayouts/NTE_Chord_Wheel.json b/src-tauri/resources/defaults/KeyboardLayouts/NTE_Chord_Wheel.json new file mode 100644 index 00000000..500fe67a --- /dev/null +++ b/src-tauri/resources/defaults/KeyboardLayouts/NTE_Chord_Wheel.json @@ -0,0 +1,16 @@ +{ + "id": "NTE_Chord_Wheel", + "name": "Chord Wheel", + "keys": [], + "chordWheel": { + "positions": [[693, 255], [786, 352], [786, 532], [693, 631], [599, 532], [599, 352]], + "strumPosition": [910, 670], + "moveDelayMs": 30, + "selectHoldMs": 15, + "afterSelectMs": 15, + "pageCount": 4, + "pageKeys": ["r", "t"], + "pageHoldMs": 35, + "pageWaitMs": 145 + } +} diff --git a/src-tauri/resources/defaults/KeyboardLayouts/NTE_Fret_Wheel.json b/src-tauri/resources/defaults/KeyboardLayouts/NTE_Fret_Wheel.json new file mode 100644 index 00000000..2c757b25 --- /dev/null +++ b/src-tauri/resources/defaults/KeyboardLayouts/NTE_Fret_Wheel.json @@ -0,0 +1,17 @@ +{ + "id": "NTE_Fret_Wheel", + "name": "Fret Wheel", + "keys": [], + "fretboard": { + "stringKeys": [ + "6", + "5", + "4", + "3", + "2", + "1" + ], + "wheelLayout": "NTE_Chord_Wheel", + "modeKey": "z" + } +} diff --git a/src-tauri/src/config_manager.rs b/src-tauri/src/config_manager.rs index 07da4645..a7903d32 100644 --- a/src-tauri/src/config_manager.rs +++ b/src-tauri/src/config_manager.rs @@ -2,6 +2,7 @@ use amp_core::{ KeyboardLayoutJson, LoadedGameBundle, }; use amp_core::input::config_scan::{scan_games_checked, scan_layouts_checked, ConfigIssue}; +use amp_core::input::defaults_sync::{self, BundledDefault, DefaultConfigChoice, DefaultConfigUpdates}; use include_dir::{include_dir, Dir}; use log::{info, warn}; use std::collections::HashMap; @@ -10,6 +11,18 @@ use std::io::Write; use std::path::{Path, PathBuf}; static DEFAULTS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/resources/defaults"); +static DEFAULT_SYNC_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Available before AppState, audio, database, and playback initialization. +pub fn check_startup_defaults() -> Result { + let _guard = DEFAULT_SYNC_LOCK.lock().map_err(|e| e.to_string())?; + defaults_sync::sync_defaults(&get_appdata_dir(), &bundled_default_files(&DEFAULTS_DIR)) +} + +pub fn resolve_startup_defaults(choices: &[DefaultConfigChoice], duplicates: &[DefaultConfigChoice]) -> Result { + let _guard = DEFAULT_SYNC_LOCK.lock().map_err(|e| e.to_string())?; + defaults_sync::resolve_default_updates(&get_appdata_dir(), &bundled_default_files(&DEFAULTS_DIR), choices, duplicates) +} pub struct ConfigManager { base_dir: PathBuf, @@ -50,12 +63,22 @@ impl ConfigManager { mgr } - /// Extracts bundled defaults into %LocalAppData%\Jed556\AutoMIDIPlayer without overwriting existing files + /// Install missing defaults; existing JSON revisions remain pending until reviewed. pub fn extract_defaults_if_missing(&self) { - let _ = fs::create_dir_all(&self.games_dir); - let _ = fs::create_dir_all(&self.layouts_dir); + if let Err(error) = self.default_config_updates() { + warn!("[ConfigManager] Unable to synchronize bundled defaults: {error}"); + } + } + + pub fn default_config_updates(&self) -> Result { + let _guard = DEFAULT_SYNC_LOCK.lock().map_err(|e| e.to_string())?; + defaults_sync::sync_defaults(&self.base_dir, &bundled_default_files(&DEFAULTS_DIR)) + } - extract_dir_recursive(&DEFAULTS_DIR, &self.base_dir); + #[cfg(test)] + fn resolve_default_config_updates(&self, choices: &[DefaultConfigChoice], duplicates: &[DefaultConfigChoice]) -> Result { + let _guard = DEFAULT_SYNC_LOCK.lock().map_err(|e| e.to_string())?; + defaults_sync::resolve_default_updates(&self.base_dir, &bundled_default_files(&DEFAULTS_DIR), choices, duplicates) } /// Reloads all keyboard layouts and game definitions from disk @@ -106,6 +129,9 @@ impl ConfigManager { fs::rename(staging.join(name), self.base_dir.join(name)) .map_err(|e| format!("Unable to restore {name}: {e}"))?; } + // A deliberate reset accepts the currently bundled revisions. + defaults_sync::reset_default_history(&self.base_dir)?; + self.default_config_updates()?; self.loaded = false; self.reload(); Ok(()) @@ -164,7 +190,9 @@ impl ConfigManager { } } // Patch the latest file, preserving key matrices, custom metadata and other edits. - let mut document: serde_json::Value = serde_json::from_slice(&fs::read(&path).map_err(|e| e.to_string())?) + let _sync_guard = DEFAULT_SYNC_LOCK.lock().map_err(|e| e.to_string())?; + let before = fs::read(&path).map_err(|e| e.to_string())?; + let mut document: serde_json::Value = serde_json::from_slice(&before) .map_err(|e| format!("Cannot read keyboard layout: {e}"))?; let original: KeyboardLayoutJson = serde_json::from_value(document.clone()).map_err(|e| e.to_string())?; let registered = &self.layouts[&layout_id.to_lowercase()]; @@ -186,6 +214,14 @@ impl ConfigManager { })(); if result.is_err() { let _ = fs::remove_file(&temporary); } result?; + if let Some(file) = DEFAULTS_DIR.get_dir("KeyboardLayouts").into_iter().flat_map(|dir| dir.files()) + .find(|file| serde_json::from_slice::(file.contents()).ok() + .and_then(|doc| doc.get("id").and_then(|id| id.as_str()).map(|id| id.eq_ignore_ascii_case(&updated.id))).unwrap_or(false)) { + if let Err(error) = defaults_sync::record_reviewed_edit(&self.base_dir, file.path(), &before, + &serde_json::to_vec(&document).map_err(|e| e.to_string())?) { + warn!("[ConfigManager] Unable to record reviewed pedal edit: {error}"); + } + } // Keep ID and filename aliases current even if another config has an unrelated error. for layout in self.layouts.values_mut().filter(|layout| layout.id.eq_ignore_ascii_case(&updated.id)) { *layout = updated.clone(); @@ -235,24 +271,9 @@ fn extract_defaults_checked(dir: &Dir, root: &Path) -> Result<(), String> { Ok(()) } -fn extract_dir_recursive(embedded_dir: &Dir, target_root: &Path) { - for file in embedded_dir.files() { - let rel_path = file.path(); - let target_file_path = target_root.join(rel_path); - - if !target_file_path.exists() { - if let Some(parent) = target_file_path.parent() { - let _ = fs::create_dir_all(parent); - } - if let Err(e) = fs::write(&target_file_path, file.contents()) { - warn!("[ConfigManager] Failed to extract \"{}\": {}", target_file_path.display(), e); - } - } - } - - for dir in embedded_dir.dirs() { - extract_dir_recursive(dir, target_root); - } +fn bundled_default_files<'a>(dir: &'a Dir<'a>) -> Vec> { + dir.files().map(|file| BundledDefault { path: file.path(), contents: file.contents() }) + .chain(dir.dirs().flat_map(bundled_default_files)).collect() } fn open_folder_in_explorer(path: &Path) -> Result<(), String> { @@ -274,6 +295,69 @@ fn open_folder_in_explorer(path: &Path) -> Result<(), String> { mod tests { use super::*; + #[test] + fn explicit_pedal_edits_do_not_request_another_default_review() { + let mut manager = pedal_test_manager(); + manager.save_layout_pedals("QWERTY_61Keys", serde_json::json!({ "sustainKey": "Shift" }).as_object()).unwrap(); + assert!(manager.default_config_updates().unwrap().conflicts.is_empty()); + let path = manager.layouts_dir.join("QWERTY_61Keys.json"); + let mut external: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + external["custom"] = serde_json::json!(true); + fs::write(&path, serde_json::to_vec(&external).unwrap()).unwrap(); + manager.save_layout_pedals("QWERTY_61Keys", serde_json::json!({ "sustainKey": "Enter" }).as_object()).unwrap(); + assert_eq!(manager.default_config_updates().unwrap().conflicts.len(), 1); + fs::remove_dir_all(manager.base_dir).unwrap(); + } + + #[test] + fn embedded_default_updates_add_missing_files_and_review_existing_json() { + let mut manager = pedal_test_manager(); + let layout_path = manager.layouts_dir.join("QWERTY_61Keys.json"); + let mut local: serde_json::Value = serde_json::from_slice(&fs::read(&layout_path).unwrap()).unwrap(); + local["customMetadata"] = serde_json::json!({ "keep": true }); + let original = serde_json::to_vec_pretty(&local).unwrap(); + fs::write(&layout_path, &original).unwrap(); + fs::remove_file(manager.base_dir.join("configuration-state.json")).unwrap(); + fs::remove_file(manager.layouts_dir.join("Genshin_QWERTY_Chords.json")).unwrap(); + let report = manager.default_config_updates().unwrap(); + assert_eq!(report.added_files, ["KeyboardLayouts/Genshin_QWERTY_Chords.json"]); + assert_eq!(report.conflicts.len(), 1); + assert_eq!(fs::read(&layout_path).unwrap(), original); + let conflict = &report.conflicts[0]; + let result = manager.resolve_default_config_updates(&[DefaultConfigChoice { + id: conflict.id.clone(), token: conflict.token.clone(), + action: defaults_sync::DefaultConfigAction::Keep, + }], &[]).unwrap(); + assert!(result.conflicts.is_empty()); + manager.reload(); + assert!(manager.issues.is_empty(), "{:?}", manager.issues); + let genshin = manager.games.iter().find(|game| game.config.id == "Genshin Impact").unwrap(); + for id in ["ukulele", "lingering-euphonia"] { + let instrument = genshin.instruments.iter().find(|instrument| instrument.id == id).unwrap(); + assert!(instrument.supports_keyboard_layout("Genshin_QWERTY_Melody")); + assert!(instrument.supports_chord_layout("Genshin_QWERTY_Chords")); + assert!(!instrument.chords.is_empty()); + } + assert!(!genshin.instruments.iter().any(|instrument| instrument.id == "ukulele-chords" || instrument.id == "lingering-euphonia-chords")); + assert_eq!(fs::read(&layout_path).unwrap(), original); + let duplicate_path = manager.layouts_dir.join("newer-layout.json"); + fs::write(&duplicate_path, &original).unwrap(); + fs::File::options().write(true).open(&layout_path).unwrap().set_times(fs::FileTimes::new() + .set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000))).unwrap(); + let review = manager.default_config_updates().unwrap(); + assert_eq!(review.duplicates.len(), 1); + let duplicate = &review.duplicates[0]; + let updated = manager.resolve_default_config_updates(&[], &[DefaultConfigChoice { + id: duplicate.id.clone(), token: duplicate.token.clone(), action: defaults_sync::DefaultConfigAction::Replace, + }]).unwrap(); + assert!(updated.duplicates.is_empty()); + manager.reload(); + assert!(manager.issues.is_empty(), "{:?}", manager.issues); + assert!(!layout_path.exists()); + assert_eq!(fs::read(duplicate_path).unwrap(), original); + fs::remove_dir_all(manager.base_dir).unwrap(); + } + fn pedal_test_manager() -> ConfigManager { let root = std::env::temp_dir().join(format!("amp_pedal_edit_{}_{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 950ea42e..86604ced 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -21,6 +21,7 @@ mod log_privacy; pub mod logging; pub mod telemetry; use config_manager::{ConfigManager, ConfigSnapshot}; +use amp_core::input::defaults_sync::{DefaultConfigAction, DefaultConfigChoice, DefaultConfigUpdates}; use process_monitor::{ focus_window_by_pid, GameProcessTarget, GameStatusPayload, ProcessMonitor, @@ -510,11 +511,17 @@ fn read_midi_payload( Ok(payload) } +async fn start_engine_playback(engine: &PlaybackEngine) -> Result { + let result = engine.request_play(); + tauri::async_runtime::spawn_blocking(move || { + result.recv().map_err(|_| "The playback engine stopped.".to_string())?.map(|()| true) + }).await.map_err(|e| e.to_string())? +} + #[cfg(windows)] #[tauri::command] -fn play_song(state: State) -> Result { - state.engine.play(); - Ok(true) +async fn play_song(state: State<'_, AppState>) -> Result { + start_engine_playback(&state.engine).await } #[cfg(not(windows))] @@ -542,8 +549,7 @@ async fn play_song(state: State<'_, AppState>) -> Result { if epoch.load(Ordering::Acquire) != request { return Err("Playback request cancelled.".into()); } - state.engine.play(); - Ok(true) + start_engine_playback(&state.engine).await } fn cancel_pending_playback(state: &AppState) { @@ -624,7 +630,6 @@ fn set_note_timing(hold_notes: bool, tap_threshold_ms: u64, state: State, ) -> Result { @@ -635,7 +640,7 @@ fn set_note_processing( return Err("Chord detection tolerance must be between 0 and 1000 ms".into()); } state.engine.set_note_processing(amp_core::player::NoteProcessingSettings { - merge_notes, merge_tolerance_ms, auto_chord, chord_detection_milliseconds, + merge_notes, merge_tolerance_ms, chord_detection_milliseconds, }); Ok(true) } @@ -1587,6 +1592,83 @@ fn focus_game(pid: u32) -> Result { Ok(focus_window_by_pid(pid)) } +#[tauri::command] +async fn get_chord_wheel_state(state: State<'_, AppState>) -> Result { + let engine = Arc::clone(&state.engine); + tauri::async_runtime::spawn_blocking(move || engine.chord_wheel_state()).await.map_err(|e| e.to_string())? +} + +#[tauri::command] +async fn set_chord_wheel_page(page: usize, send: bool, state: State<'_, AppState>) -> Result { + let engine = Arc::clone(&state.engine); + let monitor = Arc::clone(&state.process_monitor); + let configs = Arc::clone(&state.config_manager); + let sources = Arc::clone(&state.config_sources); + tauri::async_runtime::spawn_blocking(move || { + if engine.get_status() == PlaybackStatus::Playing { return Err("Pause playback before changing the page manually.".into()); } + if send { + let selected_sources = sources.lock().map_err(|e| e.to_string())?.clone(); + let game_id = configs.lock().map_err(|e| e.to_string())?.games.iter() + .find(|game| game.instruments.iter().any(|instrument| instrument.file_path.as_ref() + .is_some_and(|path| selected_sources.iter().any(|source| source == Path::new(path))))) + .map(|game| game.config.id.clone()).ok_or("The selected instrument's game is unavailable.")?; + let target = monitor.lock().map_err(|e| e.to_string())?.check_statuses().into_iter() + .find(|game| game.id == game_id && game.is_running).and_then(|game| game.pid) + .ok_or("Start the selected game and open its chord wheel first.")?; + if !focus_window_by_pid(target) { return Err("Could not focus the selected game window.".into()); } + } + engine.set_chord_wheel_page(page, send)?; + Ok(true) + }).await.map_err(|e| e.to_string())? +} + +/// Explicit guitar sub-mode changes use the instrument's fret-layout binding. +/// Startup and ordinary config reloads never send this toggle to the game. +#[tauri::command] +async fn set_guitar_mode(mode: String, state: State<'_, AppState>) -> Result { + if !matches!(mode.as_str(), "chords" | "frets") { return Err("Unknown guitar mode.".into()); } + #[cfg(not(windows))] + { let _ = state; return Err("Guitar game output is currently supported on Windows only.".into()); } + #[cfg(windows)] + { + let engine = Arc::clone(&state.engine); + let monitor = Arc::clone(&state.process_monitor); + let configs = Arc::clone(&state.config_manager); + let sources = Arc::clone(&state.config_sources); + tauri::async_runtime::spawn_blocking(move || { + if engine.get_status() == PlaybackStatus::Playing { return Err("Pause playback before changing guitar mode.".into()); } + let selected_sources = sources.lock().map_err(|e| e.to_string())?.clone(); + let (game_id, binding) = { + let manager = configs.lock().map_err(|e| e.to_string())?; + let (game, instrument) = manager.games.iter().flat_map(|game| game.instruments.iter().map(move |instrument| (game, instrument))) + .find(|(_, instrument)| instrument.file_path.as_ref().is_some_and(|path| selected_sources.iter().any(|source| source == Path::new(path)))) + .ok_or("The selected guitar is unavailable.")?; + let current = selected_sources.iter().find_map(|source| manager.layouts.values().find(|layout| + layout.file_path.as_ref().is_some_and(|path| source == Path::new(path)))); + if current.is_some_and(|layout| layout.fretboard.is_some() == (mode == "frets")) { return Ok(true); } + let fret_layout = current.filter(|layout| layout.fretboard.is_some()) + .or_else(|| instrument.fret_layouts.iter().find_map(|id| manager.layouts.get(&id.to_lowercase()))) + .and_then(|layout| layout.fretboard.as_ref()).ok_or("The guitar has no fret mode binding.")?; + let binding = amp_core::parse_key_stroke(&fret_layout.mode_key).ok_or("Invalid guitar mode binding.")?; + (game.config.id.clone(), binding) + }; + let pid = monitor.lock().map_err(|e| e.to_string())?.check_statuses().into_iter() + .find(|game| game.id == game_id && game.is_running).and_then(|game| game.pid) + .ok_or("Start the selected game and open its guitar controls first.")?; + if !focus_window_by_pid(pid) { return Err("Could not focus the selected game window.".into()); } + let mut output = amp_core::KeySimulator::new(); + output.prepare()?; + output.press_stroke(binding); + std::thread::sleep(std::time::Duration::from_millis(35)); + output.send_key(binding.key, true); + output.release_all(&[binding.key]); + if let Some(error) = output.take_error() { return Err(error); } + std::thread::sleep(std::time::Duration::from_millis(120)); + Ok(true) + }).await.map_err(|e| e.to_string())? + } +} + #[tauri::command] fn tap_note_preview(pitch: u8, is_listen_mode: bool, state: State) -> Result { state.engine.tap_note(pitch, is_listen_mode); @@ -1656,20 +1738,43 @@ fn set_game_instrument_mapping( let mapping = mapping.with_pedal_bindings(layout_cfg); // The renderer already supplies the selected instrument's config path. // Resolve pads from that instrument, never another instrument sharing its layout. - if let Some(instrument) = cm.games.iter().flat_map(|game| &game.instruments) - .find(|instrument| instrument.file_path.as_ref() + if let Some((game, instrument)) = cm.games.iter().flat_map(|game| game.instruments.iter().map(move |instrument| (game, instrument))) + .find(|(_, instrument)| instrument.file_path.as_ref() .is_some_and(|path| sources.iter().any(|source| source == Path::new(path)))) { - mapping.with_chord_pads(instrument, layout_cfg) + let mut processes = game.config.process_names.clone(); + processes.extend(state.process_monitor.lock().map_err(|e| e.to_string())?.process_names_for_game(&game.config.id)); + processes.sort(); + processes.dedup(); + let mapping = if instrument.supports_fret_layout(&layout_cfg.id) { + let unavailable = |reason: &str| { + state.engine.set_config_available(false); + state.engine.set_mapping(NoteKeyMapping::from_pairs(KeyboardLayout::Diatonic21, &[])); + reason.to_owned() + }; + let fretboard = layout_cfg.fretboard.as_ref() + .ok_or_else(|| unavailable("The selected fret layout has no fretboard bindings."))?; + let wheel_layout = cm.layouts.get(&fretboard.wheel_layout.to_lowercase()) + .ok_or_else(|| unavailable("The fret layout's referenced wheel layout is unavailable."))?; + let wheel = wheel_layout.chord_wheel.as_ref() + .ok_or_else(|| unavailable("The referenced layout has no wheel controls."))?; + if let Some(path) = &wheel_layout.file_path { + if !Path::new(path).is_file() { return Err(unavailable("The referenced wheel layout file is unavailable.")); } + if !sources.iter().any(|source| source == Path::new(path)) { sources.push(PathBuf::from(path)); } + } + mapping.with_frets(instrument, layout_cfg, wheel) + } else { mapping.with_chord_pads(instrument, layout_cfg) }; + mapping.with_game_target(&game.config).with_game_process_names(&processes) } else { mapping } } else { mapping }; // Stop while the old mapping is still installed so its held keys are released. - if layout.is_empty() { state.engine.set_config_available(false); } + let available = !layout.is_empty() && mapping.has_playable_bindings(); + if !available { state.engine.set_config_available(false); } state.engine.set_mapping(mapping); - if !layout.is_empty() { state.engine.set_config_available(true); } - Ok(true) + if available { state.engine.set_config_available(true); } + Ok(available) } #[tauri::command] @@ -1691,6 +1796,32 @@ fn get_game_configs(state: State) -> Result { Ok(state.config_manager.lock().map_err(|e| e.to_string())?.snapshot()) } +#[tauri::command] +async fn get_default_config_updates(app: AppHandle) -> Result { + tauri::async_runtime::spawn_blocking(move || { + let report = config_manager::check_startup_defaults()?; + if !report.added_files.is_empty() { + if let Some(state) = app.try_state::() { reload_configs(&app, &state.config_manager, &state.process_monitor)?; } + } + Ok(report) + }).await.map_err(|e| e.to_string())? +} + +#[tauri::command] +async fn resolve_default_config_updates( + choices: Vec, duplicate_choices: Vec, app: AppHandle, +) -> Result { + tauri::async_runtime::spawn_blocking(move || { + if let Some(state) = app.try_state::() { + if choices.iter().chain(&duplicate_choices).any(|choice| choice.action == DefaultConfigAction::Replace) { state.engine.stop(); } + } + let result = config_manager::resolve_startup_defaults(&choices, &duplicate_choices); + // Refresh even after a partial I/O failure so the mapping matches files already saved. + if let Some(state) = app.try_state::() { reload_configs(&app, &state.config_manager, &state.process_monitor)?; } + result + }).await.map_err(|e| e.to_string())? +} + #[tauri::command] fn get_layout_pedal_defaults(layout_id: String, state: State) -> Result { state.config_manager.lock().map_err(|e| e.to_string())?.layout_pedal_defaults(&layout_id) @@ -1940,6 +2071,7 @@ struct StartupStatus { ready: bool, error: Option, update_resume: Option, + configuration_review_required: Option, } type StartupState = Arc>; @@ -1954,6 +2086,7 @@ fn start_runtime(app: AppHandle, gate: State) -> Result<(), String> let mut status = state.lock().map_err(|e| e.to_string())?; status.ready = false; status.stage = "Initializing application\u{2026}".into(); + status.configuration_review_required = Some(false); *started = true; wake.notify_one(); } @@ -2040,6 +2173,7 @@ pub fn run() { ready: false, error: None, update_resume: updates::load_resume(env!("CARGO_PKG_VERSION")), + configuration_review_required: None, })); app.manage(startup.clone()); let runtime_gate: RuntimeGate = Arc::new((Mutex::new(false), Condvar::new())); @@ -2050,13 +2184,18 @@ pub fn run() { let launch_settings = read_launch_settings().expect("Failed to read launch settings"); let completed = launch_settings.get("onboardingCompleted") .and_then(serde_json::Value::as_bool).unwrap_or(false); + // Check configurations before creating audio, DB, player, or process monitors. + let review_required = config_manager::check_startup_defaults() + .map(|report| report.needs_review()).unwrap_or(true); + startup.lock().unwrap().configuration_review_required = Some(review_required); let (lock, wake) = &*runtime_gate; let mut started = lock.lock().unwrap(); - if !completed { + if !completed || review_required { { let mut status = startup.lock().unwrap(); status.ready = true; // Preferences and window commands are available. - status.stage = "Waiting for setup\u{2026}".into(); + status.stage = if review_required { "Waiting for configuration review\u{2026}" } + else { "Waiting for setup\u{2026}" }.into(); } while !*started { started = wake.wait(started).unwrap(); @@ -2111,6 +2250,9 @@ pub fn run() { PlayerEvent::PedalsChanged(state) => { let _ = app_handle.emit("playback:pedals", state); } + PlayerEvent::ChordWheelChanged(state) => { + let _ = app_handle.emit("playback:chord_wheel", state); + } PlayerEvent::ActiveNotes(notes) => { let _ = app_handle.emit("playback:notes", notes); } @@ -2434,11 +2576,16 @@ pub fn run() { get_game_statuses, set_game_targets, focus_game, + get_chord_wheel_state, + set_chord_wheel_page, + set_guitar_mode, tap_note_preview, set_game_instrument_mapping, // Phase 9 modular config commands get_games, get_game_configs, + get_default_config_updates, + resolve_default_config_updates, get_keyboard_layouts, get_layout_pedal_defaults, save_layout_pedal_bindings, diff --git a/src-tauri/src/process_monitor.rs b/src-tauri/src/process_monitor.rs index ce7f88b2..f7c0a08b 100644 --- a/src-tauri/src/process_monitor.rs +++ b/src-tauri/src/process_monitor.rs @@ -102,6 +102,18 @@ impl ProcessMonitor { } } + /// Reuse configured aliases and executable preferences for native game input. + pub fn process_names_for_game(&self, game_id: &str) -> Vec { + let Some(target) = self.targets.iter().find(|target| target.id == game_id) else { return Vec::new() }; + let mut names = target.process_names.clone(); + #[cfg(windows)] + let location = self.locations.get(&target.id); + #[cfg(not(windows))] + let location = self.locations.get(&target.display_name).or_else(|| self.locations.get(&target.id)); + if let Some(location) = location { names.push(location.clone()); } + names + } + pub fn check_statuses(&mut self) -> Vec { // Linux's comm name is truncated to 15 bytes. Read exe and argv[0] too // for long native executable names and Wine/Proton executable paths. diff --git a/src-tauri/src/storage.rs b/src-tauri/src/storage.rs index e9024d6e..bc7fddc0 100644 --- a/src-tauri/src/storage.rs +++ b/src-tauri/src/storage.rs @@ -235,7 +235,8 @@ pub fn clear_data_files() -> Result<(), String> { } fn clear_data_files_with(root: &Path, recycle: impl FnOnce(&[PathBuf]) -> Result<(), String>) -> Result<(), String> { - for path in [root.to_path_buf(), root.join("cache"), root.join("OnlineMidi"), root.join("cache/discover")] { + for path in [root.to_path_buf(), root.join("cache"), root.join("OnlineMidi"), root.join("cache/discover"), + root.join("configuration-state.json"), root.join(".bundled-defaults.json"), root.join("ConfigBackups")] { match fs::symlink_metadata(&path) { Ok(meta) if is_link(&meta) => return Err(format!("Cannot clear linked app storage: {}", path.display())), Ok(_) => {}, @@ -243,7 +244,7 @@ fn clear_data_files_with(root: &Path, recycle: impl FnOnce(&[PathBuf]) -> Result Err(error) => return Err(error.to_string()), } } - let paths = ["OnlineMidi", "cache/discover", "cache/.discover-last-clean"].map(|name| root.join(name)); + let paths = ["OnlineMidi", "cache/discover", "cache/.discover-last-clean", "configuration-state.json", ".bundled-defaults.json", "ConfigBackups"].map(|name| root.join(name)); let paths: Vec<_> = paths.into_iter().filter(|path| path.exists()).collect(); // Recycle only fixed application-owned paths, never targets from settings. if !paths.is_empty() { recycle(&paths)?; } @@ -261,10 +262,11 @@ mod tests { use std::time::Duration; #[test] - fn clear_data_only_recycles_downloads_and_discover_cache() { + fn clear_data_recycles_payloads_and_configuration_review_data() { let root = std::env::temp_dir().join(format!("amp-clear-{}-{}", std::process::id(), SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos())); for path in ["OnlineMidi/song.mid", "cache/discover/preview.mid", "cache/.discover-last-clean", + "configuration-state.json", ".bundled-defaults.json", "ConfigBackups/review/KeyboardLayouts/old.json", "cache/update/installer.exe", "SoundFonts/custom.sf2", "EBWebView/Default/data", "logs/app.log", "Legacy/old.db", "AutoMidiPlayer.db", "settings.json"] { let file = root.join(path); @@ -272,7 +274,8 @@ mod tests { fs::write(file, b"kept").unwrap(); } clear_data_files_with(&root, |paths| { - assert_eq!(paths, [root.join("OnlineMidi"), root.join("cache/discover"), root.join("cache/.discover-last-clean")]); + assert_eq!(paths, [root.join("OnlineMidi"), root.join("cache/discover"), root.join("cache/.discover-last-clean"), + root.join("configuration-state.json"), root.join(".bundled-defaults.json"), root.join("ConfigBackups")]); for path in paths { if path.is_dir() { fs::remove_dir_all(path).unwrap(); } else { fs::remove_file(path).unwrap(); } @@ -281,6 +284,9 @@ mod tests { }).unwrap(); assert!(!root.join("OnlineMidi").exists()); assert!(!root.join("cache/discover").exists()); + assert!(!root.join("configuration-state.json").exists()); + assert!(!root.join(".bundled-defaults.json").exists()); + assert!(!root.join("ConfigBackups").exists()); for path in ["cache/update/installer.exe", "SoundFonts/custom.sf2", "EBWebView/Default/data", "logs/app.log", "Legacy/old.db", "AutoMidiPlayer.db", "settings.json"] { assert_eq!(fs::read(root.join(path)).unwrap(), b"kept"); diff --git a/src/renderer/App.svelte b/src/renderer/App.svelte index 7c6d5d34..7c019b20 100644 --- a/src/renderer/App.svelte +++ b/src/renderer/App.svelte @@ -503,7 +503,7 @@ - + {/if} diff --git a/src/renderer/configurationReview.ts b/src/renderer/configurationReview.ts new file mode 100644 index 00000000..93956f40 --- /dev/null +++ b/src/renderer/configurationReview.ts @@ -0,0 +1,37 @@ +import { mount, tick, unmount } from 'svelte'; +import './app.css'; +import ConfigUpdatesScreen from './lib/components/Layout/ConfigUpdatesScreen.svelte'; +import { defaultConfigStore } from './lib/state/defaultConfigStore.svelte'; +import { themeStore } from './lib/state/themeStore.svelte'; +import { animationStore } from './lib/state/animationStore.svelte'; +import { api } from './lib/backend'; +import { fadeConfigurationSurface } from './lib/utils/configurationReviewFade'; + +/** Mount only the setup view; App, audio, DB, playback, and process monitors stay deferred. */ +export async function reviewConfigurations(): Promise { + await Promise.all([ + defaultConfigStore.load(), + api.settings.getSettings().then(settings => themeStore.init(settings.theme, settings.accentColor)).catch(console.warn), + animationStore.init(), + ]); + const report = defaultConfigStore.report; + if (!defaultConfigStore.error && !report?.conflicts.length && !report?.duplicates.length && !report?.issues.length) return; + let proceed!: () => void; + const finished = new Promise(resolve => { proceed = resolve; }); + const view = mount(ConfigUpdatesScreen, { + target: document.getElementById('app')!, props: { oncontinue: proceed, onskip: proceed }, + }); + await tick(); + const splash = document.getElementById('boot-screen'); + const screen = document.querySelector('.config-updates-screen')!; + const fadeDuration = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : animationStore.durationMs; + try { + await fadeConfigurationSurface(splash, screen, fadeDuration()); + await finished; + } + finally { + // Do not wake the native runtime until the loader has faded back in. + if (splash) await fadeConfigurationSurface(screen, splash, fadeDuration()); + await unmount(view); + } +} diff --git a/src/renderer/lib/backend/configurationStartup.ts b/src/renderer/lib/backend/configurationStartup.ts new file mode 100644 index 00000000..2c05a5d6 --- /dev/null +++ b/src/renderer/lib/backend/configurationStartup.ts @@ -0,0 +1,26 @@ +interface ConfigurationStartupStatus { configurationReviewRequired: boolean | null } + +/** A launch with pending review must not import App or wake the native runtime yet. */ +export async function prepareConfigurationStartup(options: { + initialStatus?: T; + readStatus: () => Promise; + onStatus: (status: T) => void; + review: () => Promise; + getSettings: () => Promise<{ onboardingCompleted?: boolean }>; + startRuntime: () => Promise; + wait?: () => Promise; +}): Promise { + let status = options.initialStatus; + for (;;) { + status ??= await options.readStatus(); + options.onStatus(status); + if (status.configurationReviewRequired !== null) break; + await (options.wait?.() ?? new Promise(resolve => setTimeout(resolve, 50))); + status = undefined; + } + if (!status.configurationReviewRequired) return status; + await options.review(); + // Fresh installs still defer the runtime until the normal onboarding Finish step. + if ((await options.getSettings()).onboardingCompleted) await options.startRuntime(); + return undefined; +} diff --git a/src/renderer/lib/backend/mappers.ts b/src/renderer/lib/backend/mappers.ts index fe1e7d8c..9b07b113 100644 --- a/src/renderer/lib/backend/mappers.ts +++ b/src/renderer/lib/backend/mappers.ts @@ -26,7 +26,6 @@ export interface RawSongRecord { imagePath?: string; cachedDurationMs?: number; cachedNativeBpm?: number; - autoChord?: boolean; chordDetectionMilliseconds?: number; keyChanges?: string; enableKeyChangeMarkers?: boolean; @@ -68,8 +67,12 @@ export interface RawLoadedBundle { layoutStyle?: InstrumentLayoutStyle; keys?: KeyMatrix; notes?: number[]; - supportedLayouts?: string[]; - chordPads?: Array<{ name: string; pitchClasses: number[] }>; + keyboardLayouts?: string[]; + chordLayouts?: string[]; + fretLayouts?: string[]; + guitar?: { tuning: number[]; fretCount: number }; + chords?: Array<{ name: string; pitchClasses: number[] }>; + chordMode?: 'pads' | 'wheel'; supportsPedals?: boolean; supportsChords?: boolean; subfolder?: string; @@ -150,7 +153,6 @@ export function songRecordToMidiFile(record: RawSongRecord): MidiFile { holdNotes: record.holdNotes ?? DEFAULT_APP_SETTINGS.defaultHoldNotes, tapThresholdMs: record.tapThresholdMs ?? DEFAULT_APP_SETTINGS.defaultTapThresholdMs, disabledTracks: record.disabledTracks ?? null, - autoChord: record.autoChord ?? DEFAULT_APP_SETTINGS.defaultAutoChord, chordDetectionMilliseconds: record.chordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds, enableKeyChangeMarkers: record.enableKeyChangeMarkers ?? DEFAULT_APP_SETTINGS.defaultEnableKeyChangeMarkers, dateAdded: record.dateAdded || new Date().toISOString(), @@ -288,7 +290,6 @@ export function loadedMidiToMidiFile(raw: RawLoadedMidiFile | MidiFile): MidiFil holdNotes: typeof source.holdNotes === 'boolean' ? source.holdNotes : DEFAULT_APP_SETTINGS.defaultHoldNotes, tapThresholdMs: Number(source.tapThresholdMs ?? DEFAULT_APP_SETTINGS.defaultTapThresholdMs), disabledTracks: typeof source.disabledTracks === 'string' ? source.disabledTracks : null, - autoChord: typeof source.autoChord === 'boolean' ? source.autoChord : DEFAULT_APP_SETTINGS.defaultAutoChord, chordDetectionMilliseconds: Number(source.chordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds), enableKeyChangeMarkers: typeof source.enableKeyChangeMarkers === 'boolean' ? source.enableKeyChangeMarkers : DEFAULT_APP_SETTINGS.defaultEnableKeyChangeMarkers, dateAdded: String(source.dateAdded ?? new Date().toISOString()), @@ -329,7 +330,7 @@ export function loadedBundleToGameInfo( const layouts = Object.values(normalizedLayouts); for (const instrument of bundle.instruments || []) { - for (const layoutId of instrument.supportedLayouts || []) { + for (const layoutId of [...instrument.keyboardLayouts ?? [], ...instrument.chordLayouts ?? [], ...instrument.fretLayouts ?? []]) { const layout = normalizedLayouts[layoutId.toLowerCase()] || layouts.find((candidate) => candidate.id.toLowerCase() === layoutId.toLowerCase() || candidate.name.toLowerCase() === layoutId.toLowerCase(), @@ -346,10 +347,14 @@ export function loadedBundleToGameInfo( layoutStyle: instrument.layoutStyle, keys: instrument.keys, notes: instrumentNotes(instrument), - supportedLayouts: instrument.supportedLayouts || [], - chordPads: instrument.chordPads || [], + keyboardLayouts: instrument.keyboardLayouts || [], + chordLayouts: instrument.chordLayouts || [], + fretLayouts: instrument.fretLayouts || [], + guitar: instrument.guitar, + chords: instrument.chords || [], + chordMode: instrument.chordMode ?? 'pads', supportsPedals: instrument.supportsPedals ?? false, - supportsChords: instrument.supportsChords ?? Boolean(instrument.chordPads?.length), + supportsChords: instrument.supportsChords ?? Boolean(instrument.chords?.length), supportsSustain: instrument.supportsPedals ?? false, subfolder: instrument.subfolder, filePath: instrument.filePath, diff --git a/src/renderer/lib/backend/nativeApi.ts b/src/renderer/lib/backend/nativeApi.ts index 3283cdd5..eac13b54 100644 --- a/src/renderer/lib/backend/nativeApi.ts +++ b/src/renderer/lib/backend/nativeApi.ts @@ -1,6 +1,6 @@ import { DEFAULT_APP_SETTINGS } from '../../../shared/defaults/settings.js'; -import type { AppWindowApi, PedalState, SongSettingsContext, StorageUsage, LegacyDataStatus, LegacyMigrationResult } from '$shared/types/ipc.js'; -import type { GameStatus, GameConfigState, ConfigIssue, KeyboardLayoutConfig } from '$shared/types/games.js'; +import type { AppWindowApi, PedalState, ChordWheelState, SongSettingsContext, StorageUsage, LegacyDataStatus, LegacyMigrationResult } from '$shared/types/ipc.js'; +import type { GameStatus, GameConfigState, ConfigIssue, KeyboardLayoutConfig, DefaultConfigUpdates } from '$shared/types/games.js'; import type { MidiFile } from '$shared/types/midi.js'; import type { SystemSnapshot } from '$shared/types/system.js'; import type { MidiInputState } from '$shared/types/midiInput.js'; @@ -49,7 +49,6 @@ function serializeSongSettings(song: MidiFile) { mergeMilliseconds: song.mergeToleranceMs ?? DEFAULT_APP_SETTINGS.defaultMergeToleranceMs, holdNotes: song.holdNotes, tapThresholdMs: song.tapThresholdMs ?? DEFAULT_APP_SETTINGS.defaultTapThresholdMs, - autoChord: song.autoChord ?? DEFAULT_APP_SETTINGS.defaultAutoChord, chordDetectionMilliseconds: song.chordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds, enableKeyChangeMarkers: song.enableKeyChangeMarkers ?? DEFAULT_APP_SETTINGS.defaultEnableKeyChangeMarkers, }; @@ -142,8 +141,12 @@ export function createAppApi(): AppWindowApi { setTrackVolume: (trackIndex, volume) => invokeTauri('Playback', 'set_track_volume', { trackIndex, volume }), setListenMode: (enabled) => invokeTauri('Playback', 'set_listen_mode', { enabled }), setNoteTiming: (holdNotes, tapThresholdMs) => invokeTauri('Playback', 'set_note_timing', { holdNotes, tapThresholdMs }), - setNoteProcessing: (mergeNotes, mergeToleranceMs, autoChord, chordDetectionMilliseconds) => - invokeTauri('Playback', 'set_note_processing', { mergeNotes, mergeToleranceMs, autoChord, chordDetectionMilliseconds }), + setNoteProcessing: (mergeNotes, mergeToleranceMs, chordDetectionMilliseconds) => + invokeTauri('Playback', 'set_note_processing', { mergeNotes, mergeToleranceMs, chordDetectionMilliseconds }), + getChordWheelState: () => invokeTauri('Playback', 'get_chord_wheel_state', undefined), + setGuitarMode: (mode) => invokeTauri('Playback', 'set_guitar_mode', { mode }), + setChordWheelPage: (page, send) => invokeTauri('Playback', 'set_chord_wheel_page', { page, send }), + onChordWheelState: (callback) => listenTauri('playback:chord_wheel', callback), setKeyMarkers: (markers) => invokeTauri('Playback', 'set_key_markers', { markers: markers.map((marker) => ({ timeMs: marker.timeMs ?? Math.round((marker.time ?? 0) * 1000), @@ -279,6 +282,8 @@ export function createAppApi(): AppWindowApi { games: { getConfigs, + getDefaultConfigUpdates: () => invokeTauri('Games', 'get_default_config_updates', undefined), + resolveDefaultConfigUpdates: (choices, duplicateChoices) => invokeTauri('Games', 'resolve_default_config_updates', { choices, duplicateChoices }), onConfigsChanged: async (callback) => { if (!isTauriEnvironment) return () => {}; const { listen } = await import('@tauri-apps/api/event'); diff --git a/src/renderer/lib/components/Common/CustomScrollViewer.svelte b/src/renderer/lib/components/Common/CustomScrollViewer.svelte index 8105150d..d93d69a9 100644 --- a/src/renderer/lib/components/Common/CustomScrollViewer.svelte +++ b/src/renderer/lib/components/Common/CustomScrollViewer.svelte @@ -19,6 +19,8 @@ overlayScrollbar?: boolean; // Draw the scrollbar over content without reserving a gutter. scrollContainer?: HTMLDivElement; // Bindable ref to the scrollable element persistenceKey?: string; + tabIndex?: number; + ariaLabel?: string; onscroll?: (e: Event) => void; onwheel?: (e: WheelEvent) => void; onpointerdown?: (e: PointerEvent) => void; @@ -45,6 +47,8 @@ overlayScrollbar = false, scrollContainer = $bindable(), persistenceKey, + tabIndex = -1, + ariaLabel, onscroll: externalOnScroll, onwheel: externalOnWheel, onpointerdown: externalOnPointerDown, @@ -246,14 +250,15 @@ {style} > - +
.gradient-sweep-inner { justify-content: flex-end; text-align: right; } - .gradient-sweep.horizontal .gradient-sweep-inner { + .gradient-sweep.horizontal > .gradient-sweep-inner { display: inline-flex; align-items: center; + flex-shrink: 0; width: max-content; white-space: nowrap; box-sizing: border-box; @@ -293,7 +294,7 @@ mask-repeat: no-repeat; } - .gradient-sweep.vertical .gradient-sweep-inner { + .gradient-sweep.vertical > .gradient-sweep-inner { width: 100%; display: flex; flex-direction: column; diff --git a/src/renderer/lib/components/Common/JsonDiffViewer.svelte b/src/renderer/lib/components/Common/JsonDiffViewer.svelte new file mode 100644 index 00000000..e83db0fb --- /dev/null +++ b/src/renderer/lib/components/Common/JsonDiffViewer.svelte @@ -0,0 +1,199 @@ + + +{#snippet line(content: DiffLine | null, tone: 'equal' | 'removed' | 'added', sourceLabel: string)} +
+ + + {#if content}{sourceLabel}, {t(`jsonDiff.${tone}Line`, { line: content.lineNumber })}: {/if} + {#if content}{#each content.parts as part}{part.text}{/each}{/if} +
+{/snippet} + +
+
+
+ {#if showChoiceTabs} + selectChoice(id as DiffChoice)} + tabs={[ + { id: 'keep', label: keepLabel, title: keepTitle }, + { id: 'replace', label: replaceLabel, title: replaceTitle }, + ]} + /> + {/if} +
+ {#if diff.changeStarts.length} + +{diff.added} + −{diff.removed} + ~{diff.modified} + {:else}{t('jsonDiff.noChanges')}{/if} +
+
+
+ {#if diff.changeStarts.length}{t('jsonDiff.position', { current: currentChange + 1, total: diff.changeStarts.length })}{/if} +
+
+
+
+ {#if diff.invalidLeft || diff.invalidRight}

{t('jsonDiff.invalidJson')}

{/if} +
+ {#if narrow}{beforeLabel} / {afterLabel} + {:else}{beforeLabel}{afterLabel}{/if} +
+ +
+ {#each diff.rows as row, index} +
+ {#if narrow} + {#if row.kind === 'equal'}{@render line(row.right ?? row.left, 'equal', afterLabel)} + {:else} + {#if row.left}{@render line(row.left, 'removed', beforeLabel)}{/if} + {#if row.right}{@render line(row.right, 'added', afterLabel)}{/if} + {/if} + {:else} + {@render line(row.left, row.kind === 'equal' ? 'equal' : 'removed', beforeLabel)} + {@render line(row.right, row.kind === 'equal' ? 'equal' : 'added', afterLabel)} + {/if} +
+ {/each} +
+
+
+ + diff --git a/src/renderer/lib/components/Common/SlidingTabs.svelte b/src/renderer/lib/components/Common/SlidingTabs.svelte index 8f8587ac..54ed38f2 100644 --- a/src/renderer/lib/components/Common/SlidingTabs.svelte +++ b/src/renderer/lib/components/Common/SlidingTabs.svelte @@ -1,11 +1,13 @@ -
{#each tabs as tab, index (tab.id)}
-
diff --git a/src/renderer/lib/components/Instrument/ChordPadsLayout.svelte b/src/renderer/lib/components/Instrument/ChordPadsLayout.svelte new file mode 100644 index 00000000..339ed085 --- /dev/null +++ b/src/renderer/lib/components/Instrument/ChordPadsLayout.svelte @@ -0,0 +1,31 @@ + + +
+ {#each chords as chord, index} + + {/each} +
+ + diff --git a/src/renderer/lib/components/Instrument/ChordWheelControls.svelte b/src/renderer/lib/components/Instrument/ChordWheelControls.svelte new file mode 100644 index 00000000..32a3e981 --- /dev/null +++ b/src/renderer/lib/components/Instrument/ChordWheelControls.svelte @@ -0,0 +1,124 @@ + + +
+
+
{t(fretMode ? 'instrument.fretboard' : 'instrument.chordWheel')}
+
+ + {wheelState.page === null ? t('instrument.chordWheelUnknownPage') : + t('instrument.chordWheelPage', { page: wheelState.page + 1, count: wheel.pageCount })} + +
+
+ {t('instrument.chordWheelSyncPage')} + setPage(page, false)} /> +
+
+
+ {#each visiblePads as pad} + {pad.name} + {/each} +
+

{t(fretMode ? 'instrument.guitarSharedFret' : 'instrument.chordWheelHint')}

+
+ + diff --git a/src/renderer/lib/components/Instrument/GuitarLayout.svelte b/src/renderer/lib/components/Instrument/GuitarLayout.svelte new file mode 100644 index 00000000..997daed2 --- /dev/null +++ b/src/renderer/lib/components/Instrument/GuitarLayout.svelte @@ -0,0 +1,74 @@ + + +
+
+ {t(mode === 'chords' ? 'instrument.chordWheel' : 'instrument.fretboard')} + {mode === 'chords' ? chord ?? t('instrument.guitarWaiting') : positions.length ? t('instrument.guitarFret', { fret: positions[0].fret }) : t('instrument.guitarWaiting')} +
+ {#if mode === 'chords'} +
+ {#each instrument.chords ?? [] as item}{item.name}{/each} +
+ {/if} +
+
+ {t('instrument.guitarString')} + {#each Array.from({ length: count + 1 }, (_, fret) => fret) as fret}{fret}{/each} + {#each tuning as open, string} + {string + 1}{noteName(open)} + {#each Array.from({ length: count + 1 }, (_, fret) => fret) as fret} + + {#if activeCells.has(`${string}/${fret}`)}{fret}{/if} + + {/each} + {/each} +
+
+
+ {t('instrument.guitarTabPreview')} + {#each tuning as open, string}{noteName(open)}{activeFrets.get(string) ?? '—'}{/each} +
+

{mode === 'frets' && activePitches.size && !positions.length ? t('instrument.guitarUnplayable') : t('instrument.guitarSharedFret')}

+
+ + diff --git a/src/renderer/lib/components/Layout/ConfigUpdatesReview.svelte b/src/renderer/lib/components/Layout/ConfigUpdatesReview.svelte new file mode 100644 index 00000000..8bbe950c --- /dev/null +++ b/src/renderer/lib/components/Layout/ConfigUpdatesReview.svelte @@ -0,0 +1,158 @@ + + +
+
+

{t('defaultConfigs.description')}

+ {#if store.error}{/if} + {#each store.report?.issues ?? [] as issue} + + {/each} + {#if conflicts.length} +
+ { replacements = new Set(checked ? conflicts.map(conflict => conflict.id) : []); }} /> + {t('defaultConfigs.selection', { replace: replaceCount, keep: conflicts.length - replaceCount })} +
+
+ + {#each conflicts as conflict (conflict.id)} + + {/each} + + {#if selected} +
+

{heading}

+

{selected.path}

+ {#if fields.length}

{t('defaultConfigs.changedFields', { fields: fields.join(', ') })}

{/if} + {#if selected.duplicate} +

{t('defaultConfigs.duplicateExplanation')}

+
+

{t('defaultConfigs.fileToKeep')} {selected.duplicate.keep.path} +

+ {#each selected.duplicate.olderFiles as file} +

{t('defaultConfigs.fileToRemove')} {file.path} +

+ {/each} +
+ {:else if selected.path !== selected.id}

{t('defaultConfigs.bundledPath', { path: selected.id })}

{/if} + {#key selected.id} + setReplacement(selected.id, next === 'replace')} + beforeLabel={t(selected.duplicate ? 'defaultConfigs.olderFile' : 'defaultConfigs.current')} + afterLabel={t(selected.duplicate ? 'defaultConfigs.fileToKeep' : 'defaultConfigs.bundled')} /> + {/key} +
+ {/if} +
+ {:else if store.loading} +

{t('defaultConfigs.checking')}

+ {:else if !store.error && !store.report?.issues.length} +

{t('defaultConfigs.upToDate')}

+ {/if} +
+
+ {#if conflicts.length} +

{t('defaultConfigs.backupNote')}

+ {/if} + +
+
+ + diff --git a/src/renderer/lib/components/Layout/ConfigUpdatesScreen.svelte b/src/renderer/lib/components/Layout/ConfigUpdatesScreen.svelte new file mode 100644 index 00000000..f125a007 --- /dev/null +++ b/src/renderer/lib/components/Layout/ConfigUpdatesScreen.svelte @@ -0,0 +1,72 @@ + + +
+
+
+ + {t('titleBar.appName')} +
+
+ + + +
+
+
+

{t('defaultConfigs.beforeStartup')}

+

{t('defaultConfigs.title')}

+ +
+ +
+ + diff --git a/src/renderer/lib/components/Studio/StudioSidebar.svelte b/src/renderer/lib/components/Studio/StudioSidebar.svelte index 555e2325..e295f0b8 100644 --- a/src/renderer/lib/components/Studio/StudioSidebar.svelte +++ b/src/renderer/lib/components/Studio/StudioSidebar.svelte @@ -318,16 +318,6 @@
-
-
-
{t('studio.autoChord')}
-
{t('studio.autoChordDesc')}
-
- playbackStore.setAutoChord(val)} - /> -
diff --git a/src/renderer/lib/i18n/locales/en-US.ts b/src/renderer/lib/i18n/locales/en-US.ts index d665ef6c..aa168cca 100644 --- a/src/renderer/lib/i18n/locales/en-US.ts +++ b/src/renderer/lib/i18n/locales/en-US.ts @@ -1,4 +1,54 @@ export const enUS = { + jsonDiff: { + comparison: 'JSON comparison', + addedLines: '{count} added lines', + removedLines: '{count} removed lines', + modifiedLines: '{count} modified lines', + noChanges: 'No differences', + position: 'Change {current} of {total}', + previous: 'Previous change', + next: 'Next change', + invalidJson: 'Invalid JSON is shown as plain text.', + formattedLines: 'Line numbers refer to the formatted comparison.', + equalLine: 'unchanged line {line}', + removedLine: 'removed line {line}', + addedLine: 'added line {line}', + choice: 'Comparison choice', + keep: 'Keep', + replace: 'Replace', + }, + defaultConfigs: { + title: 'Review Updated Configurations', + description: 'Review updated defaults and duplicate IDs before the player starts. Missing bundled files are added automatically. Only selected changes will be applied.', + beforeStartup: 'Configuration setup', + continue: 'Continue', + duplicateId: 'Duplicate ID', + keepBoth: 'Keep both', + duplicateExplanation: 'These files share an ID. The file with the latest modification time will be kept; path order breaks timestamp ties. Review the exact files below before removing older copies.', + fileToKeep: 'File to keep', + fileToRemove: 'File to remove', + olderFile: 'Older duplicate', + replaceDuplicate: 'Keep the newer file and delete the older duplicates', + layout: 'Keyboard layout', + instrument: 'Instrument', + game: 'Game', + keep: 'Keep', + replace: 'Replace', + replaceFile: 'Replace this file with the bundled default', + replaceAll: 'Select all changes', + selection: '{replace} selected · {keep} unchanged', + current: 'Current file', + bundled: 'Bundled default', + bundledPath: 'Bundled file: {path}', + changedFields: 'Changed fields: {fields}', + backupNote: 'Replaced or deleted files are backed up in ConfigBackups in app data folder.', + checking: 'Checking bundled defaults…', + upToDate: 'No default updates need review.', + retry: 'Check again', + later: 'Skip for now', + apply: 'Apply Choices', + applying: 'Applying…', + }, systemInfo: { title: 'System information', os: 'Operating system / version', @@ -195,6 +245,8 @@ export const enUS = { close: 'Close', }, player: { + playbackUnavailable: 'Playback unavailable', + chooseValidLayout: 'In Instrument View, choose an instrument with a valid layout, then press Play.', noSongPlaying: 'No song playing', unknownArtist: 'Unknown artist', play: 'Play', @@ -404,10 +456,37 @@ export const enUS = { resetPedals: 'Reset', resetPedalsTooltip: 'Reset pedal bindings to defaults', pedalsResetSuccess: 'Pedal bindings reset to defaults.', - autoChord: 'Auto Chord', - detectPlayChords: 'Arrange the whole song using this instrument’s chord pads', chordTolerance: 'Strum tolerance', - noChordSupport: 'Selected instrument does not support chords.', + chordWheel: 'Chord wheel', + guitarInputMode: 'Guitar input mode', + inputMode: 'Instrument input mode', + view: 'View', + mode: 'Mode', + guitarMode_keyboard: 'Keyboard', + guitarMode_chords: 'Chords', + guitarMode_frets: 'Frets', + guitarView: 'Guitar', + fretboard: 'Fretboard', + guitarWaiting: 'Waiting for notes', + guitarFret: 'Fret {fret}', + guitarString: 'String', + guitarTabPreview: 'String / fret', + guitarOpen: 'Open', + guitarUnplayable: 'These notes require different fret positions and cannot be plucked together in this game mode.', + guitarSharedFret: 'One fret is shared by all six strings. Pause playback before changing guitar mode.', + chordWheelPages: 'Chord wheel pages', + chordWheelPage: 'Page {page} of {count}', + chordWheelPrevious: 'Previous', + chordWheelNext: 'Next', + chordWheelPreviousKey: 'Previous game page ({key})', + chordWheelNextKey: 'Next game page ({key})', + chordWheelUnknownPage: 'Page unknown', + chordWheelSyncPage: 'Sync game page', + chordWheelSyncHint: 'Choose the page currently visible in the game to synchronize AMP. This does not change the game page.', + chordWheelAvailableChords: 'Chords on this page', + chordWheelHint: 'Open the guitar chord wheel in the game and match the game page. Pages switch automatically during playback.', + chordWheelError: 'Chord wheel unavailable', + chordWheelPageFailed: 'Unable to change the chord wheel page.', noPedalSupport: 'Selected instrument does not support pedals.', midiStart: 'Start MIDI input', midiDeviceUnavailable: 'Selected device unavailable', @@ -475,8 +554,6 @@ export const enUS = { transposeModeLabel: 'Transpose Mode', holdNotes: 'Hold Notes', holdNotesDesc: 'Release note on NoteOff', - autoChord: 'Auto Chord', - autoChordDesc: 'Arrange the whole song as supported instrument chords', keyMarkers: 'Key Change Markers', keyMarkersDesc: 'Apply timeline key offset changes', tempoBpm: 'Tempo (BPM)', diff --git a/src/renderer/lib/i18n/locales/zh-CN.ts b/src/renderer/lib/i18n/locales/zh-CN.ts index 49f40f6e..f37fa73a 100644 --- a/src/renderer/lib/i18n/locales/zh-CN.ts +++ b/src/renderer/lib/i18n/locales/zh-CN.ts @@ -1,6 +1,56 @@ import type { TranslationSchema } from './en-US'; export const zhCN: TranslationSchema = { + jsonDiff: { + comparison: 'JSON 对比', + addedLines: '新增 {count} 行', + removedLines: '删除 {count} 行', + modifiedLines: '修改 {count} 行', + noChanges: '没有差异', + position: '更改 {current} / {total}', + previous: '上一个更改', + next: '下一个更改', + invalidJson: '无效 JSON 将以纯文本显示。', + formattedLines: '行号对应格式化后的对比内容。', + equalLine: '未更改的第 {line} 行', + removedLine: '已删除的第 {line} 行', + addedLine: '新增的第 {line} 行', + choice: '更改选择', + keep: '保留', + replace: '替换', + }, + defaultConfigs: { + title: '检查已更新的配置', + description: '在播放器启动前检查默认配置更新和重复 ID。缺少的内置文件会自动添加。仅应用已勾选的更改。', + beforeStartup: '配置设置', + continue: '继续', + duplicateId: '重复 ID', + keepBoth: '全部保留', + duplicateExplanation: '这些文件使用了相同的 ID。将保留修改时间最新的文件;时间相同时按路径排序。移除旧副本前,请检查下方列出的具体文件。', + fileToKeep: '保留的文件', + fileToRemove: '移除的文件', + olderFile: '较旧的重复文件', + replaceDuplicate: '保留新文件并删除较旧的重复文件', + layout: '键盘布局', + instrument: '乐器', + game: '游戏', + keep: '保留', + replace: '替换', + replaceFile: '用内置默认配置替换此文件', + replaceAll: '选择所有更改', + selection: '已选择 {replace} 个 · 不更改 {keep} 个', + current: '当前文件', + bundled: '内置默认配置', + bundledPath: '内置文件:{path}', + changedFields: '更改的字段:{fields}', + backupNote: '被替换或删除的文件会备份到应用数据目录中的 ConfigBackups 文件夹。', + checking: '正在检查内置默认配置…', + upToDate: '没有需要检查的默认配置更新。', + retry: '重新检查', + later: '暂时跳过', + apply: '应用选择', + applying: '正在应用…', + }, systemInfo: { title: '系统信息', os: '操作系统 / 版本', @@ -197,6 +247,8 @@ export const zhCN: TranslationSchema = { close: '关闭', }, player: { + playbackUnavailable: '无法播放', + chooseValidLayout: '请在乐器视图中选择具有有效布局的乐器,然后按播放。', noSongPlaying: '未在播放歌曲', unknownArtist: '未知艺术家', play: '播放', @@ -406,10 +458,37 @@ export const zhCN: TranslationSchema = { resetPedals: '重置', resetPedalsTooltip: '恢复踏板按键默认值', pedalsResetSuccess: '踏板按键映射已恢复默认。', - autoChord: '自动和弦', - detectPlayChords: '使用当前乐器的和弦键编配整首歌曲', chordTolerance: '扫弦容差', - noChordSupport: '所选乐器不支持和弦演奏。', + chordWheel: '和弦轮盘', + guitarInputMode: '吉他输入模式', + inputMode: '乐器输入模式', + view: '视图', + mode: '模式', + guitarMode_keyboard: '键盘', + guitarMode_chords: '和弦', + guitarMode_frets: '品格', + guitarView: '吉他', + fretboard: '指板', + guitarWaiting: '等待音符', + guitarFret: '第 {fret} 品', + guitarString: '弦', + guitarTabPreview: '弦 / 品格', + guitarOpen: '空弦', + guitarUnplayable: '这些音符需要不同的品位,无法在此游戏模式中同时拨奏。', + guitarSharedFret: '六根弦共用一个品格。切换吉他模式前请暂停播放。', + chordWheelPages: '和弦轮盘页面', + chordWheelPage: '第 {page} / {count} 页', + chordWheelPrevious: '上一页', + chordWheelNext: '下一页', + chordWheelPreviousKey: '游戏上一页({key})', + chordWheelNextKey: '游戏下一页({key})', + chordWheelUnknownPage: '页面未知', + chordWheelSyncPage: '同步游戏页面', + chordWheelSyncHint: '选择游戏当前显示的页面以同步 AMP。此操作不会切换游戏页面。', + chordWheelAvailableChords: '此页和弦', + chordWheelHint: '在游戏中打开吉他和弦轮盘并同步游戏页面。播放时会自动翻页。', + chordWheelError: '和弦轮盘不可用', + chordWheelPageFailed: '无法切换和弦轮盘页面。', noPedalSupport: '所选乐器不支持踏板。', midiStart: '启动 MIDI 输入', midiDeviceUnavailable: '所选设备不可用', @@ -477,8 +556,6 @@ export const zhCN: TranslationSchema = { transposeModeLabel: '移调模式', holdNotes: '长音保持', holdNotesDesc: '在 NoteOff 时释放按键', - autoChord: '自动和弦', - autoChordDesc: '将整首歌曲编配为乐器支持的和弦', keyMarkers: '变调标记', keyMarkersDesc: '应用时间轴上的变调标记', tempoBpm: '曲速 (BPM)', diff --git a/src/renderer/lib/state/defaultConfigStore.svelte.ts b/src/renderer/lib/state/defaultConfigStore.svelte.ts new file mode 100644 index 00000000..fc6db64a --- /dev/null +++ b/src/renderer/lib/state/defaultConfigStore.svelte.ts @@ -0,0 +1,51 @@ +import type { DefaultConfigUpdates } from '../../../shared/types/games.js'; +import { api } from '../backend/index.js'; + +class DefaultConfigStore { + report = $state(null); + error = $state(''); + loading = $state(false); + saving = $state(false); + + async load() { + if (this.loading || this.saving) return; + this.loading = true; + this.error = ''; + try { + this.report = await api.games.getDefaultConfigUpdates(); + } catch (error) { + this.error = String(error); + } finally { + this.loading = false; + } + } + + async apply(replaceIds: ReadonlySet): Promise { + if (!this.report || this.saving || this.loading) return false; + this.saving = true; + this.error = ''; + const choices = this.report.conflicts.map(conflict => ({ + id: conflict.id, token: conflict.token, + action: replaceIds.has(conflict.id) ? 'replace' as const : 'keep' as const, + })); + const duplicateChoices = (this.report.duplicates ?? []).map(duplicate => ({ + id: duplicate.id, token: duplicate.token, + action: replaceIds.has(duplicate.id) ? 'replace' as const : 'keep' as const, + })); + try { + this.report = await api.games.resolveDefaultConfigUpdates(choices, duplicateChoices); + return true; + } catch (error) { + this.error = String(error); + // A file may have changed while the comparison was open, or a later write failed. + // Refresh the preview before letting the user consent to another attempt. + try { this.report = await api.games.getDefaultConfigUpdates(); } + catch { this.report = null; } + return false; + } finally { + this.saving = false; + } + } +} + +export const defaultConfigStore = new DefaultConfigStore(); diff --git a/src/renderer/lib/state/gameStore.svelte.ts b/src/renderer/lib/state/gameStore.svelte.ts index 1dbecc55..873bb470 100644 --- a/src/renderer/lib/state/gameStore.svelte.ts +++ b/src/renderer/lib/state/gameStore.svelte.ts @@ -1,7 +1,7 @@ -import type { GameInfo, GameStatus, GameConfigState, InstrumentConfig } from '../../../shared/types/games.js'; +import type { GameInfo, GameStatus, GameConfigState, InstrumentConfig, InstrumentInputMode } from '../../../shared/types/games.js'; import type { SongSettingsContext } from '../../../shared/types/ipc.js'; import type { PedalBindings } from '../../../shared/types/settings.js'; -import { instrumentKeyPairs } from '../../../shared/utils/instrumentLayout.js'; +import { instrumentKeyPairs, instrumentLayoutIds } from '../../../shared/utils/instrumentLayout.js'; import { api } from '../backend/index.js'; import { notificationCenter } from '../ui/notificationCenter.svelte'; @@ -12,6 +12,7 @@ class GameStore { private selectedLayoutIds = $state>({}); private configRefresh: Promise | null = null; private configDirty = false; + private mappingReady: Promise = Promise.resolve(false); private reportedIssues = new Set(); private settingsContextListeners: (() => void)[] = []; private contextKey = ''; @@ -33,10 +34,41 @@ class GameStore { return this.getGameLayout(this.activeGame); } + get activeInputMode(): InstrumentInputMode { return this.getInputMode(this.activeGame); } + + getInputMode(game: GameInfo | null, instrument = this.getGameInstrument(game)): InstrumentInputMode { + if (!game || !instrument) return 'keyboard'; + const key = `${game.id}/${instrument.id}`; + const saved = this.selectedLayoutIds[`${key}/mode`] as InstrumentInputMode | undefined; + if (saved && instrumentLayoutIds(instrument, saved).length) return saved; + const layout = this.selectedLayoutIds[key]; + return (['keyboard', 'chords', 'frets'] as const).find(mode => + layout && instrumentLayoutIds(instrument, mode).includes(layout)) + ?? (['keyboard', 'chords', 'frets'] as const).find(mode => instrumentLayoutIds(instrument, mode).length) ?? 'keyboard'; + } + + async setInputMode(mode: InstrumentInputMode) { + const game = this.activeGame; + const instrument = this.activeInstrument; + if (!game || !instrument || !instrumentLayoutIds(instrument, mode).length || mode === this.activeInputMode) return; + const previous = this.activeInputMode; + if (game.isRunning && previous !== 'keyboard' && mode !== 'keyboard') { + if (!await api.playback.setGuitarMode(mode)) throw new Error('Unable to change the game guitar mode.'); + } + this.selectedLayoutIds[`${game.id}/${instrument.id}/mode`] = mode; + await Promise.all([ + this.syncActiveInstrumentMapping(), + api.settings.updateSettings({ selectedLayoutIds: { ...this.selectedLayoutIds } }), + ]); + } + getGameLayout(game: GameInfo | null, instrument = this.getGameInstrument(game)) { if (!game || !instrument) return null; - const layouts = this.getInstrumentLayouts(instrument, game); - const selected = this.selectedLayoutIds[`${game.id}/${instrument.id}`]; + const mode = this.getInputMode(game, instrument); + const layouts = this.getInstrumentLayouts(instrument, game, mode); + const key = `${game.id}/${instrument.id}`; + const selected = this.selectedLayoutIds[`${key}/${mode}`] ?? + (instrumentLayoutIds(instrument, mode).includes(this.selectedLayoutIds[key]) ? this.selectedLayoutIds[key] : undefined); if (selected) return layouts.find(layout => layout.id === selected) ?? null; return layouts.find(layout => layout.id === game.defaultLayout || layout.name === game.defaultLayout) ?? layouts[0] ?? null; } @@ -50,7 +82,7 @@ class GameStore { const game = this.activeGame; const instrument = this.activeInstrument; return this.isInstrumentMissing || Boolean(game && instrument - && instrument.supportedLayouts?.length && this.selectedLayoutIds[`${game.id}/${instrument.id}`] && !this.activeLayout); + && instrumentLayoutIds(instrument, this.activeInputMode).length && !this.activeLayout); } get hasDeletedSelection() { @@ -259,9 +291,9 @@ class GameStore { this.applyGameStatuses(this.latestStatuses); } - getInstrumentLayouts(instrument: InstrumentConfig | null, game = this.activeGame) { - const supported = instrument?.supportedLayouts ?? []; - return (game?.layouts ?? []).filter(layout => layout.keys.length > 0 && supported.some(id => + getInstrumentLayouts(instrument: InstrumentConfig | null, game = this.activeGame, mode: InstrumentInputMode | 'all' = this.getInputMode(game, instrument)) { + const supported = instrumentLayoutIds(instrument, mode); + return (game?.layouts ?? []).filter(layout => (layout.keys.length > 0 || layout.chordKeys?.length || layout.chordWheel?.positions.length || layout.fretboard?.stringKeys.length) && supported.some(id => id.toLowerCase() === layout.id.toLowerCase() || id.toLowerCase() === layout.name.toLowerCase())); } @@ -280,19 +312,41 @@ class GameStore { await this.refreshConfigs(); } + // Apply selections in order so an older clear cannot overwrite a newer mapping. + private applyMapping(layout: string, pairs: [number, string][], paths?: string[]) { + this.mappingReady = this.mappingReady.then(async () => { + try { + const applied = await api.games.setGameInstrumentMapping(layout, pairs, paths); + return applied && layout !== ''; + } catch (error) { + console.error('[GameState] Failed to apply instrument mapping:', error); + return false; + } + }); + return this.mappingReady; + } + + async hasPlaybackMapping(): Promise { + let pending: Promise; + let ready: boolean; + do { + pending = this.mappingReady; + ready = await pending; + } while (pending !== this.mappingReady); + return ready; + } + syncActiveInstrumentMapping(instrumentId?: string, layoutId?: string) { if (!this.activeGame || this.activeGame.isMissing) { this.publishSettingsContext(); - void api.games.setGameInstrumentMapping('', []).catch(console.error); - return; + return this.applyMapping('', []); } const explicitInstrument = this.activeGame.instruments?.find(i => i.id === instrumentId); if (explicitInstrument) this.selectedInstrumentIds[this.activeGame.id] = explicitInstrument.id; const inst = this.activeInstrument; if (!inst) { this.publishSettingsContext(); - void api.games.setGameInstrumentMapping('', []).catch(console.error); - return; + return this.applyMapping('', []); } if (explicitInstrument || this.selectedInstrumentIds[this.activeGame.id] !== inst.id) { this.selectedInstrumentIds[this.activeGame.id] = inst.id; @@ -300,24 +354,32 @@ class GameStore { } this.publishSettingsContext(); - const layouts = this.getInstrumentLayouts(inst); + const layouts = this.getInstrumentLayouts(inst, this.activeGame, 'all'); const selectionKey = `${this.activeGame.id}/${inst.id}`; - const previousLayoutId = this.selectedLayoutIds[selectionKey]; - if (!inst.supportedLayouts?.length) delete this.selectedLayoutIds[selectionKey]; + if (!instrumentLayoutIds(inst, 'all').length) delete this.selectedLayoutIds[selectionKey]; const explicitLayout = layouts.find(l => l.id === layoutId || l.name === layoutId); - if (explicitLayout) this.selectedLayoutIds[selectionKey] = explicitLayout.id; + if (explicitLayout) { + const mode = ([this.activeInputMode, 'keyboard', 'chords', 'frets'] as const) + .find(mode => this.getInstrumentLayouts(inst, this.activeGame, mode).includes(explicitLayout))!; + this.selectedLayoutIds[`${selectionKey}/mode`] = mode; + this.selectedLayoutIds[`${selectionKey}/${mode}`] = explicitLayout.id; + this.selectedLayoutIds[selectionKey] = explicitLayout.id; + } const targetLayout = this.activeLayout; - if (targetLayout) this.selectedLayoutIds[selectionKey] = targetLayout.id; - if (explicitLayout && this.selectedLayoutIds[selectionKey] !== previousLayoutId) { + if (targetLayout) { + this.selectedLayoutIds[selectionKey] = targetLayout.id; + this.selectedLayoutIds[`${selectionKey}/${this.activeInputMode}`] = targetLayout.id; + } + if (explicitLayout) { void api.settings.updateSettings({ selectedLayoutIds: { ...this.selectedLayoutIds } }).catch(console.error); } const keyPairs = instrumentKeyPairs(inst, targetLayout); - const effectiveLayoutName = keyPairs.length ? targetLayout!.id : ''; + const effectiveLayoutName = keyPairs.length || targetLayout?.chordWheel?.positions.length || targetLayout?.fretboard?.stringKeys.length || targetLayout?.chordKeys?.length ? targetLayout!.id : ''; const configPaths = [this.activeGame.filePath, inst.filePath, targetLayout?.filePath] .filter((path): path is string => Boolean(path)); - api.games.setGameInstrumentMapping(effectiveLayoutName, keyPairs, configPaths.length ? configPaths : undefined).catch(console.error); + return this.applyMapping(effectiveLayoutName, keyPairs, configPaths.length ? configPaths : undefined); } } diff --git a/src/renderer/lib/state/playbackStore.svelte.ts b/src/renderer/lib/state/playbackStore.svelte.ts index 83570979..12d2df0a 100644 --- a/src/renderer/lib/state/playbackStore.svelte.ts +++ b/src/renderer/lib/state/playbackStore.svelte.ts @@ -36,7 +36,6 @@ class PlaybackStore { tapThresholdMs = $state(DEFAULT_APP_SETTINGS.defaultTapThresholdMs); mergeNotes = $state(DEFAULT_APP_SETTINGS.defaultMergeNotes); mergeToleranceMs = $state(DEFAULT_APP_SETTINGS.defaultMergeToleranceMs); - autoChord = $state(DEFAULT_APP_SETTINGS.defaultAutoChord); chordDetectionMilliseconds = $state(DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds); enableKeyChangeMarkers = $state(DEFAULT_APP_SETTINGS.defaultEnableKeyChangeMarkers); isShuffled = $state(DEFAULT_UI_PREFERENCES.playback.isShuffled); @@ -443,6 +442,7 @@ class PlaybackStore { }); }); await this.restoreSession(preferences); + if (!await gameStore.hasPlaybackMapping()) this.notifyMissingLayout(); // Subscribe to process monitor updates for mid-playback focus loss or process exit gameStore.onGameStatusChange((activeGame) => { @@ -481,7 +481,6 @@ class PlaybackStore { this.tapThresholdMs = settingsStore.settings.defaultTapThresholdMs; this.mergeNotes = settingsStore.settings.defaultMergeNotes ?? DEFAULT_APP_SETTINGS.defaultMergeNotes; this.mergeToleranceMs = settingsStore.settings.defaultMergeToleranceMs ?? DEFAULT_APP_SETTINGS.defaultMergeToleranceMs; - this.autoChord = settingsStore.settings.defaultAutoChord ?? DEFAULT_APP_SETTINGS.defaultAutoChord; this.chordDetectionMilliseconds = settingsStore.settings.defaultChordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds; } this.currentTimeSeconds = restoredSong ? Math.min(saved.positionSeconds, this.durationSeconds) : 0; @@ -609,7 +608,6 @@ class PlaybackStore { mergeMilliseconds: this.mergeToleranceMs, holdNotes: this.holdNotes, tapThresholdMs: this.tapThresholdMs, - autoChord: this.autoChord, chordDetectionMilliseconds: this.chordDetectionMilliseconds, enableKeyChangeMarkers: this.enableKeyChangeMarkers, }; @@ -679,7 +677,6 @@ class PlaybackStore { } this.tapThresholdMs = song.tapThresholdMs ?? DEFAULT_APP_SETTINGS.defaultTapThresholdMs; void this.syncNoteTiming(); - this.autoChord = song.autoChord ?? DEFAULT_APP_SETTINGS.defaultAutoChord; this.chordDetectionMilliseconds = song.chordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds; // A preview selection must not reprocess the previously loaded native song. // Play reapplies these settings after the selected file has loaded. @@ -793,7 +790,7 @@ class PlaybackStore { // Controls and Edit can update a preview before its file replaces the engine song. if (isTauri && (!this.activeSong || this._currentLoadedPath !== this.activeSong.filePath)) return Promise.resolve(true); return api.playback.setNoteProcessing(this.mergeNotes, this.mergeToleranceMs, - this.autoChord, this.chordDetectionMilliseconds) + this.chordDetectionMilliseconds) .catch(error => notificationCenter.error('Unable to update note processing', String(error))); } @@ -805,15 +802,6 @@ class PlaybackStore { this.scheduleAutoSaveSongSettings(); } - setAutoChord(val: boolean) { - this.autoChord = val; - if (this.activeSong) { - this.activeSong.autoChord = val; - } - void this.syncNoteProcessing(); - this.scheduleAutoSaveSongSettings(); - } - setChordDetectionMilliseconds(value: number) { if (!Number.isFinite(value)) return; this.chordDetectionMilliseconds = Math.max(0, Math.min(500, Math.round(value))); @@ -1163,15 +1151,32 @@ class PlaybackStore { await this.play(songs[0]); } - async play(song?: MidiFile) { - if (this.isChangingSongContext) return; + private notifyMissingLayout() { + notificationCenter.error(t('player.playbackUnavailable'), t('player.chooseValidLayout')); + } + + private async canStartPlayback(request: number) { + let mappingReady: boolean; + do { + if (this.isChangingSongContext) await this.contextRefresh; + mappingReady = await gameStore.hasPlaybackMapping(); + if (request !== this.playRequestRevision) return false; + } while (this.isChangingSongContext); + if (!mappingReady) this.notifyMissingLayout(); + return mappingReady; + } + + async play(song?: MidiFile): Promise { const playRequest = ++this.playRequestRevision; - if (gameStore.hasDeletedSelection) { - notificationCenter.warning('Playback unavailable', gameStore.layoutDeletionTooltip); - return; + const originalContext = this.contextRevision; + const wasChangingContext = this.isChangingSongContext; + if (!await this.canStartPlayback(playRequest)) return false; + if (song && (wasChangingContext || originalContext !== this.contextRevision)) { + const requestedId = song.id; + song = libraryStore.songs.find(entry => entry.id === requestedId) ?? song; } const targetSong = song || this.activeSong || this.playbackQueue[0]; - if (!targetSong) return; + if (!targetSong) return false; this.cancelSongFinish(); // Check game running state if not in listen mode (matching WPF StartPlayback / HandleGameNotRunning) @@ -1190,13 +1195,14 @@ class PlaybackStore { 'Game not running', `${gameName} is not running.` ); - return; + return false; } } else { await gameStore.focusActiveGame(); } } + if (playRequest !== this.playRequestRevision) return false; const isNewSong = !this.activeSong || this.activeSong.id !== targetSong.id; const isPathLoaded = this._currentLoadedPath === targetSong.filePath; @@ -1233,31 +1239,28 @@ class PlaybackStore { } } catch (e) { notificationCenter.error('Unable to load song', String(e)); - return; + return false; } } } if (song && !isNewSong && isPathLoaded) await this.seek(0); - // A pause/stop during a load must not restart playback after the load finishes. - if (!settingsStore.isWindows && playRequest !== this.playRequestRevision) return; - if (settingsStore.isWindows) { - this.status = 'Playing'; - await api.playback.play(targetSong.id); - return; - } + // The selection or transport request can change while a MIDI file is loading. + if (!await this.canStartPlayback(playRequest)) return false; if (!this.isListenMode && gameStore.activeGame?.requiresManualFocus) { notificationCenter.info('Switch to your game', 'Allow keyboard access if prompted, then switch to the game within 30 seconds. Playback starts after AMP loses focus.'); } const previousStatus = this.status; this.status = 'Playing'; try { - await api.playback.play(targetSong.id); + if (!await api.playback.play(targetSong.id)) throw new Error(t('player.chooseValidLayout')); + return playRequest === this.playRequestRevision; } catch (error) { - if (playRequest !== this.playRequestRevision) return; + if (playRequest !== this.playRequestRevision) return false; if (this.status === 'Playing') this.status = previousStatus; if (!String(error).includes('cancelled')) notificationCenter.error('Unable to start playback', String(error)); + return false; } } @@ -1534,7 +1537,6 @@ class PlaybackStore { await this.syncNoteTiming(); this.mergeNotes = song.mergeNotes ?? DEFAULT_APP_SETTINGS.defaultMergeNotes; this.mergeToleranceMs = song.mergeToleranceMs ?? DEFAULT_APP_SETTINGS.defaultMergeToleranceMs; - this.autoChord = song.autoChord ?? DEFAULT_APP_SETTINGS.defaultAutoChord; this.chordDetectionMilliseconds = song.chordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds; await this.syncNoteProcessing(); this.enableKeyChangeMarkers = song.enableKeyChangeMarkers ?? DEFAULT_APP_SETTINGS.defaultEnableKeyChangeMarkers; @@ -1618,14 +1620,14 @@ class PlaybackStore { } } - this.activeQueueIndex = nextIndex; - const nextSong = currentList[this.activeQueueIndex]; + const nextSong = currentList[nextIndex]; if (nextSong) { - if (this.activeSong && this.activeSong.id !== nextSong.id) { - this.historyStack.push(this.activeSong); + const previous = this.activeSong; + const started = await this.play(nextSong); + if (started && previous && previous.id !== nextSong.id) { + this.historyStack.push(previous); if (this.historyStack.length > 50) this.historyStack.shift(); } - await this.play(nextSong); } } @@ -1636,13 +1638,8 @@ class PlaybackStore { } if (this.historyStack.length > 0) { - const prevSong = this.historyStack.pop()!; - const currentList = this.playbackQueue; - const foundIdx = currentList.findIndex(s => s.id === prevSong.id); - if (foundIdx !== -1) { - this.activeQueueIndex = foundIdx; - } - await this.play(prevSong); + const prevSong = this.historyStack[this.historyStack.length - 1]; + if (await this.play(prevSong)) this.historyStack.pop(); return; } @@ -1654,8 +1651,7 @@ class PlaybackStore { prevIndex = this.loopMode === 'all' ? currentList.length - 1 : 0; } - this.activeQueueIndex = prevIndex; - const prevSong = currentList[this.activeQueueIndex]; + const prevSong = currentList[prevIndex]; if (prevSong) { await this.play(prevSong); } diff --git a/src/renderer/lib/state/scheduledPlaybackStore.svelte.ts b/src/renderer/lib/state/scheduledPlaybackStore.svelte.ts index 61bb2c5c..9e372bba 100644 --- a/src/renderer/lib/state/scheduledPlaybackStore.svelte.ts +++ b/src/renderer/lib/state/scheduledPlaybackStore.svelte.ts @@ -8,7 +8,7 @@ export interface ScheduledPlaybackRuntime { now: () => number; isPlaying: () => boolean; hasSong: () => boolean; - play: () => Promise; + play: () => Promise; pause: () => Promise; interval: (callback: () => void) => ReturnType; clearInterval: (id: ReturnType) => void; diff --git a/src/renderer/lib/state/settingsStore.svelte.ts b/src/renderer/lib/state/settingsStore.svelte.ts index 8abfab35..8cb98c13 100644 --- a/src/renderer/lib/state/settingsStore.svelte.ts +++ b/src/renderer/lib/state/settingsStore.svelte.ts @@ -135,7 +135,6 @@ class SettingsStore { defaultTapThresholdMs: this.settings.defaultTapThresholdMs ?? DEFAULT_APP_SETTINGS.defaultTapThresholdMs, defaultMergeNotes: this.settings.defaultMergeNotes ?? DEFAULT_APP_SETTINGS.defaultMergeNotes, defaultMergeToleranceMs: this.settings.defaultMergeToleranceMs ?? DEFAULT_APP_SETTINGS.defaultMergeToleranceMs, - defaultAutoChord: this.settings.defaultAutoChord ?? DEFAULT_APP_SETTINGS.defaultAutoChord, defaultChordDetectionMilliseconds: this.settings.defaultChordDetectionMilliseconds ?? DEFAULT_APP_SETTINGS.defaultChordDetectionMilliseconds, defaultEnableKeyChangeMarkers: this.settings.defaultEnableKeyChangeMarkers ?? DEFAULT_APP_SETTINGS.defaultEnableKeyChangeMarkers, }, applyToExisting).then(result => { diff --git a/src/renderer/lib/utils/configUpdateReview.ts b/src/renderer/lib/utils/configUpdateReview.ts new file mode 100644 index 00000000..380085a8 --- /dev/null +++ b/src/renderer/lib/utils/configUpdateReview.ts @@ -0,0 +1,65 @@ +import type { DefaultConfigConflict, DefaultConfigUpdates, DuplicateConfig } from '../../../shared/types/games.js'; + +function canonical(value: unknown): string | undefined { + return JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) + ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item); +} + +export function formatConfigJson(source: string): string { + try { return JSON.stringify(JSON.parse(source), null, 2); } + catch { return source; } +} + +export function changedConfigFields(current: string, bundled: string): string[] { + try { + const before = JSON.parse(current); + const after = JSON.parse(bundled); + if (!before || !after || typeof before !== 'object' || typeof after !== 'object') return []; + return [...new Set([...Object.keys(before), ...Object.keys(after)])] + .filter(key => canonical(before[key]) !== canonical(after[key])).sort(); + } catch { return []; } +} +export interface ConfigReviewItem extends DefaultConfigConflict { duplicate?: DuplicateConfig } + +function parseRecord(source: string): Record | null { + try { + const parsed: unknown = JSON.parse(source); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? parsed as Record + : null; + } catch { + return null; + } +} + +function readText(record: Record | null, key: string): string | null { + const value = record?.[key]; + return typeof value === 'string' && value.length > 0 ? value : null; +} + +export function configReviewHeading( + item: Pick, +): string { + const before = parseRecord(item.currentJson); + const after = parseRecord(item.bundledJson); + const beforeName = readText(before, 'name') ?? readText(before, 'displayName'); + const afterName = readText(after, 'name') ?? readText(after, 'displayName'); + const beforeId = readText(before, 'id'); + const afterId = readText(after, 'id'); + const fileName = item.path.split('/').at(-1) || item.path; + + if (beforeName && beforeName === afterName) return beforeName; + const sharedId = (beforeId && afterId && beforeId === afterId ? afterId : null) ?? item.duplicate?.configId ?? null; + if (sharedId) return sharedId; + return fileName; +} + +export function configReviewItems(report: DefaultConfigUpdates | null): ConfigReviewItem[] { + if (!report) return []; + return [...report.conflicts, ...(report.duplicates ?? []).map(duplicate => ({ + id: duplicate.id, path: duplicate.keep.path, kind: duplicate.kind, name: duplicate.configId, + currentJson: duplicate.olderFiles[0].json, bundledJson: duplicate.keep.json, + token: duplicate.token, duplicate, + }))]; +} + diff --git a/src/renderer/lib/utils/configurationReviewFade.ts b/src/renderer/lib/utils/configurationReviewFade.ts new file mode 100644 index 00000000..6751d311 --- /dev/null +++ b/src/renderer/lib/utils/configurationReviewFade.ts @@ -0,0 +1,25 @@ +/** Keep both surfaces mounted until the fade finishes so the loader never flashes. */ +export async function fadeConfigurationSurface( + outgoing: HTMLElement | null, + incoming: HTMLElement, + duration: number, +): Promise { + incoming.inert = true; + incoming.style.opacity = '0'; + incoming.style.removeProperty('display'); + if (outgoing) outgoing.inert = true; + const animations: Animation[] = []; + try { + if (duration > 0 && typeof incoming.animate === 'function') { + const options: KeyframeAnimationOptions = { duration, easing: 'ease-in-out', fill: 'both' }; + animations.push(incoming.animate([{ opacity: 0 }, { opacity: 1 }], options)); + if (outgoing) animations.push(outgoing.animate([{ opacity: 1 }, { opacity: 0 }], options)); + await Promise.allSettled(animations.map(animation => animation.finished)); + } + } finally { + incoming.style.opacity = '1'; + incoming.inert = false; + if (outgoing) outgoing.style.display = 'none'; + animations.forEach(animation => animation.cancel()); + } +} diff --git a/src/renderer/lib/utils/guitarLayout.ts b/src/renderer/lib/utils/guitarLayout.ts new file mode 100644 index 00000000..c0d6eab8 --- /dev/null +++ b/src/renderer/lib/utils/guitarLayout.ts @@ -0,0 +1,31 @@ +import type { InstrumentConfig } from '../../../shared/types/games'; + +export interface GuitarPosition { string: number; fret: number; pitch: number } + +/** The game's fret selector is shared by all strings; preserve exact pitches. */ +export function guitarVoicing(instrument: InstrumentConfig | null, pitches: Iterable): GuitarPosition[] { + const guitar = instrument?.guitar; + const notes = [...new Set(pitches)].sort((a, b) => a - b); + if (!guitar || !notes.length || notes.length > guitar.tuning.length) return []; + for (let fret = 0; fret <= guitar.fretCount; fret++) { + const used = new Set(); + const positions: GuitarPosition[] = []; + for (const pitch of notes) { + const string = guitar.tuning.findIndex((open, index) => !used.has(index) && open + fret === pitch); + if (string < 0) break; + used.add(string); + positions.push({ string, fret, pitch }); + } + if (positions.length === notes.length) return positions; + } + return []; +} + +export function guitarChord(instrument: InstrumentConfig | null, pitches: Iterable): string | null { + const notes = [...pitches].sort((a, b) => a - b); + if (!notes.length) return null; + const mask = notes.reduce((value, pitch) => value | (1 << (pitch % 12)), 0); + return [...(instrument?.chords ?? [])].sort((a, b) => Number(b.bassPitchClass !== undefined) - Number(a.bassPitchClass !== undefined)) + .find(chord => chord.pitchClasses.reduce((value, pitch) => value | (1 << pitch), 0) === mask + && (chord.bassPitchClass === undefined || chord.bassPitchClass === notes[0] % 12))?.name ?? null; +} diff --git a/src/renderer/lib/utils/jsonDiff.ts b/src/renderer/lib/utils/jsonDiff.ts new file mode 100644 index 00000000..9171bc6c --- /dev/null +++ b/src/renderer/lib/utils/jsonDiff.ts @@ -0,0 +1,232 @@ +export interface DiffPart { + text: string; + changed: boolean; +} + +export interface DiffLine { + text: string; + lineNumber: number; + parts: DiffPart[]; +} + +export interface JsonDiffRow { + kind: 'equal' | 'added' | 'removed' | 'modified'; + left: DiffLine | null; + right: DiffLine | null; +} + +export interface JsonDiffResult { + rows: JsonDiffRow[]; + /** Start row of each contiguous group of changed lines. */ + changeStarts: number[]; + added: number; + removed: number; + modified: number; + invalidLeft: boolean; + invalidRight: boolean; +} + +interface SourceLines { + lines: string[]; + invalid: boolean; + requiresRaw: boolean; +} + +type Edit = { kind: 'equal' | 'added' | 'removed'; text: string }; + +// The full dynamic-programming table never exceeds four megabytes. Larger +// comparisons use a bounded search rather than quadratic memory or CPU work. +const MAX_LCS_CELLS = 1_000_000; +const LOOKAHEAD = 48; + +function hasUnsafeNumbers(source: string): boolean { + const numberToken = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y; + for (let index = 0; index < source.length;) { + if (source[index] === '"') { + // JSON keys and string contents are text even if they look like numbers. + index++; + while (index < source.length) { + if (source[index] === '\\') index += 2; + else if (source[index++] === '"') break; + } + } else if (source[index] === '-' || /[0-9]/.test(source[index])) { + numberToken.lastIndex = index; + const token = numberToken.exec(source)?.[0]; + if (!token) { index++; continue; } + const value = Number(token); + const significant = token.split(/[eE]/)[0].replace(/[-.]/g, '').replace(/^0+|0+$/g, ''); + // JSON.parse/stringify can silently round distinct lexemes to the same + // number, or turn overflowing exponents into null. Fifteen significant + // decimal digits are a conservative bound for canonical formatting. + if (!Number.isFinite(value) || Object.is(value, -0) || significant.length > 15 + || (Number.isInteger(value) && !Number.isSafeInteger(value)) + || (value === 0 && significant.length > 0) + || (value !== 0 && Math.abs(value) < 2.2250738585072014e-308)) return true; + index = numberToken.lastIndex; + } else index++; + } + return false; +} + +function sourceLines(source: string): SourceLines { + let value: unknown; + try { + value = JSON.parse(source); + } catch { + return { lines: source.split('\n'), invalid: true, requiresRaw: false }; + } + if (hasUnsafeNumbers(source)) return { lines: source.split('\n'), invalid: false, requiresRaw: true }; + try { + const canonical = JSON.stringify(value, (_key, item: unknown) => { + if (!item || typeof item !== 'object' || Array.isArray(item)) return item; + const object = item as Record; + return Object.fromEntries(Object.keys(object).sort().map(key => [key, object[key]])); + }, 2); + return { lines: canonical.split('\n'), invalid: false, requiresRaw: false }; + } catch { + // Valid deeply nested JSON may exceed stringify's recursion limit. Keep it + // intact rather than incorrectly reporting a syntax error. + return { lines: source.split('\n'), invalid: false, requiresRaw: true }; + } +} + +function boundedEdits(left: string[], right: string[]): Edit[] { + const edits: Edit[] = []; + let i = 0; + let j = 0; + while (i < left.length && j < right.length) { + if (left[i] === right[j]) { + edits.push({ kind: 'equal', text: left[i++] }); + j++; + continue; + } + let addedDistance = 0; + let removedDistance = 0; + for (let distance = 1; distance <= LOOKAHEAD; distance++) { + if (!addedDistance && j + distance < right.length && left[i] === right[j + distance]) addedDistance = distance; + if (!removedDistance && i + distance < left.length && left[i + distance] === right[j]) removedDistance = distance; + if (addedDistance || removedDistance) break; + } + if (addedDistance && (!removedDistance || addedDistance < removedDistance)) { + for (let count = 0; count < addedDistance; count++) edits.push({ kind: 'added', text: right[j++] }); + } else if (removedDistance) { + for (let count = 0; count < removedDistance; count++) edits.push({ kind: 'removed', text: left[i++] }); + } else { + edits.push({ kind: 'removed', text: left[i++] }, { kind: 'added', text: right[j++] }); + } + } + while (i < left.length) edits.push({ kind: 'removed', text: left[i++] }); + while (j < right.length) edits.push({ kind: 'added', text: right[j++] }); + return edits; +} + +function middleEdits(left: string[], right: string[]): Edit[] { + const width = right.length + 1; + if ((left.length + 1) * width > MAX_LCS_CELLS) return boundedEdits(left, right); + const lengths = new Uint32Array((left.length + 1) * width); + for (let i = left.length - 1; i >= 0; i--) { + for (let j = right.length - 1; j >= 0; j--) { + lengths[i * width + j] = left[i] === right[j] + ? lengths[(i + 1) * width + j + 1] + 1 + : Math.max(lengths[(i + 1) * width + j], lengths[i * width + j + 1]); + } + } + const edits: Edit[] = []; + let i = 0; + let j = 0; + while (i < left.length && j < right.length) { + if (left[i] === right[j]) { + edits.push({ kind: 'equal', text: left[i++] }); + j++; + } else if (lengths[(i + 1) * width + j] >= lengths[i * width + j + 1]) { + edits.push({ kind: 'removed', text: left[i++] }); + } else { + edits.push({ kind: 'added', text: right[j++] }); + } + } + while (i < left.length) edits.push({ kind: 'removed', text: left[i++] }); + while (j < right.length) edits.push({ kind: 'added', text: right[j++] }); + return edits; +} + +function lineEdits(left: string[], right: string[]): Edit[] { + let prefix = 0; + while (prefix < left.length && prefix < right.length && left[prefix] === right[prefix]) prefix++; + let suffix = 0; + while (suffix < left.length - prefix && suffix < right.length - prefix + && left[left.length - 1 - suffix] === right[right.length - 1 - suffix]) suffix++; + return [ + ...left.slice(0, prefix).map(text => ({ kind: 'equal' as const, text })), + ...middleEdits(left.slice(prefix, left.length - suffix), right.slice(prefix, right.length - suffix)), + ...left.slice(left.length - suffix).map(text => ({ kind: 'equal' as const, text })), + ]; +} + +function changedParts(left: string, right: string): [DiffPart[], DiffPart[]] { + // Compare code points so highlighting never splits a surrogate pair. + const before = Array.from(left); + const after = Array.from(right); + let prefix = 0; + while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++; + let suffix = 0; + while (suffix < before.length - prefix && suffix < after.length - prefix + && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) suffix++; + const parts = (characters: string[]): DiffPart[] => [ + { text: characters.slice(0, prefix).join(''), changed: false }, + { text: characters.slice(prefix, characters.length - suffix).join(''), changed: true }, + { text: suffix ? characters.slice(-suffix).join('') : '', changed: false }, + ].filter(part => part.text.length > 0); + return [parts(before), parts(after)]; +} + +/** Read-only aligned JSON diff; source text is always rendered as text, never HTML. */ +export function createJsonDiff(leftSource: string, rightSource: string): JsonDiffResult { + const leftSourceLines = sourceLines(leftSource); + const rightSourceLines = sourceLines(rightSource); + // Compare both originals if either cannot be canonicalized faithfully. Mixing + // raw and formatted text would otherwise invent unrelated formatting edits. + const raw = leftSourceLines.requiresRaw || rightSourceLines.requiresRaw; + const edits = lineEdits(raw ? leftSource.split('\n') : leftSourceLines.lines, + raw ? rightSource.split('\n') : rightSourceLines.lines); + const rows: JsonDiffRow[] = []; + let leftNumber = 1; + let rightNumber = 1; + let removed: string[] = []; + let added: string[] = []; + const line = (text: string, lineNumber: number, changed: boolean): DiffLine => ({ text, lineNumber, parts: [{ text, changed }] }); + function flushChanges() { + for (let index = 0; index < Math.max(removed.length, added.length); index++) { + const before = removed[index]; + const after = added[index]; + const left = before === undefined ? null : line(before, leftNumber++, true); + const right = after === undefined ? null : line(after, rightNumber++, true); + if (left && right) [left.parts, right.parts] = changedParts(left.text, right.text); + rows.push({ kind: left && right ? 'modified' : left ? 'removed' : 'added', left, right }); + } + removed = []; + added = []; + } + for (const edit of edits) { + if (edit.kind === 'removed') removed.push(edit.text); + else if (edit.kind === 'added') added.push(edit.text); + else { + flushChanges(); + rows.push({ kind: 'equal', left: line(edit.text, leftNumber++, false), right: line(edit.text, rightNumber++, false) }); + } + } + flushChanges(); + const changeStarts: number[] = []; + let addedCount = 0; + let removedCount = 0; + let modifiedCount = 0; + rows.forEach((row, index) => { + if (row.kind !== 'equal' && (index === 0 || rows[index - 1].kind === 'equal')) changeStarts.push(index); + if (row.kind === 'added') addedCount++; + else if (row.kind === 'removed') removedCount++; + else if (row.kind === 'modified') modifiedCount++; + }); + return { + rows, changeStarts, added: addedCount, removed: removedCount, modified: modifiedCount, + invalidLeft: leftSourceLines.invalid, invalidRight: rightSourceLines.invalid, + }; +} diff --git a/src/renderer/lib/views/InstrumentView.svelte b/src/renderer/lib/views/InstrumentView.svelte index 252264bc..ba8b1425 100644 --- a/src/renderer/lib/views/InstrumentView.svelte +++ b/src/renderer/lib/views/InstrumentView.svelte @@ -18,17 +18,23 @@ import PedalIcon from '../components/Icons/PedalIcon.svelte'; import ChordIcon from '../components/Icons/ChordIcon.svelte'; import GradientSweep from '../components/Common/GradientSweep.svelte'; + import SlidingTabs from '../components/Common/SlidingTabs.svelte'; import { createFrameResizeObserver } from '../utils/frameResizeObserver'; import { tooltip } from '../actions/tooltip'; - import { persistScroll } from '../actions/persistScroll'; import GameIcon from '../components/Common/GameIcon.svelte'; import { toastOffset } from '../actions/toastOffset'; import { createDropdownState } from '../ui/dropdownState.svelte'; import { InstrumentInput, keyboardPitches } from '../utils/instrumentInput'; import { createPianoRows, createPianoSlots, hasInGameInstrumentLayout, pianoRange, type PianoSlot } from '../utils/instrumentKeyboard'; - import { instrumentKeyRows, instrumentLayoutStyle, instrumentNotes as getInstrumentNotes } from '../../../shared/utils/instrumentLayout'; + import { guitarNotes, instrumentChordMode, instrumentKeyRows, instrumentLayoutStyle, instrumentNotes as getInstrumentNotes } from '../../../shared/utils/instrumentLayout'; import InstrumentLayout from '../components/Instrument/InstrumentLayout.svelte'; + import GuitarLayout from '../components/Instrument/GuitarLayout.svelte'; + import ChordPadsLayout from '../components/Instrument/ChordPadsLayout.svelte'; + import type { InstrumentInputMode } from '../../../shared/types/games'; + import ChordWheelControls from '../components/Instrument/ChordWheelControls.svelte'; + let topBarWidth = $state(0); + const showTopLabels = $derived(topBarWidth >= 700); let bottomBarWidth = $state(0); const showBottomLabels = $derived(bottomBarWidth >= 700); @@ -50,9 +56,22 @@ let selectedInstrument = $derived( gameStore.activeGame?.instruments?.find(i => i.id === selectedInstrumentId) || null ); + const inputModes = $derived((['keyboard', 'chords', 'frets'] as InstrumentInputMode[]).filter(mode => + (mode === 'keyboard' ? selectedInstrument?.keyboardLayouts : mode === 'chords' ? selectedInstrument?.chordLayouts : selectedInstrument?.fretLayouts)?.length)); + const showInputModes = $derived(inputModes.length > 1); + let lastInputModes = $state([]); + let lastInputMode = $state('keyboard'); + $effect(() => { + if (showInputModes) { + lastInputModes = inputModes; + lastInputMode = gameStore.activeInputMode; + } + }); + const displayInputModes = $derived(showInputModes ? inputModes : lastInputModes); + const displayInputMode = $derived(showInputModes ? gameStore.activeInputMode : lastInputMode); let compactStage = $state(uiStore.instrumentCompactStage); - const initialWidth = typeof window !== 'undefined' ? Math.max(720, Math.min(1600, window.innerWidth - 88)) : 720; + const initialWidth = typeof window !== 'undefined' ? Math.max(720, Math.min(1600, window.innerWidth - 40)) : 720; const initialHeight = typeof window !== 'undefined' ? Math.max(300, window.innerHeight - 100) : 500; let pianoAvailableWidth = $state(initialWidth); let pianoAvailableHeight = $state(initialHeight); @@ -61,27 +80,24 @@ let gameSelected = $derived(uiStore.instrumentGameSelected); let pianoSelected = $derived(uiStore.instrumentPianoSelected); const hasInGameLayout = $derived(hasInGameInstrumentLayout(selectedInstrument)); - const showGame = $derived(hasInGameLayout && (compactStage ? selectedStage === 'game' : gameSelected)); - const showPiano = $derived(!hasInGameLayout || (compactStage ? selectedStage === 'piano' : pianoSelected)); + const usePreferredStage = $derived( + (compactStage && gameSelected && pianoSelected) || (!gameSelected && !pianoSelected) + ); + const showGame = $derived(hasInGameLayout && (usePreferredStage ? selectedStage === 'game' : gameSelected)); + const showPiano = $derived(!hasInGameLayout || (usePreferredStage ? selectedStage === 'piano' : pianoSelected)); function selectStage(view: 'game' | 'piano') { - uiStore.setInstrumentStage(view); - if (compactStage) return; - let nextGame = uiStore.instrumentGameSelected; - let nextPiano = uiStore.instrumentPianoSelected; - if (view === 'game') { - nextGame = !nextGame; - if (!nextGame) nextPiano = true; - } else { - nextPiano = !nextPiano; - if (!nextPiano) nextGame = true; - } - uiStore.setInstrumentToggles(nextGame, nextPiano); + const other = view === 'game' ? 'piano' : 'game'; + const next = { game: showGame, piano: showPiano }; + next[view] = compactStage || !next[view]; + next[other] = !compactStage && (next[other] || !next[view]); + uiStore.setInstrumentStage(next[view] ? view : other); + uiStore.setInstrumentToggles(next.game, next.piano); } function fitInstrumentStage( viewport: HTMLDivElement, - options: { game: boolean; piano: boolean; hasGame: boolean; maxWidth: number; duration: number }, + options: { stage: 'game' | 'piano'; gameSelected: boolean; pianoSelected: boolean; hasGame: boolean; duration: number }, ) { const content = viewport.querySelector('.inst-stage') as HTMLDivElement; const game = content.querySelector('.game-stage') as HTMLDivElement; @@ -89,98 +105,123 @@ const gameSlot = game.parentElement!; const pianoSlot = piano.parentElement!; const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)'); - // Width, occupied heights, gap, and available space share one eased timeline. - let current: number[] | null = null; - let target: number[] = []; + type StageReveal = [game: number, piano: number, gap: number]; + let availableWidth = 0; + let availableHeight = 0; + let stageWidth = 0; + let naturalGameHeight = 0; + let naturalPianoHeight = 0; + let current: StageReveal | null = null; + let target: StageReveal = [0, 0, 0]; let frame: number | null = null; - let isSettled = false; - let settleFrame: number | null = null; - - settleFrame = requestAnimationFrame(() => { - settleFrame = requestAnimationFrame(() => { - isSettled = true; - settleFrame = null; - }); - }); - function draw(values: number[]) { - current = values; - const [width, gameHeight, pianoHeight, gap, availableWidth, availableHeight, - naturalGameHeight, naturalPianoHeight] = values; + function draw(reveal: StageReveal) { + if (!current) content.style.visibility = 'visible'; + current = reveal; + const [gameReveal, pianoReveal, gapReveal] = reveal; + const gameHeight = gameReveal * naturalGameHeight; + const pianoHeight = pianoReveal * naturalPianoHeight; + const gap = gapReveal * 24; const height = Math.max(1, gameHeight + pianoHeight + gap); - const scale = Math.min(1, availableWidth / width, availableHeight / height); - content.style.width = `${width}px`; + const scale = Math.min(1, availableWidth / stageWidth, availableHeight / height); gameSlot.style.height = `${gameHeight}px`; pianoSlot.style.height = `${pianoHeight}px`; content.style.gap = `${gap}px`; content.style.transform = `scale(${scale})`; - // Keep hidden views beyond the viewport, rather than clipping them at their slots. - // The same eased occupied heights drive their travel and push the other view. + // The slots push the other view while the panels slide out through the stage mask. const travel = (availableHeight + 40) / Math.max(scale, 0.001); - const gameReveal = Math.min(1, gameHeight / Math.max(1, naturalGameHeight)); - const pianoReveal = Math.min(1, pianoHeight / Math.max(1, naturalPianoHeight)); - game.style.transform = `translateY(${-travel * (1 - gameReveal)}px)`; - piano.style.transform = `translateY(${travel * (1 - pianoReveal)}px)`; + game.style.visibility = gameReveal === 0 ? 'hidden' : ''; + piano.style.visibility = pianoReveal === 0 ? 'hidden' : ''; + game.style.transform = gameReveal > 0 && gameReveal < 1 + ? `translateY(${-travel * (1 - gameReveal)}px)` : ''; + piano.style.transform = pianoReveal > 0 && pianoReveal < 1 + ? `translateY(${travel * (1 - pianoReveal)}px)` : ''; } - function measure() { - const width = Math.max(0, viewport.clientWidth - 88); - const height = Math.max(0, viewport.clientHeight - 40); - const naturalWidth = Math.max(720, Math.min(options.maxWidth, width)); - // Use the visible width, since the stage itself may be scaled down. - pianoAvailableWidth = Math.min(naturalWidth, width); - pianoAvailableHeight = height; - pianoStageWidth = naturalWidth; - // Measure full inner views even while their occupied heights are zero. - const previousWidth = content.style.width; - content.style.width = `${naturalWidth}px`; - const naturalGameHeight = game.offsetHeight; - const naturalPianoHeight = piano.offsetHeight; - content.style.width = previousWidth; - const widthScale = Math.min(1, width / naturalWidth); - compactStage = options.hasGame && height < (naturalGameHeight + naturalPianoHeight + 24) * widthScale * 0.85; - uiStore.instrumentCompactStage = compactStage; - // Read the derived selection after updating the compact layout mode. - const next = [naturalWidth, showGame ? naturalGameHeight : 0, - showPiano ? naturalPianoHeight : 0, showGame && showPiano ? 24 : 0, width, height, - naturalGameHeight, naturalPianoHeight]; - const duration = (!isSettled || reducedMotion.matches) ? 0 : options.duration; - if (current && duration > 0 && next.every((value, index) => Math.abs(value - target[index]) < 0.01)) return; - target = next; + function stopAnimation() { if (frame !== null) cancelAnimationFrame(frame); frame = null; - if (!current || duration <= 0) { + } + + function fit() { + if (stageWidth === 0) { + stopAnimation(); + current = null; + return; + } + + pianoAvailableWidth = Math.min(stageWidth, availableWidth); + pianoAvailableHeight = availableHeight; + pianoStageWidth = stageWidth; + const widthScale = Math.min(1, availableWidth / stageWidth); + compactStage = options.hasGame && availableHeight < (naturalGameHeight + naturalPianoHeight + 24) * widthScale * 0.85; + uiStore.instrumentCompactStage = compactStage; + const next: StageReveal = [showGame ? 1 : 0, showPiano ? 1 : 0, showGame && showPiano ? 1 : 0]; + const duration = reducedMotion.matches ? 0 : options.duration; + const start = current; + if (!start || duration <= 0) { + stopAnimation(); + target = next; draw(next); return; } - // Reversals start at the currently rendered layout, including mid-resize. - const start = [...current]; + // Resize the current frame of the slide using the latest natural sizes. + draw(start); + if (next[0] === target[0] && next[1] === target[1]) return; + + stopAnimation(); + target = next; + const [startGame, startPiano, startGap] = start; const startedAt = performance.now(); function advance(now: number) { const progress = Math.min(1, Math.max(0, (now - startedAt) / duration)); + if (progress === 1) { + frame = null; + draw(next); + return; + } const eased = 1 - Math.pow(1 - progress, 3); - draw(start.map((value, index) => value + (next[index] - value) * eased)); - frame = progress < 1 ? requestAnimationFrame(advance) : null; + draw([ + startGame + (next[0] - startGame) * eased, + startPiano + (next[1] - startPiano) * eased, + startGap + (next[2] - startGap) * eased, + ]); + frame = requestAnimationFrame(advance); } frame = requestAnimationFrame(advance); } - const resize = createFrameResizeObserver(measure); + const resize = createFrameResizeObserver(entries => { + let changed = false; + for (const { target, contentRect: { width, height } } of entries) { + if (target === viewport && (width !== availableWidth || height !== availableHeight)) { + availableWidth = width; + availableHeight = height; + changed = true; + } else if (target === game && height !== naturalGameHeight) { + naturalGameHeight = height; + changed = true; + } else if (target === piano && (width !== stageWidth || height !== naturalPianoHeight)) { + stageWidth = width; + naturalPianoHeight = height; + changed = true; + } + } + if (changed) fit(); + }); resize.observe(viewport); resize.observe(game); resize.observe(piano); - reducedMotion.addEventListener('change', measure); - measure(); + reducedMotion.addEventListener('change', fit); return { update(next: typeof options) { options = next; - measure(); + fit(); }, destroy() { resize.disconnect(); - reducedMotion.removeEventListener('change', measure); - if (frame !== null) cancelAnimationFrame(frame); - if (settleFrame !== null) cancelAnimationFrame(settleFrame); + reducedMotion.removeEventListener('change', fit); + stopAnimation(); }, }; } @@ -236,14 +277,28 @@ selectedLayoutId = gameStore.activeLayout?.id ?? ''; }); - let supportsChords = $derived( - selectedInstrument ? selectedInstrument.supportsChords : false - ); + const chordMode = $derived(instrumentChordMode(selectedInstrument, gameStore.activeLayout)); + let supportsChords = $derived(chordMode !== null); + let modePending = $state(false); + async function selectInputMode(mode: InstrumentInputMode) { + if (modePending || playbackStore.isPlaying) return; + modePending = true; + try { await gameStore.setInputMode(mode); } + catch (error) { notificationCenter.error(t('common.error'), String(error)); } + finally { modePending = false; } + } + const wheelLayout = $derived(gameStore.activeLayout?.chordWheel ? gameStore.activeLayout : + gameStore.activeGame?.layouts.find(layout => layout.id === gameStore.activeLayout?.fretboard?.wheelLayout)); + const displayWheel = $derived(wheelLayout?.chordWheel ? { ...wheelLayout.chordWheel, + pageCount: gameStore.activeInputMode === 'frets' ? Math.ceil((selectedInstrument?.guitar?.fretCount ?? 24) / wheelLayout.chordWheel.positions.length) + 1 : wheelLayout.chordWheel.pageCount } : null); + const wheelItems = $derived(gameStore.activeInputMode === 'frets' ? [ + ...Array.from({ length: selectedInstrument?.guitar?.fretCount ?? 24 }, (_, index) => ({ name: String(index + 1), pitchClasses: [] })), + { name: t('instrument.guitarOpen'), pitchClasses: [] }, + ] : selectedInstrument?.chords ?? []); let supportsPedals = $derived( selectedInstrument ? selectedInstrument.supportsSustain : true ); - const chordsActive = $derived(supportsChords && playbackStore.autoChord); const pedalsActive = $derived(supportsPedals && playbackStore.pedals.enabled); // ========================================== @@ -340,7 +395,7 @@ const selectedGameLayout = $derived( gameStore.activeGame?.layouts?.find(layout => layout.id === selectedLayoutId) ?? null ); - const instrumentNotes = $derived(getInstrumentNotes(selectedInstrument)); + const instrumentNotes = $derived(gameStore.activeInputMode === 'frets' ? guitarNotes(selectedInstrument) : getInstrumentNotes(selectedInstrument)); const layoutStyle = $derived(instrumentLayoutStyle(selectedInstrument)); const mappedRows = $derived(instrumentKeyRows(selectedInstrument, selectedGameLayout)); const mappedKeys = $derived(mappedRows.flat().filter(key => key !== null)); @@ -416,6 +471,17 @@ +{#snippet topLabel(label: string)} + +{/snippet} + {#snippet bottomLabel(label: string)}