Refactor state system #7

This commit is contained in:
2026-04-04 22:04:53 +02:00
parent faf3e4ffef
commit 02454625d6
5 changed files with 112 additions and 58 deletions
+25 -24
View File
@@ -1,35 +1,17 @@
use tauri::State;
use crate::{LauncherSettings, Mod, SharedState};
use crate::{save_state, LauncherSettings, Mod, SharedState};
#[tauri::command]
pub fn get_installed_mods(state: State<SharedState>, version_id: String) -> Vec<Mod> {
let state = state.lock().unwrap();
state
.mods
.iter()
.filter(|m| m.supported_versions.contains(&version_id))
.cloned()
.collect()
Vec::new()
}
#[tauri::command]
pub fn toggle_mod(state: State<SharedState>, mod_id: String) {
let mut state = state.lock().unwrap();
if let Some(mod_item) = state.mods.iter_mut().find(|m| m.id == mod_id) {
mod_item.enabled = !mod_item.enabled;
}
}
pub fn toggle_mod(state: State<SharedState>, mod_id: String) {}
#[tauri::command]
pub fn install_mod(state: State<SharedState>, mut mod_item: Mod) {
let mut state = state.lock().unwrap();
if !state.mods.iter().any(|m| m.id == mod_item.id) {
mod_item.enabled = true;
state.mods.push(mod_item);
}
}
pub fn install_mod(state: State<SharedState>, mut mod_item: Mod) {}
#[tauri::command]
pub fn get_settings(state: State<SharedState>) -> LauncherSettings {
@@ -38,6 +20,25 @@ pub fn get_settings(state: State<SharedState>) -> LauncherSettings {
#[tauri::command]
pub fn update_settings(state: State<SharedState>, new_settings: LauncherSettings) {
let mut state = state.lock().unwrap();
state.settings = new_settings;
{
let mut state = state.lock().unwrap();
state.settings = new_settings;
}
save_state(&state);
}
#[tauri::command]
pub fn get_version(state: State<SharedState>) -> String {
state.lock().unwrap().version.clone()
}
#[tauri::command]
pub fn update_version(state: State<SharedState>, version: String) {
{
let mut state = state.lock().unwrap();
state.version = version;
}
save_state(&state);
}
+60 -25
View File
@@ -2,7 +2,11 @@ pub mod commands;
pub mod launcher;
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use std::{fs, path::PathBuf, sync::Mutex};
use crate::launcher::LAUNCHER_DIR;
type SharedState = Mutex<AppState>;
// --- Types ---
#[derive(Clone, Serialize, Deserialize)]
@@ -31,43 +35,74 @@ pub struct LauncherSettings {
}
// --- App State ---
#[derive(Clone, Serialize, Deserialize)]
pub struct AppState {
pub mods: Vec<Mod>,
pub settings: LauncherSettings,
pub version: String,
}
impl Default for AppState {
fn default() -> Self {
Self {
mods: vec![
Mod {
id: "sodium".into(),
name: "Sodium".into(),
version: "0.5.8".into(),
author: "jellysquid3".into(),
description: "Modern rendering engine for Minecraft.".into(),
enabled: true,
icon: None,
supported_versions: vec!["1.20.1".into(), "1.20.4".into(), "1.21".into()],
},
Mod {
id: "iris".into(),
name: "Iris".into(),
version: "1.7.0".into(),
author: "coderbot".into(),
description: "A modern shaders mod for Minecraft.".into(),
enabled: true,
icon: None,
supported_versions: vec!["1.20.1".into(), "1.20.4".into(), "1.21".into()],
},
],
settings: LauncherSettings {
jvm_arguments: "-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200"
.into(),
max_memory: 4096,
},
version: String::from("1.21.6"),
}
}
}
type SharedState = Mutex<AppState>;
// Helper to get config path
fn config_path() -> PathBuf {
LAUNCHER_DIR.config_dir().join("launcher.json")
}
// --- Load ---
pub fn load_state() -> SharedState {
let path = config_path();
if path.exists() {
match fs::read_to_string(&path) {
Ok(content) => match serde_json::from_str::<AppState>(&content) {
Ok(state) => return Mutex::new(state),
Err(err) => {
eprintln!("Failed to parse config, using default: {err}");
}
},
Err(err) => {
eprintln!("Failed to read config, using default: {err}");
}
}
}
// If missing or failed → create default
let default = Mutex::new(AppState::default());
save_state(&default);
default
}
// --- Save ---
pub fn save_state(state: &SharedState) {
let path = config_path();
if let Some(parent) = path.parent() {
if let Err(err) = fs::create_dir_all(parent) {
eprintln!("Failed to create config directory: {err}");
return;
}
}
match serde_json::to_string_pretty(&*state.lock().unwrap()) {
Ok(json) => {
if let Err(err) = fs::write(path, json) {
eprintln!("Failed to write config: {err}");
}
}
Err(err) => {
eprintln!("Failed to serialize config: {err}");
}
}
}
+9 -8
View File
@@ -1,21 +1,22 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use saturn_launcher_lib::{commands::*, AppState};
use std::sync::Mutex;
use saturn_launcher_lib::load_state;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.manage(Mutex::new(AppState::default()))
.manage(load_state())
.invoke_handler(tauri::generate_handler![
// Saturn Launcher Commands
get_installed_mods,
toggle_mod,
install_mod,
get_settings,
update_settings,
saturn_launcher_lib::commands::get_installed_mods,
saturn_launcher_lib::commands::toggle_mod,
saturn_launcher_lib::commands::install_mod,
saturn_launcher_lib::commands::get_settings,
saturn_launcher_lib::commands::update_settings,
saturn_launcher_lib::commands::get_version,
saturn_launcher_lib::commands::update_version,
// Launcher Commands
saturn_launcher_lib::launcher::launch_game,
// Auth Commands
+9 -1
View File
@@ -7,6 +7,7 @@ import SettingsSection from "./components/SettingsSection";
import { versions } from "./lib/launcher";
import { GameVersion } from "./lib/types";
import { MinecraftAccount } from "./lib/auth";
import { getVersion, updateVersion } from "./lib/saturn";
type Section = "play" | "mods" | "settings";
@@ -50,9 +51,16 @@ export default function App() {
}, []);
useEffect(() => {
setSelectedVersion(versions[0]);
(async () => {
const version = await getVersion();
setSelectedVersion(versions.find((v) => v.id == version) || null);
})();
}, []);
useEffect(() => {
if (selectedVersion?.id) updateVersion(selectedVersion?.id);
}, [selectedVersion]);
return (
<div className="flex h-screen">
<Sidebar active={active} setActive={setActive} />
+9
View File
@@ -65,3 +65,12 @@ export async function updateSettings(
): Promise<void> {
await invoke("update_settings", { newSettings });
}
// --- Version ---
export async function getVersion(): Promise<string> {
return await invoke("get_version");
}
export async function updateVersion(version: string): Promise<void> {
await invoke("update_version", { version });
}