//! Draft and persistence for the menu's sound controls. use super::profile; use fparkan_assets::game_settings::GameSettings; use fparkan_vfs::DirectoryVfs; use std::{io, path::Path}; #[derive(Clone, Copy)] pub(super) enum Volume { Effects, Music, } #[derive(Clone, Copy)] struct SoundValues { effects: u8, music: u8, play_music: bool, } pub(super) struct SoundSettings { saved: SoundValues, draft: SoundValues, pub(super) status: &'static str, pub(super) drag: Option, } impl SoundSettings { pub(super) fn open(root: &Path) -> io::Result { let profile = GameSettings::load(&DirectoryVfs::new(root)).map_err(io::Error::other)?; let audio = profile.audio(); let percent = |gain: Option| (gain.unwrap_or(1.0) * 100.0).round() as u8; let values = SoundValues { effects: percent(audio.effects_gain), music: percent(audio.cd_gain), play_music: audio.play_cd, }; Ok(Self { saved: values, draft: values, status: "", drag: None, }) } pub(super) fn volume(&self, volume: Volume) -> u8 { match volume { Volume::Effects => self.draft.effects, Volume::Music => self.draft.music, } } pub(super) fn set_volume(&mut self, volume: Volume, value: u8) { match volume { Volume::Effects => self.draft.effects = value.min(100), Volume::Music => self.draft.music = value.min(100), } self.status = ""; } pub(super) fn music_enabled(&self) -> bool { self.draft.play_music } pub(super) fn toggle_music(&mut self) { self.draft.play_music = !self.draft.play_music; self.status = ""; } pub(super) fn apply(&mut self, root: &Path) -> io::Result<()> { let updates: Vec<_> = [ ( "SFX_VOLUME", i32::from(self.saved.effects), i32::from(self.draft.effects), ), ( "CD_VOLUME", i32::from(self.saved.music), i32::from(self.draft.music), ), ( "PLAY_CD_MUSIC", i32::from(self.saved.play_music), i32::from(self.draft.play_music), ), ] .into_iter() .filter_map(|(key, previous, next)| (previous != next).then_some((key, next))) .collect(); profile::save_integers(root, &updates)?; self.saved = self.draft; self.status = "Сохранено"; Ok(()) } }