[feat] reset modal + basic auto get path + basic wrap err try

This commit is contained in:
Purp1e
2025-03-20 14:13:03 +08:00
parent 60782669ea
commit a9a48d2aba
12 changed files with 163 additions and 62 deletions

12
src-tauri/Cargo.lock generated
View File

@@ -1,11 +1,13 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "CS工具箱"
version = "0.0.1"
dependencies = [
"anyhow",
"log",
"serde",
"serde_json",
"tauri",
@@ -85,9 +87,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.91"
version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c042108f3ed77fd83760a5fd79b53be043192bb3b9dba91d8c574c0ada7850c8"
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
[[package]]
name = "arboard"
@@ -2439,9 +2441,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.22"
version = "0.4.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"
[[package]]
name = "mac"

View File

@@ -7,7 +7,7 @@ license = ""
repository = ""
default-run = "CS工具箱"
edition = "2021"
rust-version = "1.66"
rust-version = "1.85"
[profile.release]
panic = "abort" # Strip expensive panic clean-up logic
@@ -21,6 +21,7 @@ strip = true # Remove debug symbols
tauri-build = { version = "2.0.6", features = [] }
[dependencies]
log = "0.4.26"
serde_json = "1.0.140"
serde = { version = "1.0.219", features = ["derive"] }
tauri = { version = "2.3.1", features = [ "macos-private-api",
@@ -41,6 +42,7 @@ tauri-plugin-system-info = "2.0.9"
tauri-plugin-theme = "2.1.3"
tauri-plugin-single-instance = { version = "2.0.0", features = ["deep-link"] }
tauri-plugin-deep-link = "2.0.0"
anyhow = "1.0.97"
[target.'cfg(windows)'.dependencies] # Windows Only
winreg = "0.55.0"

View File

@@ -1,39 +1,63 @@
use crate::steam;
use crate::tool::*;
use crate::wrap_err;
use anyhow::Result;
// pub type Result<T, String = ()> = Result<T, String>;
#[tauri::command]
pub fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
pub fn greet(name: &str) -> Result<String, String> {
Ok(format!("Hello, {}! You've been greeted from Rust!", name))
}
// 工具
#[tauri::command]
pub fn launch_game(steam_path: &str, launch_option: &str, server: &str) -> String {
steam::launch_game(steam_path, launch_option, server).expect("启动失败");
pub fn launch_game(steam_path: &str, launch_option: &str, server: &str) -> Result<String, String> {
wrap_err!(steam::launch_game(steam_path, launch_option, server));
format!(
Ok(format!(
"Launching game on server: {}, with launch Option {}",
server, launch_option
)
))
}
#[tauri::command]
pub fn kill_game() -> String {
common::kill("cs2.exe")
pub fn kill_game() -> Result<String, String> {
Ok(common::kill("cs2.exe"))
}
#[tauri::command]
pub fn kill_steam() -> String {
common::kill("steam.exe")
pub fn kill_steam() -> Result<String, String> {
Ok(common::kill("steam.exe"))
}
// Steam
#[tauri::command]
pub fn get_steam_path() -> String {
steam::path::get_steam_path().expect("获取Steam路径失败")
pub fn get_steam_path() -> Result<String, String> {
wrap_err!(steam::path::get_steam_path())
}
#[tauri::command]
pub fn get_cs_path(name: &str) -> Result<String, String> {
wrap_err!(steam::path::get_cs_path(name))
}
#[tauri::command]
pub fn get_powerplan() -> Result<String, String> {
#[cfg(target_os = "windows")]
let powerplan = powerplan::get_powerplan()?;
Ok(powerplan)
}
#[tauri::command]
pub fn set_powerplan(plan: &str) -> Result<String, String> {
#[cfg(target_os = "windows")]
powerplan::set_powerplan(plan)?;
Ok(format!("Set powerplan to {}", plan))
}
// TODO get_cs_path
// TODO get_powerplan
// TODO set_powerplan
@@ -44,14 +68,14 @@ pub fn get_steam_path() -> String {
// TODO fs_watch_dir
#[tauri::command]
pub fn set_auto_login_user(user: &str) -> String {
pub fn set_auto_login_user(user: &str) -> Result<String, String> {
#[cfg(target_os = "windows")]
steam::reg::set_auto_login_user(user).expect("设置自动登录用户失败");
steam::reg::set_auto_login_user(user)?;
format!("Set auto login user to {}", user)
Ok(format!("Set auto login user to {}", user))
}
#[tauri::command]
pub fn check_path(path: &str) -> bool {
std::path::Path::new(&path).exists()
pub fn check_path(path: &str) -> Result<bool, String> {
Ok(std::path::Path::new(&path).exists())
}

View File

@@ -92,6 +92,9 @@ fn main() {
cmds::kill_game,
cmds::kill_steam,
cmds::get_steam_path,
cmds::get_cs_path,
cmds::get_powerplan,
cmds::set_powerplan,
cmds::set_auto_login_user,
cmds::check_path,
on_button_clicked

View File

@@ -4,6 +4,7 @@ pub mod path;
pub mod reg;
// common steam utils
use anyhow::Result;
use std::error::Error;
use std::process::{Command, Output};

View File

@@ -3,11 +3,12 @@
// - CS2(CS:GO) Path
#![allow(unused)]
use anyhow::Result;
use crate::tool::common::get_exe_path;
use super::reg;
pub fn get_steam_path<'a>() -> Result<String, &'a str> {
pub fn get_steam_path() -> Result<String, String> {
// Windows Registry
#[cfg(target_os = "windows")]
if let Ok(reg) = reg::SteamReg::get_all() {
@@ -20,12 +21,12 @@ pub fn get_steam_path<'a>() -> Result<String, &'a str> {
return Ok(steam_path);
}
Err("no steam path found")
Err("no steam path found".into())
}
pub fn get_cs_path<'a>(name: &str) -> Result<String, &'a str> {
if name != "csgo" || name != "cs2" {
return Err("invalid cs name");
pub fn get_cs_path(name: &str) -> Result<String, String> {
if name != "csgo" && name != "cs2" {
return Err("invalid cs name".into());
}
#[cfg(target_os = "windows")]
@@ -33,7 +34,7 @@ pub fn get_cs_path<'a>(name: &str) -> Result<String, &'a str> {
return Ok(cs_path);
}
Err("no cs path found")
Err("no cs path found".into())
}
#[cfg(test)]

View File

@@ -29,7 +29,7 @@ impl SteamReg {
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_ver = hkcu.open_subkey(STEAM_REG).expect("steam reg");
let steam_path: String = cur_ver.get_value("SteamExe").expect("steam path");
let steam_path: String = cur_ver.get_value("SteamPath").expect("steam path");
let auto_login_user: String = cur_ver.get_value("AutoLoginUser").expect("auto login user");
let suppress_auto_run: u32 = cur_ver
.get_value("SuppressAutoRun")
@@ -39,12 +39,12 @@ impl SteamReg {
.expect("remember password");
let language: String = cur_ver.get_value("Language").expect("language");
let users = cur_ver
.open_subkey("Users")
.expect("users")
.enum_keys()
.map(|x| x.unwrap().to_string())
.collect::<Vec<String>>();
// let users = cur_ver
// .open_subkey("Users")
// .expect("users")
// .enum_keys()
// .map(|x| x.unwrap().to_string())
// .collect::<Vec<String>>();
Ok(Self {
steam_path,
@@ -52,7 +52,7 @@ impl SteamReg {
suppress_auto_run,
remember_password,
language,
users: users,
users: vec![],
})
}
}

View File

@@ -36,9 +36,10 @@ macro_rules! wrap_err {
match $stat {
Ok(a) => Ok(a),
Err(err) => {
log::error!(target: "app", "{}", err.to_string());
Err(format!("{}", err.to_string()))
let err_str = err.to_string();
log::error!(target: "app", "{}", err_str);
Err(err_str)
}
}
};
}
}

View File

@@ -1,2 +1,3 @@
pub mod common;
pub mod macros;
pub mod powerplan;

View File

@@ -0,0 +1,8 @@
pub fn get_powerplan<'a>() -> Result<String, &'a str> {
Ok(String::from(""))
}
pub fn set_powerplan<'a>(plan: &str) -> Result<String, &'a str> {
println!("{}", plan);
Ok(String::from(""))
}

View File

@@ -85,6 +85,22 @@ export function Prepare() {
}
}
const autoGetPaths = async () => {
try {
const steam_path = await invoke<string>("get_steam_path")
if (steam_path) steam.setDir(steam_path)
} catch (e) {
addToast({ title: "自动获取Steam路径失败", color: "danger" })
}
try {
const cs2_path = await invoke<string>("get_cs_path", { name: "cs2" })
if (cs2_path) steam.setCsDir(cs2_path.replace(/\\[^\\]+$/, ""))
} catch (e) {
addToast({ title: "自动获取CS2路径失败", color: "danger" })
}
}
const handleSelectCs2Dir = async () => {
const selected = await open({
title: "选择 CS2.exe 文件",
@@ -147,7 +163,7 @@ export function Prepare() {
{links.length > 0 && <p className="text-white">{links}</p>}
<section className="flex justify-center w-full gap-3 mt-6">
<Button onPress={() => alert("获取")} variant="ghost" color="default" size="sm">
<Button onPress={() => void autoGetPaths()} variant="ghost" color="default" size="sm">
</Button>
<Button

View File

@@ -2,7 +2,7 @@
import { setTheme as setTauriTheme } from "@/hooks/tauri/theme"
import { useAppStore } from "@/store/app"
import { useToolStore } from "@/store/tool"
import { addToast } from "@heroui/react"
import { addToast, Button, useDisclosure } from "@heroui/react"
import { Close, Minus, Moon, Refresh, RocketOne, Square, SunOne } from "@icon-park/react"
import { type Theme, getCurrentWindow } from "@tauri-apps/api/window"
import { /* relaunch, */ exit } from "@tauri-apps/plugin-process"
@@ -10,11 +10,9 @@ import { useTheme } from "next-themes"
import { usePathname, useRouter } from "next/navigation"
import { saveAllNow } from "@tauri-store/valtio"
import { useSteamStore } from "@/store/steam"
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter } from "@heroui/react"
const Nav = () => {
const app = useAppStore()
const tool = useToolStore()
const steam = useSteamStore()
const { theme, setTheme } = useTheme()
const setAppTheme = async (theme: Theme) => {
setTheme(theme)
@@ -46,23 +44,7 @@ const Nav = () => {
return (
<nav className="absolute top-0 right-0 flex flex-row h-16 gap-0.5 p-4" data-tauri-drag-region>
<button
type="button"
className="px-2 py-0 transition duration-150 rounded hover:bg-zinc-200/80 dark:hover:bg-zinc-100/10 active:scale-95"
onClick={() => {
app.resetAppStore()
tool.resetToolStore()
steam.resetSteamStore()
addToast({
title: "重置成功",
color: "success",
// description: "已重置所有设置",
})
router.push("/")
}}
>
<Refresh size={16} />
</button>
<ResetModal />
{pathname !== "/" && (
<button
@@ -111,4 +93,64 @@ const Nav = () => {
)
}
function ResetModal() {
const app = useAppStore()
const tool = useToolStore()
const steam = useSteamStore()
const router = useRouter()
const { isOpen, onOpen, onOpenChange } = useDisclosure()
function reset() {
app.resetAppStore()
tool.resetToolStore()
steam.resetSteamStore()
addToast({
title: "重置成功",
color: "success",
// description: "已重置所有设置",
})
router.push("/")
}
return (
<>
<button
type="button"
className="px-2 py-0 transition duration-150 rounded hover:bg-zinc-200/80 dark:hover:bg-zinc-100/10 active:scale-95"
onClick={onOpen}
>
<Refresh size={16} />
</button>
<Modal isOpen={isOpen} onOpenChange={onOpenChange}>
<ModalContent>
{(onClose) => (
<>
<ModalHeader className="flex flex-col gap-1"></ModalHeader>
<ModalBody>
<p>
CS工具箱的偏好设置为默认设置
</p>
</ModalBody>
<ModalFooter>
<Button color="danger" variant="light" onPress={onClose}>
</Button>
<Button
color="primary"
onPress={() => {
reset()
onClose()
}}
>
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
</>
)
}
export default Nav