🐛 修复重启异常

This commit is contained in:
BTMuli
2025-12-02 11:37:37 +08:00
parent 1d204c8284
commit b267599039
8 changed files with 102 additions and 66 deletions

View File

@@ -136,29 +136,44 @@ pub fn run_with_admin() -> Result<(), String> {
use std::ffi::OsStr;
use std::iter::once;
use std::os::windows::ffi::OsStrExt;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::HWND;
use windows_sys::Win32::UI::Shell::ShellExecuteW;
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
fn to_wide(s: &OsStr) -> Vec<u16> {
s.encode_wide().chain(once(0)).collect()
}
let exe_path = std::env::current_exe().map_err(|e| e.to_string())?;
let exe_str: Vec<u16> = exe_path.as_os_str().encode_wide().chain(once(0)).collect();
let verb: Vec<u16> = OsStr::new("runas").encode_wide().chain(once(0)).collect();
let workdir: Vec<u16> =
exe_path.parent().unwrap().as_os_str().encode_wide().chain(once(0)).collect();
if !exe_path.exists() {
return Err(format!("executable not found: {}", exe_path.display()));
}
let elevated_arg = "--elevated-action=post_install";
// /C start "" "<full_path>" --elevated-action=post_install
let params = format!("/C start \"\" \"{}\" {}", exe_path.display(), elevated_arg);
let cmd_w = to_wide(OsStr::new("cmd.exe"));
let verb_w = to_wide(OsStr::new("runas"));
let params_w = to_wide(OsStr::new(&params));
let workdir_w =
exe_path.parent().map(|p| to_wide(p.as_os_str())).unwrap_or_else(|| to_wide(OsStr::new("")));
unsafe {
let result = ShellExecuteW(
0 as HWND,
verb.as_ptr(),
exe_str.as_ptr(),
std::ptr::null(),
workdir.as_ptr(),
verb_w.as_ptr(),
cmd_w.as_ptr(),
params_w.as_ptr(),
if workdir_w.len() > 1 { workdir_w.as_ptr() } else { null_mut() },
SW_SHOWNORMAL,
);
if result as usize > 32 {
std::process::exit(0);
if (result as usize) > 32 {
Ok(())
} else {
Err("Failed to restart as administrator.".into())
Err("Failed to restart as administrator via cmd.".into())
}
}
}

View File

@@ -1,6 +1,5 @@
//! @file src/plugins.rs
//! @desc 插件模块,用于注册插件
//! @since Beta v0.6.2
//! 插件模块,用于注册插件
//! @since Beta v0.7.8
use crate::utils::get_current_date;
use log::LevelFilter;
@@ -11,7 +10,29 @@ use tauri_plugin_single_instance::init;
// 单例插件
pub fn build_si_plugin<R: Runtime>() -> TauriPlugin<R> {
init(move |app, argv, _cwd| app.emit("active_deep_link", argv).unwrap())
init(move |app, argv, _cwd| {
// 把 argv 转成 Vec<String>
let args: Vec<String> = argv.iter().map(|s| s.to_string()).collect();
// 如果包含提升约定参数,发出专门事件并短路退出
if args.iter().any(|a| a.starts_with("--elevated-action"))
|| args.iter().any(|a| a == "--elevated")
{
if let Err(e) = app.emit("elevated_launch", args.clone()) {
// 记录错误但不要 panic
eprintln!("emit elevated_launch failed: {}", e);
}
// 提升实例通常只负责传参或执行一次性任务,退出避免与主实例冲突
std::process::exit(0);
}
// 非提升启动:按原逻辑广播 deep link
if let Err(e) = app.emit("active_deep_link", argv) {
eprintln!("emit active_deep_link failed: {}", e);
}
// 回调必须返回 unit直接结束即可
})
}
// 日志插件