feat: more breaking changes

This commit is contained in:
2025-03-06 20:38:18 +00:00
parent 39ba6a5891
commit cda8230d7d
19 changed files with 638 additions and 559 deletions

View File

@ -14,56 +14,51 @@ pub struct GlobalConfig {
pub struct AppData {
pub profile: Option<Profile>,
pub pkgs: PackageStore,
pub cfg: GlobalConfig
pub cfg: GlobalConfig,
}
impl AppData {
pub fn new(app: AppHandle) -> AppData {
let path = util::get_dirs()
.config_dir()
.join("config.json");
let cfg = std::fs::read_to_string(&path)
pub fn new(apph: AppHandle) -> AppData {
let cfg = std::fs::read_to_string(util::config_dir().join("config.json"))
.and_then(|s| Ok(serde_json::from_str::<GlobalConfig>(&s)?))
.unwrap_or_default();
let profile = match cfg.recent_profile {
Some((ref game, ref name)) => Profile::load(game, name).ok(),
Some((ref game, ref name)) => Profile::load(game.clone(), name.clone()).ok(),
None => None
};
AppData {
profile,
pkgs: PackageStore::new(app),
cfg
pkgs: PackageStore::new(apph.clone()),
cfg,
}
}
pub fn write(&self) -> Result<(), std::io::Error> {
let path = util::get_dirs()
.config_dir()
.join("config.json");
std::fs::write(&path, serde_json::to_string(&self.cfg)?)
std::fs::write(util::config_dir().join("config.json"), serde_json::to_string(&self.cfg)?)
}
pub fn switch_profile(&mut self, game: &Game, name: &str) -> Result<()> {
self.profile = Profile::load(game, name).ok();
if self.profile.is_some() {
self.cfg.recent_profile = Some((game.to_owned(), name.to_owned()));
} else {
self.cfg.recent_profile = None;
pub fn switch_profile(&mut self, game: Game, name: String) -> Result<()> {
match Profile::load(game.clone(), name.clone()) {
Ok(profile) => {
self.profile = Some(profile);
self.cfg.recent_profile = Some((game, name));
self.write()?;
Ok(())
}
Err(e) => {
self.profile = None;
self.cfg.recent_profile = None;
Err(e)
}
}
self.write()?;
Ok(())
}
pub fn toggle_package(&mut self, key: PkgKey, enable: bool) -> Result<()> {
log::debug!("toggle: {} {}", key, enable);
let profile = self.profile.as_mut()
.ok_or_else(|| anyhow!("No profile"))?;
let profile = self.profile.as_mut().ok_or_else(|| anyhow!("No profile"))?;
if enable {
let pkg = self.pkgs.get(&key)?;

View File

@ -1,6 +1,5 @@
use log;
use std::collections::HashMap;
use std::path::PathBuf;
use tokio::sync::Mutex;
use tokio::fs;
@ -9,7 +8,7 @@ use crate::pkg::{Package, PkgKey};
use crate::pkg_store::InstallResult;
use crate::profile::Profile;
use crate::appdata::AppData;
use crate::{liner, start};
use crate::{liner, start, util};
use tauri::{AppHandle, Manager, State};
@ -121,7 +120,7 @@ pub async fn load_profile(state: State<'_, Mutex<AppData>>, game: Game, name: St
log::debug!("invoke: load_profile({} {:?})", game, name);
let mut appd = state.lock().await;
appd.switch_profile(&game, &name).map_err(|e| e.to_string())?;
appd.switch_profile(game, name).map_err(|e| e.to_string())?;
Ok(())
}
@ -133,17 +132,6 @@ pub async fn get_current_profile(state: State<'_, Mutex<AppData>>) -> Result<Opt
Ok(appd.profile.clone())
}
#[tauri::command]
pub async fn get_current_profile_dir(state: State<'_, Mutex<AppData>>) -> Result<PathBuf, &str> {
let appd = state.lock().await;
if let Some(p) = &appd.profile {
Ok(p.dir())
} else {
Err("No profile loaded")
}
}
#[tauri::command]
pub async fn save_current_profile(state: State<'_, Mutex<AppData>>) -> Result<(), ()> {
log::debug!("invoke: save_current_profile");
@ -161,54 +149,23 @@ pub async fn save_current_profile(state: State<'_, Mutex<AppData>>) -> Result<()
#[tauri::command]
pub async fn init_profile(
state: State<'_, Mutex<AppData>>,
exe_path: PathBuf
game: Game,
name: String
) -> Result<Profile, String> {
log::debug!("invoke: init_profile({:?})", exe_path);
log::debug!("invoke: init_profile({}, {})", game, name);
let mut appd = state.lock().await;
if let Some(new_profile) = Profile::new(exe_path) {
new_profile.save().await;
appd.profile = Some(new_profile.clone());
fs::create_dir_all(new_profile.dir()).await
.map_err(|e| format!("Unable to create the profile directory: {}", e))?;
let new_profile = Profile::new(game, name);
Ok(new_profile)
} else {
Err("Unrecognized game".to_owned())
}
}
fs::create_dir_all(new_profile.config_dir()).await
.map_err(|e| format!("Unable to create the profile config directory: {}", e))?;
fs::create_dir_all(new_profile.data_dir()).await
.map_err(|e| format!("Unable to create the profile data directory: {}", e))?;
#[tauri::command]
pub async fn read_profile_data(
state: State<'_, Mutex<AppData>>,
path: PathBuf
) -> Result<String, String> {
let appd = state.lock().await;
appd.profile = Some(new_profile.clone());
new_profile.save().await;
if let Some(p) = &appd.profile {
let res = fs::read_to_string(p.dir().join(&path)).await
.map_err(|e| format!("Unable to open {:?}: {}", path, e))?;
Ok(res)
} else {
Err("No profile loaded".to_owned())
}
}
#[tauri::command]
pub async fn write_profile_data(
state: State<'_, Mutex<AppData>>,
path: PathBuf,
content: String
) -> Result<(), String> {
let appd = state.lock().await;
if let Some(p) = &appd.profile {
fs::write(p.dir().join(&path), content).await
.map_err(|e| format!("Unable to write to {:?}: {}", path, e))?;
Ok(())
} else {
Err("No profile loaded".to_owned())
}
Ok(new_profile)
}
#[tauri::command]
@ -266,3 +223,10 @@ pub async fn list_displays() -> Result<Vec<String>, ()> {
Ok(Vec::new())
}
#[tauri::command]
pub async fn list_directories() -> Result<util::Dirs, ()> {
log::debug!("invoke: list_directores");
Ok(util::all_dirs().clone())
}

View File

@ -17,7 +17,7 @@ pub async fn prepare_display(_: &Profile) -> Result<()> {
#[cfg(target_os = "windows")]
pub async fn prepare_display(p: &Profile) -> Result<Option<DisplayInfo>> {
use anyhow::anyhow;
use displayz::{query_displays, Orientation, Resolution};
use displayz::{query_displays, Orientation, Resolution, Frequency};
let display_name = p.get_str("display", "default");
let rotation = p.get_int("display-rotation", 0);
@ -57,11 +57,22 @@ pub async fn prepare_display(p: &Profile) -> Result<Option<DisplayInfo>> {
}
}
let frequency: u32 = p.get_int("frequency", 60)
.try_into()
.map_err(|e| anyhow!("Invalid display frequency: {}", e))?;
let width: u32 = p.get_int("rez-w", 1080)
.try_into()
.map_err(|e| anyhow!("Invalid display width: {}", e))?;
let height: u32 = p.get_int("rez-h", 1080)
.try_into()
.map_err(|e| anyhow!("Invalid display height: {}", e))?;
settings.borrow_mut().frequency = Frequency::new(frequency);
if p.get_str("display-mode", "borderless") == "borderless" && p.get_bool("borderless-fullscreen", false) {
settings.borrow_mut().resolution = Resolution::new(
p.get_int("rez-w", 1080).try_into().expect("Negative resolution"),
p.get_int("rez-h", 1920).try_into().expect("Negative resolution")
);
settings.borrow_mut().resolution = Resolution::new(width, height);
}
display_set.apply()?;
@ -74,6 +85,7 @@ pub async fn prepare_display(p: &Profile) -> Result<Option<DisplayInfo>> {
#[cfg(target_os = "windows")]
pub async fn undo_display(info: DisplayInfo) -> Result<()> {
use anyhow::anyhow;
use displayz::query_displays;
let display_set = query_displays()?;

View File

@ -31,12 +31,6 @@ pub async fn run(_args: Vec<String>) {
.unwrap_or_default()
);
try_join!(
fs::create_dir_all(util::config_dir()),
fs::create_dir_all(util::pkg_dir()),
fs::create_dir_all(util::cache_dir())
).expect("Unable to create working directories");
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {
let _ = app
@ -74,12 +68,29 @@ pub async fn run(_args: Vec<String>) {
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_opener::init())
.setup(|app| {
let apph = app.handle();
util::init_dirs(&apph);
let app_data = AppData::new(app.handle().clone());
app.manage(Mutex::new(app_data));
app.deep_link().register_all()?;
let apph = app.handle();
log::debug!("\n{:?}\n{:?}\n{:?}", util::config_dir(), util::pkg_dir(), util::cache_dir());
tauri::async_runtime::spawn(async {
let e = try_join!(
fs::create_dir_all(util::config_dir()),
fs::create_dir_all(util::pkg_dir()),
fs::create_dir_all(util::cache_dir())
);
if let Err(e) = e {
log::error!("Unable to create base directories: {}", e);
std::process::exit(1);
}
});
app.listen("download-end", closure!(clone apph, |ev| {
let raw = ev.payload();
@ -107,17 +118,15 @@ pub async fn run(_args: Vec<String>) {
cmd::init_profile,
cmd::load_profile,
cmd::get_current_profile,
cmd::get_current_profile_dir,
cmd::save_current_profile,
cmd::read_profile_data,
cmd::write_profile_data,
cmd::set_cfg,
cmd::startline,
cmd::kill,
cmd::list_platform_capabilities,
cmd::set_cfg,
cmd::list_displays,
cmd::list_platform_capabilities,
cmd::list_directories,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");

View File

@ -17,7 +17,7 @@ async fn symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Resul
}
pub async fn line_up(p: &Profile, pkg_hash: String) -> Result<()> {
let dir_out = p.dir();
let dir_out = p.data_dir();
if dir_out.join("option").exists() {
fs::remove_dir_all(dir_out.join("option")).await?;
@ -25,7 +25,7 @@ pub async fn line_up(p: &Profile, pkg_hash: String) -> Result<()> {
fs::create_dir_all(dir_out.join("option")).await?;
let hash_path = p.dir().join(".sl-state");
let hash_path = p.data_dir().join(".sl-state");
let prev_hash = fs::read_to_string(&hash_path).await.unwrap_or_default();
if prev_hash != pkg_hash {
log::debug!("state {} -> {}", prev_hash, pkg_hash);
@ -40,7 +40,7 @@ pub async fn line_up(p: &Profile, pkg_hash: String) -> Result<()> {
}
async fn prepare_packages(p: &Profile) -> Result<()> {
let dir_out = p.dir();
let dir_out = p.data_dir();
if dir_out.join("BepInEx").exists() {
fs::remove_dir_all(dir_out.join("BepInEx")).await?;
@ -71,25 +71,26 @@ async fn prepare_packages(p: &Profile) -> Result<()> {
}
async fn prepare_config(p: &Profile) -> Result<()> {
let dir_out = p.dir();
let dir_out = p.data_dir();
let ini_in_raw = fs::read_to_string(p.data.exe_dir.join("segatools.ini")).await?;
let target_path = PathBuf::from(p.get_str("target-path", ""));
let exe_dir = target_path.parent().ok_or_else(|| anyhow!("Invalid target path"))?;
let ini_in_raw = fs::read_to_string(p.config_dir().join("segatools-base.ini")).await?;
let ini_in = Ini::load_from_str(&ini_in_raw)?;
let mut opt_dir_in = PathBuf::from(
ini_in.section(Some("vfs"))
.ok_or_else(|| anyhow!("No VFS section in segatools.ini"))?
.get("option")
.ok_or_else(|| anyhow!("No option specified in segatools.ini"))?
);
if opt_dir_in.is_relative() {
opt_dir_in = p.data.exe_dir.join(opt_dir_in);
let mut opt_dir_in = PathBuf::from(p.get_str("option", ""));
if opt_dir_in.as_os_str().len() > 0 && opt_dir_in.is_relative() {
opt_dir_in = exe_dir.join(opt_dir_in);
}
let opt_dir_out = &dir_out.join("option");
let mut ini_out = ini_in.clone();
ini_out.with_section(Some("vfs")).set(
"option",
util::path_to_str(opt_dir_out)?
ini_out.with_section(Some("vfs"))
.set(
"option",
util::path_to_str(opt_dir_out)?
)
.set("amfs", p.get_str("amfs", ""))
.set("appdata", p.get_str("appdata", "appdata")
);
ini_out.with_section(Some("unity"))
.set("enable", "1")
@ -107,9 +108,11 @@ async fn prepare_config(p: &Profile) -> Result<()> {
ini_out.write_to_file(dir_out.join("segatools.ini"))?;
log::debug!("Option dir: {:?} -> {:?}", opt_dir_in, opt_dir_out);
for opt in opt_dir_in.read_dir()? {
let opt = opt?;
symlink(&opt.path(), opt_dir_out.join(opt.file_name())).await?;
if opt_dir_in.as_os_str().len() > 0 {
for opt in opt_dir_in.read_dir()? {
let opt = opt?;
symlink(&opt.path(), opt_dir_out.join(opt.file_name())).await?;
}
}
log::debug!("prepare config: done");

View File

@ -5,7 +5,6 @@ use crate::pkg::PkgKeyVersion;
// /c/{game}/api/v1/package
#[derive(Deserialize)]
#[allow(dead_code)]
pub struct V1Package {
pub owner: String,
pub package_url: String,
@ -14,7 +13,6 @@ pub struct V1Package {
}
#[derive(Deserialize)]
#[allow(dead_code)]
pub struct V1Version {
pub name: String,
pub description: String,

View File

@ -14,73 +14,67 @@ pub struct Profile {
// The contents of profile-{game}-{name}.json
#[derive(Deserialize, Serialize, Clone)]
pub struct ProfileData {
pub exe_dir: PathBuf,
pub mods: BTreeSet<PkgKey>,
pub wine_runtime: Option<PathBuf>,
pub wine_prefix: Option<PathBuf>,
// cfg is temporarily just a map to make iteration easier
// eventually it should become strict
pub cfg: BTreeMap<String, serde_json::Value>
}
impl Profile {
pub fn new(exe_path: PathBuf) -> Option<Profile> {
let game;
if exe_path.ends_with("mu3.exe") {
game = misc::Game::Ongeki
} else if exe_path.ends_with("chusanApp.exe") {
// game = misc::Game::Chunithm;
return None;
} else {
return None;
pub fn new(game: Game, mut name: String) -> Profile {
name = name.trim().replace(" ", "-");
while Self::config_dir_f(&game, &name).exists() {
name = format!("new-{}", name);
}
Some(Profile {
name: format!("{}", "default"),
Profile {
name,
game,
data: ProfileData {
exe_dir: exe_path.parent().unwrap().to_owned(),
mods: BTreeSet::new(),
wine_runtime: None,
wine_prefix: None,
cfg: BTreeMap::new()
}
})
}
}
pub fn dir(&self) -> PathBuf {
util::get_dirs()
.data_dir()
.join(format!("profile-{}-{}", self.game, self.name))
.to_owned()
fn config_dir_f(game: &Game, name: &str) -> PathBuf {
util::config_dir().join(format!("profile-{}-{}", game, name))
}
pub fn config_dir(&self) -> PathBuf {
Self::config_dir_f(&self.game, &self.name)
}
pub fn data_dir(&self) -> PathBuf {
util::data_dir().join(format!("profile-{}-{}", self.game, self.name))
}
pub async fn list() -> Result<Vec<(Game, String)>> {
let path = std::fs::read_dir(
util::get_dirs().config_dir()
)?;
let path = std::fs::read_dir(util::config_dir())?;
let mut res = Vec::new();
for f in path {
let f = f?;
if let Some(pair) = Self::name_from_path(f.path()) {
res.push(pair);
if let Ok(meta) = f.metadata() {
if !meta.is_dir() {
continue;
}
log::debug!("{:?}", f);
if let Some(pair) = Self::name_from_path(f.path()) {
res.push(pair);
}
}
}
Ok(res)
}
pub fn load(game: &Game, name: &str) -> Result<Profile> {
let path = util::get_dirs()
.config_dir()
.join(format!("profile-{}-{}.json", game, name));
pub fn load(game: Game, name: String) -> Result<Profile> {
let path = Self::config_dir_f(&game, &name).join("profile.json");
if let Ok(s) = std::fs::read_to_string(&path) {
let (game, name) = Self::name_from_path(&path)
.ok_or_else(|| anyhow!("Invalid filename: {:?}", path.file_name()))?;
let data = serde_json::from_str::<ProfileData>(&s)
.map_err(|e| anyhow!("Unable to parse {:?}: {:?}", path, e))?;
@ -95,9 +89,7 @@ impl Profile {
}
pub async fn save(&self) {
let path = util::get_dirs()
.config_dir()
.join(format!("profile-{}-{}.json", self.game, self.name));
let path = self.config_dir().join("profile.json");
let s = serde_json::to_string_pretty(&self.data).unwrap();
fs::write(&path, s).await.unwrap();
@ -131,7 +123,7 @@ impl Profile {
fn name_from_path(path: impl AsRef<Path>) -> Option<(Game, String)> {
let regex = regex::Regex::new(
r"profile-([^\-]+)-([^\-]+)\.json"
r"^profile-([^\-]+)-(.+)$"
).expect("Invalid regex");
let fname = path.as_ref().file_name().unwrap_or_default().to_string_lossy();

View File

@ -1,5 +1,6 @@
use anyhow::Result;
use anyhow::{anyhow, Result};
use std::fs::File;
use std::path::PathBuf;
use tokio::process::Command;
use tauri::{AppHandle, Emitter};
use std::process::Stdio;
@ -12,19 +13,22 @@ static CREATE_NO_WINDOW: u32 = 0x08000000;
pub async fn start(p: &Profile, app: AppHandle) -> Result<()> {
use tokio::task::JoinSet;
let ini_path = p.dir().join("segatools.ini");
let ini_path = p.data_dir().join("segatools.ini");
log::debug!("With path {}", ini_path.to_string_lossy());
let mut game_builder;
let mut amd_builder;
let target_path = PathBuf::from(p.get_str("target-path", ""));
let exe_dir = target_path.parent().ok_or_else(|| anyhow!("Invalid target path"))?;
#[cfg(target_os = "windows")]
let display_info = crate::display::prepare_display(p).await?;
#[cfg(target_os = "windows")]
{
game_builder = Command::new(p.data.exe_dir.join("inject.exe"));
game_builder = Command::new(exe_dir.join("inject.exe"));
amd_builder = Command::new("cmd.exe");
}
#[cfg(target_os = "linux")]
@ -35,7 +39,7 @@ pub async fn start(p: &Profile, app: AppHandle) -> Result<()> {
game_builder = Command::new(&wine);
amd_builder = Command::new(&wine);
game_builder.arg(p.data.exe_dir.join("inject.exe"));
game_builder.arg(exe_dir.join("inject.exe"));
amd_builder.arg("cmd.exe");
}
@ -45,10 +49,10 @@ pub async fn start(p: &Profile, app: AppHandle) -> Result<()> {
"SEGATOOLS_CONFIG_PATH",
&ini_path,
)
.current_dir(&p.data.exe_dir)
.current_dir(&exe_dir)
.args([
"/C",
&util::path_to_str(p.data.exe_dir.join("inject.exe"))?, "-d", "-k", "mu3hook.dll",
&util::path_to_str(exe_dir.join("inject.exe"))?, "-d", "-k", "mu3hook.dll",
"amdaemon.exe", "-f", "-c", "config_common.json", "config_server.json", "config_client.json"
]);
game_builder
@ -58,9 +62,9 @@ pub async fn start(p: &Profile, app: AppHandle) -> Result<()> {
)
.env(
"INOHARA_CONFIG_PATH",
p.dir().join("inohara.cfg"),
p.config_dir().join("inohara.cfg"),
)
.current_dir(&p.data.exe_dir)
.current_dir(&exe_dir)
.args([
"-d", "-k", "mu3hook.dll",
"mu3.exe", "-monitor 1",
@ -86,8 +90,8 @@ pub async fn start(p: &Profile, app: AppHandle) -> Result<()> {
}
let amd_log = File::create(p.dir().join("amdaemon.log"))?;
let game_log = File::create(p.dir().join("mu3.log"))?;
let amd_log = File::create(p.data_dir().join("amdaemon.log"))?;
let game_log = File::create(p.data_dir().join("mu3.log"))?;
amd_builder
.stdout(Stdio::from(amd_log));

View File

@ -1,26 +1,63 @@
use anyhow::{anyhow, Result};
use directories::ProjectDirs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Manager};
use std::{path::{Path, PathBuf}, sync::OnceLock};
pub fn get_dirs() -> ProjectDirs {
ProjectDirs::from("org", "7EVENDAYSHOLIDAYS", "STARTLINER")
.expect("Unable to set up config directories")
#[cfg(not(target_os = "windows"))]
static NAME: &str = "startliner";
#[cfg(target_os = "windows")]
static NAME: &str = "STARTLINER";
#[derive(Clone, Serialize, Deserialize)]
pub struct Dirs {
config_dir: PathBuf,
data_dir: PathBuf,
cache_dir: PathBuf,
}
pub fn config_dir() -> PathBuf {
get_dirs().config_dir().to_owned()
static DIRS: OnceLock<Dirs> = OnceLock::new();
pub fn init_dirs(apph: &AppHandle) {
DIRS.get_or_init(|| {
if cfg!(windows) {
Dirs {
config_dir: apph.path().data_dir().expect("Unable to set project directories").join(NAME).join("cfg"),
data_dir: apph.path().data_dir().expect("Unable to set project directories").join(NAME).join("data"),
cache_dir: apph.path().cache_dir().expect("Unable to set project directories").join(NAME),
}
} else {
Dirs {
config_dir: apph.path().config_dir().expect("Unable to set project directories").join(NAME),
data_dir: apph.path().data_dir().expect("Unable to set project directories").join(NAME),
cache_dir: apph.path().cache_dir().expect("Unable to set project directories").join(NAME),
}
}
});
}
pub fn all_dirs() -> &'static Dirs {
&DIRS.get().expect("Directories uninitialized")
}
pub fn config_dir() -> &'static Path {
&DIRS.get().expect("Directories uninitialized").config_dir
}
pub fn data_dir() -> &'static Path {
&DIRS.get().expect("Directories uninitialized").data_dir
}
pub fn cache_dir() -> &'static Path {
&DIRS.get().expect("Directories uninitialized").cache_dir
}
pub fn pkg_dir() -> PathBuf {
get_dirs().data_dir().join("pkg").to_owned()
data_dir().join("pkg")
}
pub fn pkg_dir_of(namespace: &str, name: &str) -> PathBuf {
pkg_dir().join(format!("{}-{}", namespace, name)).to_owned()
}
pub fn cache_dir() -> PathBuf {
get_dirs().cache_dir().to_owned()
pkg_dir().join(format!("{}-{}", namespace, name))
}
pub fn path_to_str(p: impl AsRef<Path>) -> Result<String> {
@ -40,4 +77,4 @@ pub fn copy_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
}
}
Ok(())
}
}