use serde::{Deserialize, Serialize}; use tauri::AppHandle; use std::{collections::BTreeSet, path::{Path, PathBuf}}; use crate::{model::{misc::Game, profile::Aime}, modules::package::prepare_packages, pkg::PkgKey, pkg_store::PackageStore, util}; use tauri::Emitter; use std::process::Stdio; use crate::model::profile::BepInEx; use crate::model::{profile::{Display, DisplayMode, Network, Segatools}, segatools_base::segatools_base}; use anyhow::{anyhow, Result}; use std::fs::File; use tokio::process::Command; use tokio::task::JoinSet; pub trait ProfilePaths { fn config_dir(&self) -> PathBuf; fn data_dir(&self) -> PathBuf; } #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)] pub struct ProfileMeta { pub game: Game, pub name: String } impl ProfilePaths for ProfileMeta { fn config_dir(&self) -> PathBuf { util::profile_config_dir(self.game, &self.name) } fn data_dir(&self) -> PathBuf { util::data_dir().join(format!("profile-{}-{}", &self.game, &self.name)) } } #[derive(Deserialize, Serialize, Clone)] pub struct Profile { pub meta: ProfileMeta, pub data: ProfileData, } #[derive(Deserialize, Serialize, Clone, Debug)] pub struct ProfileData { pub mods: BTreeSet, pub sgt: Segatools, pub display: Option, pub network: Network, #[serde(skip_serializing_if = "Option::is_none")] pub bepinex: Option, #[cfg(not(target_os = "windows"))] pub wine: crate::model::profile::Wine, } impl Profile { pub fn new(mut meta: ProfileMeta) -> Result { meta.name = fixed_name(&meta, true); log::debug!("created profile-{:?}", &meta); let p = Profile { data: ProfileData { mods: BTreeSet::new(), sgt: Segatools::default_for(meta.game), #[cfg(target_os = "windows")] display: if meta.game == Game::Ongeki { Some(Display::default_for(meta.game)) } else { None }, #[cfg(not(target_os = "windows"))] display: None, network: Network::default(), bepinex: if meta.game == Game::Ongeki { Some(BepInEx::default()) } else { None }, #[cfg(not(target_os = "windows"))] wine: crate::model::profile::Wine::default(), }, meta: meta.clone() }; p.save()?; std::fs::create_dir_all(p.config_dir())?; std::fs::create_dir_all(p.data_dir())?; std::fs::write(p.config_dir().join("segatools-base.ini"), segatools_base(meta.game))?; Ok(p) } pub fn load(game: Game, name: String) -> Result { let path = util::profile_config_dir(game, &name).join("profile.json"); if let Ok(s) = std::fs::read_to_string(&path) { let data = serde_json::from_str::(&s) .map_err(|e| anyhow!("Unable to parse {:?}: {:?}", path, e))?; log::debug!("{:?}", data); Ok(Profile { meta: ProfileMeta { game, name }, data }) } else { Err(anyhow!("Unable to open {:?}", path)) } } pub fn save(&self) -> Result<()> { let path = self.config_dir().join("profile.json"); let s = serde_json::to_string_pretty(&self.data)?; if !self.config_dir().exists() { std::fs::create_dir(self.config_dir()) .map_err(|e| anyhow!("error when creating profile directory: {}", e))?; } std::fs::write(&path, s) .map_err(|e| anyhow!("error when writing to {:?}: {}", path, e))?; log::info!("Written to {:?}", path); Ok(()) } pub fn rename(&mut self, name: String) { self.meta.name = fixed_name(&ProfileMeta { game: self.meta.game, name}, false); } pub fn mod_pkgs(&self) -> &BTreeSet { &self.data.mods } pub fn mod_pkgs_mut(&mut self) -> &mut BTreeSet { &mut self.data.mods } pub fn special_pkgs(&self) -> Vec { let mut res = Vec::new(); if let Some(hook) = &self.data.sgt.hook { res.push(hook.clone()); } if let Some(io) = &self.data.sgt.io { res.push(io.clone()); } if let Aime::AMNet(aime) = &self.data.sgt.aime { res.push(aime.clone()); } else if let Aime::Other(aime) = &self.data.sgt.aime { res.push(aime.clone()); } res } pub fn fix(&mut self, store: &PackageStore) { self.data.sgt.fix(store); } pub fn sync(&mut self, source: ProfileData) { if self.data.bepinex.is_some() { self.data.bepinex = source.bepinex; } if self.data.display.is_some() { self.data.display = source.display; } // if self.data.network.is_some() { self.data.network = source.network; // } // if self.data.sgt.is_some() { self.data.sgt = source.sgt; // } } pub async fn line_up(&self, pkg_hash: String, _app: AppHandle) -> Result<()> { let info = match &self.data.display { None => None, Some(display) => display.line_up()? }; let res = self.line_up_the_rest(pkg_hash).await; #[cfg(target_os = "windows")] if let Some(info) = info { use crate::model::profile::Display; if res.is_ok() { Display::wait_for_exit(_app, info); } else { Display::clean_up(&info)?; } } res } async fn line_up_the_rest(&self, pkg_hash: String) -> Result<()> { if !self.data_dir().exists() { tokio::fs::create_dir(self.data_dir()).await?; } let hash_path = self.data_dir().join(".sl-state"); util::clean_up_opts(self.data_dir().join("option"))?; let hash_check = Self::hash_check(&hash_path, &pkg_hash).await?; prepare_packages(&self.meta, &self.data.mods, hash_check).await .map_err(|e| anyhow!("package configuration failed:\n{:?}", e))?; let mut ini = self.data.sgt.line_up(&self.meta, self.meta.game).await .map_err(|e| anyhow!("segatools configuration failed:\n{:?}", e))?; self.data.network.line_up(&mut ini)?; ini.write_to_file(self.data_dir().join("segatools.ini")) .map_err(|e| anyhow!("Error writing segatools.ini: {}", e))?; if let Some(bepinex) = &self.data.bepinex { bepinex.line_up(&self.meta)?; } Ok(()) } pub async fn start(&self, app: AppHandle) -> Result<()> { let ini_path = self.data_dir().join("segatools.ini"); log::debug!("With path {:?}", ini_path); let mut game_builder; let mut amd_builder; let target_path = PathBuf::from(&self.data.sgt.target); let exe_dir = target_path.parent().ok_or_else(|| anyhow!("Invalid target path"))?; let sgt_dir = self.data.sgt.hook_dir()?; #[cfg(target_os = "windows")] { game_builder = Command::new(sgt_dir.join(self.meta.game.inject_exe())); amd_builder = Command::new("cmd.exe"); } #[cfg(target_os = "linux")] { game_builder = Command::new(&self.wine.runtime); amd_builder = Command::new(&self.wine.runtime); game_builder.arg(sgt_dir.join(self.meta.game.inject_exe())); amd_builder.arg("cmd.exe"); } amd_builder.env( "SEGATOOLS_CONFIG_PATH", &ini_path, ) .current_dir(&exe_dir) .arg("/C") .arg(&sgt_dir.join(self.meta.game.inject_amd())) .args(["-d", "-k"]) .arg(sgt_dir.join(self.meta.game.hook_amd())) .arg("amdaemon.exe") .args(self.meta.game.amd_args()); game_builder .env( "SEGATOOLS_CONFIG_PATH", ini_path, ) .env( "INOHARA_CONFIG_PATH", self.config_dir().join("inohara.cfg"), ) .current_dir(&exe_dir) .args(["-d", "-k"]) .arg(sgt_dir.join(self.meta.game.hook_exe())) .arg(self.meta.game.exe()); if let Some(display) = &self.data.display { game_builder.args([ "-monitor 1", "-screen-width", &display.rez.0.to_string(), "-screen-height", &display.rez.1.to_string(), "-screen-fullscreen", if display.mode == DisplayMode::Fullscreen { "1" } else { "0" } ]); if display.mode == DisplayMode::Borderless { game_builder.arg("-popupwindow"); } } #[cfg(target_os = "linux")] { amd_builder.env("WINEPREFIX", &self.wine.prefix); game_builder.env("WINEPREFIX", &self.wine.prefix); } let amd_log = File::create(self.data_dir().join("amdaemon.exe.log"))?; let game_log = File::create(self.data_dir().join(format!("{}.log", self.meta.game.exe())))?; amd_builder .stdout(Stdio::from(amd_log)); // do they use stderr? game_builder .stdout(Stdio::from(game_log)); #[cfg(target_os = "windows")] { amd_builder.creation_flags(util::CREATE_NO_WINDOW); game_builder.creation_flags(util::CREATE_NO_WINDOW); } if self.data.sgt.intel == true { amd_builder.env("OPENSSL_ia32cap", ":~0x20000000"); } util::pkill("amdaemon.exe").await; log::info!("Launching amdaemon: {:?}", amd_builder); log::info!("Launching {}: {:?}", self.meta.game, game_builder); let mut amd = amd_builder.spawn()?; let mut game = game_builder.spawn()?; let mut set = JoinSet::new(); set.spawn(async move { (amd.wait().await.expect("amdaemon failed to run"), "amdaemon") }); set.spawn(async move { (game.wait().await.expect("game failed to run"), "game") }); if let Err(e) = app.emit("launch-start", "") { log::warn!("Unable to emit launch-start: {}", e); } let (rc, process) = set.join_next().await.expect("No spawn").expect("No result"); log::info!("{} died with return code {}", process, rc); if process == "amdaemon" { util::pkill(self.meta.game.exe()).await; } else { util::pkill("amdaemon.exe").await; } set.join_next().await.expect("No spawn").expect("No result"); log::debug!("Fin"); if let Err(e) = app.emit("launch-end", "") { log::warn!("Unable to emit launch-end: {}", e); } Ok(()) } async fn hash_check(prev_hash_path: &impl AsRef, new_hash: &str) -> Result { let prev_hash = tokio::fs::read_to_string(&prev_hash_path).await.unwrap_or_default(); if prev_hash != new_hash { log::debug!("state {} -> {}", prev_hash, new_hash); tokio::fs::write(prev_hash_path, new_hash).await .map_err(|e| anyhow!("Unable to write the state file: {}", e))?; Ok(true) } else { Ok(false) } } } impl ProfilePaths for Profile { fn config_dir(&self) -> PathBuf { self.meta.config_dir() } fn data_dir(&self) -> PathBuf { self.meta.data_dir() } } impl std::fmt::Debug for Profile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple(&self.meta.game.to_string()).field(&self.meta.name).finish() } } pub async fn list_profiles() -> Result> { let path = std::fs::read_dir(util::config_dir())?; let mut res = Vec::new(); for f in path { let f = f?; if let Ok(meta) = f.metadata() { if !meta.is_dir() { continue; } log::debug!("{:?}", f); if let Some(meta) = meta_from_path(f.path()) { res.push(meta); } } } Ok(res) } fn meta_from_path(path: impl AsRef) -> Option { let regex = regex::Regex::new( r"^profile-([^\-]+)-(.+)$" ).expect("Invalid regex"); let fname = path.as_ref().file_name().unwrap_or_default().to_string_lossy(); if let Some(caps) = regex.captures(&fname) { let game = caps.get(1).unwrap().as_str(); let name = caps.get(2).unwrap().as_str().to_owned(); if let Some(game) = Game::from_str(game) { return Some(ProfileMeta { game, name }); } } None } pub fn fixed_name(meta: &ProfileMeta, prepend_new: bool) -> String { let mut name = meta.name.trim() .replace(" ", "-") .replace("..", "").replace("/", "").replace("\\", ""); while prepend_new && util::profile_config_dir(meta.game, &name).exists() { name = format!("new-{}", name); } name }