diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 467d6de..1a49aa9 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -10,6 +10,7 @@ #![windows_subsystem = "windows"] mod art; +mod settings; use eframe::egui::{self, Color32, CornerRadius, Rect, RichText, Stroke}; use std::io::{BufRead, BufReader, Read}; @@ -44,8 +45,6 @@ struct Config { install_dir: String, sound: bool, skip_intro: bool, - fullscreen: bool, - scale: u32, verbose: bool, } @@ -57,8 +56,6 @@ impl Default for Config { install_dir: String::new(), sound: true, skip_intro: false, - fullscreen: true, - scale: 3, verbose: false, } } @@ -82,8 +79,6 @@ impl Config { "install_dir" => c.install_dir = v.to_string(), "sound" => c.sound = b, "skip_intro" => c.skip_intro = b, - "fullscreen" => c.fullscreen = b, - "scale" => c.scale = v.parse().unwrap_or(3).clamp(1, 8), "verbose" => c.verbose = b, _ => {} } @@ -98,14 +93,12 @@ impl Config { } let b = |x: bool| if x { "1" } else { "0" }; let text = format!( - "lang={}\ngame_path={}\ninstall_dir={}\nsound={}\nskip_intro={}\nfullscreen={}\nscale={}\nverbose={}\n", + "lang={}\ngame_path={}\ninstall_dir={}\nsound={}\nskip_intro={}\nverbose={}\n", if self.lang == Lang::En { "en" } else { "fr" }, self.game_path, self.install_dir, b(self.sound), b(self.skip_intro), - b(self.fullscreen), - self.scale, b(self.verbose) ); let _ = std::fs::write(f, text); @@ -501,6 +494,9 @@ struct App { root: Option, cfg: Config, saved: Config, + /// réglages du jeu (settings.ini, partagé avec le menu F12) + gs: settings::GameSettings, + gs_saved: settings::GameSettings, checks: Checks, busy: Busy, game_running: bool, @@ -539,6 +535,8 @@ impl App { let mut app = Self { root: find_root(), saved: cfg.clone(), + gs: settings::GameSettings::load(), + gs_saved: settings::GameSettings::load(), cfg, checks: Checks::default(), busy: Busy::No, @@ -700,11 +698,9 @@ impl App { .arg("--exe").arg(dir.join("TUCKER.EXE")) .arg("--hd").arg(&hd) .arg("--root").arg(&hd_root) - .arg("--saves").arg(&saves) - .arg("--echelle").arg(self.cfg.scale.to_string()); + .arg("--saves").arg(&saves); if self.cfg.sound { cmd.arg("--son"); } if self.cfg.skip_intro { cmd.arg("--sans-intro"); } - if self.cfg.fullscreen { cmd.arg("--plein"); } if self.cfg.verbose { cmd.arg("-v"); } cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped()); self.log.push(format!("> {:?}", cmd)); @@ -761,6 +757,9 @@ impl App { } Msg::GameExited(code) => { self.game_running = false; + // le joueur a pu changer ses réglages avec F12 : on relit le fichier + self.gs = settings::GameSettings::load(); + self.gs_saved = self.gs.clone(); self.last_exit = Some(code); if code != 0 { self.show_log = true; @@ -1050,15 +1049,48 @@ impl App { card(ui, |ui| { title(ui, tr("Prêt à jouer", "Ready to play")); ui.add_space(4.0); - ui.checkbox(&mut self.cfg.sound, tr("Son", "Sound")); - ui.checkbox(&mut self.cfg.fullscreen, tr("Plein écran", "Fullscreen")); - ui.checkbox(&mut self.cfg.skip_intro, tr("Passer l'intro", "Skip intro")); - ui.checkbox(&mut self.cfg.verbose, tr("Journal détaillé", "Verbose log")); + ui.horizontal_wrapped(|ui| { + ui.checkbox(&mut self.cfg.sound, tr("Son", "Sound")); + ui.checkbox(&mut self.cfg.skip_intro, tr("Passer l'intro", "Skip intro")); + ui.checkbox(&mut self.cfg.verbose, tr("Journal détaillé", "Verbose log")); + }); ui.add_space(4.0); - ui.label(tr("Taille de la fenêtre", "Window scale")); - ui.horizontal(|ui| { - ui.add(egui::Slider::new(&mut self.cfg.scale, 1..=8).suffix("×")); - ui.label(RichText::new(format!("{}×{}", 320 * self.cfg.scale, 240 * self.cfg.scale)).weak()); + // réglages partagés avec le jeu : figés pendant une partie (le menu F12 écrit le même fichier) + let running = self.game_running; + let gs = &mut self.gs; + ui.add_enabled_ui(!running, |ui| { + egui::CollapsingHeader::new(RichText::new(tr("Affichage", "Display")).strong()) + .default_open(true) + .show(ui, |ui| { + ui.checkbox(&mut gs.fullscreen, tr("Plein écran", "Fullscreen")); + ui.horizontal(|ui| { + ui.label(tr("Filtre", "Filter")); + let names = if en { ["Sharp", "Smooth", "xBR", "CRT"] } else { ["Net", "Lissé", "xBR", "CRT"] }; + for (i, n) in names.iter().enumerate() { + ui.selectable_value(&mut gs.filter, i, *n); + } + }); + ui.checkbox(&mut gs.aspect_43, tr("Format 4:3 (comme un écran VGA)", "4:3 aspect (like a VGA screen)")); + ui.checkbox(&mut gs.vsync, tr("Synchronisation verticale", "Vertical sync")); + ui.horizontal(|ui| { + ui.label(tr("Fenêtre", "Window")); + ui.add(egui::Slider::new(&mut gs.window_scale, 1..=16).suffix("×")); + let h = if gs.aspect_43 { 240 } else { 200 }; + ui.label(RichText::new(format!("{}×{}", 320 * gs.window_scale, h * gs.window_scale)).weak()); + }); + }); + egui::CollapsingHeader::new(RichText::new(tr("Volumes", "Volume")).strong()) + .default_open(false) + .show(ui, |ui| { + let labels = if en { ["Master", "Music", "Voices", "Effects"] } else { ["Général", "Musique", "Voix", "Bruitages"] }; + egui::Grid::new("volumes").num_columns(2).show(ui, |ui| { + for (i, l) in labels.iter().enumerate() { + ui.label(*l); + ui.add(egui::Slider::new(&mut gs.vol[i], 0..=100).suffix(" %")); + ui.end_row(); + } + }); + }); }); ui.add_space(12.0); let can_play = !busy && !self.game_running && c.built && c.game_dir.is_some(); @@ -1072,7 +1104,7 @@ impl App { } else if let Some(code) = self.last_exit.filter(|&c| c != 0) { ui.label(RichText::new(format!("{} {code}", tr("Le jeu s'est arrêté avec le code", "The game stopped with code"))).color(BAD)); } else { - ui.label(RichText::new(tr("F11 ou Alt+Entrée : plein écran en jeu.", "F11 or Alt+Enter: toggle fullscreen in game.")).weak()); + ui.label(RichText::new(tr("En jeu : F12 réglages · F11 plein écran.", "In game: F12 settings · F11 fullscreen.")).weak()); } }); } @@ -1123,6 +1155,12 @@ impl eframe::App for App { }); }); + if self.gs != self.gs_saved && !self.game_running { + if let Err(e) = self.gs.save() { + self.log.push(format!("!! settings.ini : {e}")); + } + self.gs_saved = self.gs.clone(); + } if self.cfg != self.saved { self.cfg.save(); self.saved = self.cfg.clone(); diff --git a/launcher/src/settings.rs b/launcher/src/settings.rs new file mode 100644 index 0000000..805f4cb --- /dev/null +++ b/launcher/src/settings.rs @@ -0,0 +1,152 @@ +//! settings.ini, partagé avec le jeu (menu F12) : voir docs/SETTINGS.md. +//! Le launcher ne réécrit que les valeurs de ses clés : ordre, commentaires et clés inconnues restent intacts. + +use std::path::PathBuf; + +pub const FILTERS: [&str; 4] = ["nearest", "smooth", "xbr", "crt"]; +pub const VOLUMES: [&str; 4] = ["master_volume", "music_volume", "voice_volume", "sfx_volume"]; + +#[derive(Clone, PartialEq)] +pub struct GameSettings { + pub fullscreen: bool, + pub window_scale: u32, + pub filter: usize, + pub aspect_43: bool, + pub vsync: bool, + pub vol: [u32; 4], +} + +impl Default for GameSettings { + fn default() -> Self { + // mêmes défauts que le jeu (settings_defaults) + Self { fullscreen: false, window_scale: 3, filter: 0, aspect_43: true, vsync: false, vol: [100; 4] } + } +} + +pub fn path() -> Option { + std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("DoubleTroubleRecomp").join("settings.ini")) +} + +fn parse_bool(v: &str) -> Option { + match v.to_ascii_lowercase().as_str() { + "1" | "true" | "on" => Some(true), + "0" | "false" | "off" => Some(false), + _ => None, + } +} + +/// (clé, valeur) d'une ligne `cle=valeur`, hors commentaires et sections +fn key_value(line: &str) -> Option<(&str, &str)> { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') || l.starts_with(';') || l.starts_with('[') { + return None; + } + let (k, v) = l.split_once('=')?; + Some((k.trim(), v.trim())) +} + +impl GameSettings { + pub fn load() -> Self { + let mut s = Self::default(); + let Some(text) = path().and_then(|p| std::fs::read_to_string(p).ok()) else { return s }; + for line in text.lines() { + let Some((k, v)) = key_value(line) else { continue }; + match k { + "fullscreen" => s.fullscreen = parse_bool(v).unwrap_or(s.fullscreen), + "window_scale" => s.window_scale = v.parse().map(|n: u32| n.clamp(1, 16)).unwrap_or(s.window_scale), + "filter" => s.filter = FILTERS.iter().position(|f| f.eq_ignore_ascii_case(v)).unwrap_or(s.filter), + "aspect_43" => s.aspect_43 = parse_bool(v).unwrap_or(s.aspect_43), + "vsync" => s.vsync = parse_bool(v).unwrap_or(s.vsync), + _ => { + if let Some(i) = VOLUMES.iter().position(|&n| n == k) { + s.vol[i] = v.parse().map(|n: u32| n.min(100)).unwrap_or(s.vol[i]); + } + } + } + } + s + } + + fn entries(&self) -> Vec<(&'static str, &'static str, String)> { + let b = |x: bool| if x { "1".to_string() } else { "0".to_string() }; + let mut e = vec![ + ("display", "fullscreen", b(self.fullscreen)), + ("display", "window_scale", self.window_scale.to_string()), + ("display", "filter", FILTERS[self.filter].to_string()), + ("display", "aspect_43", b(self.aspect_43)), + ("display", "vsync", b(self.vsync)), + ]; + for (i, k) in VOLUMES.iter().enumerate() { + e.push(("audio", k, self.vol[i].to_string())); + } + e + } + + pub fn save(&self) -> std::io::Result<()> { + let Some(p) = path() else { return Ok(()) }; + let old = std::fs::read_to_string(&p).unwrap_or_default(); + let mut lines: Vec = old.lines().map(str::to_string).collect(); + for (section, key, value) in self.entries() { + // 1. la clé existe : on remplace sa valeur sur place + if let Some(l) = lines.iter_mut().find(|l| key_value(l).is_some_and(|(k, _)| k == key)) { + *l = format!("{key}={value}"); + continue; + } + // 2. sinon : à la fin de sa section, créée au besoin + let header = format!("[{section}]"); + match lines.iter().position(|l| l.trim().eq_ignore_ascii_case(&header)) { + Some(h) => { + let mut end = h + 1; + while end < lines.len() && !lines[end].trim().starts_with('[') { + end += 1; + } + while end > h + 1 && lines[end - 1].trim().is_empty() { + end -= 1; + } + lines.insert(end, format!("{key}={value}")); + } + None => { + if lines.last().is_some_and(|l| !l.trim().is_empty()) { + lines.push(String::new()); + } + lines.push(header); + lines.push(format!("{key}={value}")); + } + } + } + if let Some(dir) = p.parent() { + std::fs::create_dir_all(dir)?; + } + let mut text = lines.join("\n"); + text.push('\n'); + std::fs::write(p, text) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn save_keeps_unknown_lines() { + let dir = std::env::temp_dir().join(format!("dtr-settings-{}", std::process::id())); + std::fs::create_dir_all(dir.join("DoubleTroubleRecomp")).unwrap(); + // SAFETY : test isolé, aucun autre fil ne lit APPDATA ici + unsafe { std::env::set_var("APPDATA", &dir) }; + let file = dir.join("DoubleTroubleRecomp").join("settings.ini"); + std::fs::write(&file, "# commentaire\n[display]\nfilter=CRT\nhd_pack=perso\n\n[mods]\nfoo=1\n").unwrap(); + let mut s = GameSettings::load(); + assert_eq!(s.filter, 3); + s.window_scale = 5; + s.vol[1] = 40; + s.save().unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + assert!(text.starts_with("# commentaire\n[display]\nfilter=crt\nhd_pack=perso\n"), "{text}"); + assert!(text.contains("window_scale=5"), "{text}"); + assert!(text.contains("[mods]\nfoo=1"), "{text}"); + assert!(text.contains("[audio]\nmaster_volume=100\nmusic_volume=40"), "{text}"); + let again = GameSettings::load(); + assert!(again == s); + let _ = std::fs::remove_dir_all(dir); + } +}