From e8b82007c223c062b1e21e212c0522fa45af41d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=91=E5=85=88=E6=A3=AE?= Date: Tue, 3 Dec 2024 16:08:59 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8D=E5=86=8D=E5=85=BC=E5=AE=B9=E5=8E=9Fau?= =?UTF-8?q?tostart=E5=BA=93-=E7=A7=BB=E9=99=A4autostart=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将开机自启检测使用plugins-cli进行判断 修复创建窗口后多次触发监听的情况 --- composables/windows.ts | 18 +++-- pages/index.vue | 53 +++----------- src-tauri/Cargo.lock | 110 ++++++++++++++++++++++++++++ src-tauri/Cargo.toml | 2 + src-tauri/capabilities/default.json | 4 + src-tauri/capabilities/desktop.json | 14 ++++ src-tauri/src/lib.rs | 28 ++++--- src-tauri/tauri.conf.json | 12 ++- 8 files changed, 177 insertions(+), 64 deletions(-) create mode 100644 src-tauri/capabilities/desktop.json diff --git a/composables/windows.ts b/composables/windows.ts index df382f7..0b8d77c 100644 --- a/composables/windows.ts +++ b/composables/windows.ts @@ -2,17 +2,20 @@ import { type UnlistenFn } from "@tauri-apps/api/event"; import { getCurrentWindow, PhysicalPosition, type WindowOptions, Window, currentMonitor } from "@tauri-apps/api/window"; import { WebviewWindow } from "@tauri-apps/api/webviewWindow"; import type { WebviewLabel, WebviewOptions } from "@tauri-apps/api/webview"; + +const _listenersMaps: { [key: string]: [UnlistenFn | null, UnlistenFn | null] } = {}; + export default async ( label: WebviewLabel, options?: Omit & WindowOptions, afterCreatedFunc?: (webviewWindow: WebviewWindow, appWindow: Window) => void | null, beforeCloseFunc?: () => void | null ) => { - let unListenlogClose: UnlistenFn | null = null; - let unlistenLogCreated: UnlistenFn | null = null; + const unlistenFnList: [UnlistenFn | null, UnlistenFn | null] = _listenersMaps[label] || [null, null]; + let [unlistenLogCreated, unListenlogClose] = unlistenFnList; let dialog = await WebviewWindow.getByLabel(label); if (!dialog) { - let defaultOpts: {[key:string]: any, parent: Window | undefined} = { + let defaultOpts: { [key: string]: any; parent: Window | undefined } = { parent: undefined, closable: true, resizable: true, @@ -25,17 +28,16 @@ export default async ( const appWindow = getCurrentWindow(); if (appWindow) { const appSize = await appWindow.outerSize(); - // const monitor = await currentMonitor(); - // console.error(monitor) const factor = await appWindow.scaleFactor(); const appPosition = await appWindow.outerPosition(); - // console.error((appPosition.x + appSize.width) / 1.25); const logicalPosition = new PhysicalPosition(appPosition.x + appSize.width, appPosition.y).toLogical(factor); defaultOpts.parent = appWindow; // console.error(logicalPosition); defaultOpts.x = logicalPosition.x; defaultOpts.y = logicalPosition.y; } + unlistenLogCreated && (await (unlistenLogCreated as Function)()); + unListenlogClose && (await unListenlogClose()); dialog = new WebviewWindow(label, { ...defaultOpts, ...options }); unlistenLogCreated = await dialog.listen("tauri://webview-created", async () => { if (dialog) { @@ -43,10 +45,14 @@ export default async ( await dialog.show(); } }); + unlistenFnList[0] = unlistenLogCreated; unListenlogClose = await dialog.onCloseRequested(async () => { beforeCloseFunc && (await beforeCloseFunc()); unListenlogClose && (await unListenlogClose()); + unlistenLogCreated && (await (unlistenLogCreated as Function)()); }); + unlistenFnList[1] = unlistenLogCreated; + _listenersMaps[label] = unlistenFnList; } else { const visible = await dialog.isVisible(); if (visible) { diff --git a/pages/index.vue b/pages/index.vue index 548f481..0792f8b 100644 --- a/pages/index.vue +++ b/pages/index.vue @@ -510,13 +510,13 @@ } from "@element-plus/icons-vue"; import { reactive, onBeforeUnmount, onMounted, ref } from "vue"; import { useTray, setTrayRunState, setTrayTooltip } from "~/composables/tray"; + import { getMatches } from '@tauri-apps/plugin-cli'; import { initStartWinIpBroadcast } from "~/composables/netcard"; import useMainStore from "@/stores/index"; import { ElMessage, ElMessageBox } from "element-plus"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { getAllWebviewWindows } from "@tauri-apps/api/webviewWindow"; import etWindows from "@/composables/windows"; - import * as tauriAutoStart from "@tauri-apps/plugin-autostart"; import { resourceDir as getResourceDir, join } from "@tauri-apps/api/path"; import { readDir, exists, mkdir, BaseDirectory, readTextFile } from "@tauri-apps/plugin-fs"; import { updateConfigJson } from "~/composables/configJson"; @@ -844,42 +844,6 @@ // console.log(data.releaseList); }; - const handleAutoStart = async () => { - let is_enable = await tauriAutoStart.isEnabled(); - if (!config.autoStart && !is_enable) { - try { - await tauriAutoStart.enable(); - } catch (err) { - ElMessage.error(`开机自启失败`); - } - } else { - try { - await tauriAutoStart.disable(); - } catch (err) { - // ElMessage.error(`取消自启失败`); - } - } - is_enable = await tauriAutoStart.isEnabled(); - if (!is_enable) { - config.autoStart = false; - } else { - config.autoStart = true; - } - }; - - const initAutoStart = async () => { - try { - const is_enable = await tauriAutoStart.isEnabled(); - if (!is_enable) { - config.autoStart = false; - } else { - config.autoStart = true; - } - } catch (err) { - config.autoStart = false; - } - }; - const handleAutoStartByTask = async () => { await invoke("spawn_autostart", { enabled: !config.autoStart }); const is_enable_by_task = (await invoke("autostart_is_enabled")) as boolean; @@ -888,11 +852,6 @@ const compatibleInitAutoStart = async () => { try { - const is_enable = await tauriAutoStart.isEnabled(); - if (is_enable) { - await invoke("spawn_autostart", { enabled: true }); - await tauriAutoStart.disable(); - } let is_enable_by_task = (await invoke("autostart_is_enabled")) as boolean; if (is_enable_by_task) { // 每次打开Exe重新加载一次开机自启,因为可能路径变了 @@ -984,6 +943,15 @@ } }; + const mountedShow = async () => { + const args = await getMatches(); + if(!args.args?.['task-auto-start']?.value) { + const appWindow = getCurrentWindow(); + await appWindow.show(); + await appWindow.setFocus(); + } + } + let logsTimer: NodeJS.Timeout | null = null; let serverLogsTimer: NodeJS.Timeout | null = null; @@ -1000,6 +968,7 @@ await initConfigDir(); await initAutoStartServer(); await initConnectAfterStart(); + mountedShow(); // 不需要await closePrevent(); }); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f7b2c35..e4d60af 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -95,6 +95,55 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "0.6.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" + +[[package]] +name = "anstyle-parse" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" +dependencies = [ + "anstyle", + "windows-sys 0.59.0", +] + [[package]] name = "anyhow" version = "1.0.92" @@ -692,6 +741,33 @@ dependencies = [ "inout", ] +[[package]] +name = "clap" +version = "4.5.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.5.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" + [[package]] name = "clipboard-win" version = "5.4.0" @@ -731,6 +807,12 @@ dependencies = [ "objc", ] +[[package]] +name = "colorchoice" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" + [[package]] name = "combine" version = "4.6.7" @@ -1187,6 +1269,7 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-autostart", + "tauri-plugin-cli", "tauri-plugin-clipboard-manager", "tauri-plugin-fs", "tauri-plugin-log", @@ -2165,6 +2248,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + [[package]] name = "itoa" version = "0.4.8" @@ -4451,6 +4540,21 @@ dependencies = [ "thiserror 1.0.64", ] +[[package]] +name = "tauri-plugin-cli" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bccd4692b56822a60874542c7655546c8e7aed3c2e2926166e1498e595bd2a2" +dependencies = [ + "clap", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 1.0.64", +] + [[package]] name = "tauri-plugin-clipboard-manager" version = "2.0.2" @@ -5087,6 +5191,12 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.10.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7409022..33db545 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -44,11 +44,13 @@ tokio = { version = "1.41.1", features = ["process"] } # prost = "0.13" # prost-types = "0.13" + [dependencies.windows] version = "0.58.0" features = ["Win32_System_TaskScheduler"] [target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies] tauri-plugin-autostart = "2.0.1" +tauri-plugin-cli = "2" tauri-plugin-single-instance = "2.0.1" tauri-plugin-window-state = "2" diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 59c9aca..18899c0 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -97,6 +97,10 @@ "window-state:allow-save-window-state", "window-state:allow-restore-state", + + "cli:default", + "cli:allow-cli-matches", + "log:default", "log:allow-log" ] diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.json new file mode 100644 index 0000000..a33e9fd --- /dev/null +++ b/src-tauri/capabilities/desktop.json @@ -0,0 +1,14 @@ +{ + "identifier": "desktop-capability", + "platforms": [ + "macOS", + "windows", + "linux" + ], + "windows": [ + "main" + ], + "permissions": [ + "cli:default" + ] +} \ No newline at end of file diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8a62158..afa0af4 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -138,13 +138,14 @@ async fn get_members_by_cli() -> String { .arg("peer") .arg("list") .creation_flags(0x08000000) - .output().await + .output() + .await { Ok(output) => { if output.status.success() { let output_str = String::from_utf8_lossy(&output.stdout); return output_str.trim().to_string(); - }else { + } else { let output_str = String::from_utf8_lossy(&output.stderr); log::error!("{}", output_str.trim().to_string()); return "_EasytierGameCliFailedToConnect_".to_string(); @@ -153,7 +154,7 @@ async fn get_members_by_cli() -> String { Err(_e) => { log::error!("get member list error"); return "".to_string(); - }, + } } } @@ -482,7 +483,7 @@ fn autostart_is_enabled() -> bool { } } -pub const AUTOSTART_ARG: &str = "--autostart"; +// pub const AUTOSTART_ARG: &str = "--autostart"; pub const TASKAUTOSTART_ARG: &str = "--task-auto-start"; fn autostart(enabled: bool) -> std::result::Result<(), Box> { if !enabled { @@ -550,10 +551,11 @@ fn autostart(enabled: bool) -> std::result::Result<(), Box = std::env::args().collect(); + let _args: Vec = std::env::args().collect(); let context = tauri::generate_context!(); tauri::Builder::default() + .plugin(tauri_plugin_cli::init()) .plugin( tauri_plugin_window_state::Builder::new() .with_state_flags(tauri_plugin_window_state::StateFlags::SIZE) @@ -561,10 +563,6 @@ pub fn run() { ) .plugin(tauri_plugin_clipboard_manager::init()) .plugin(tauri_plugin_fs::init()) - .plugin(tauri_plugin_autostart::init( - MacosLauncher::LaunchAgent, - Some(vec![AUTOSTART_ARG]), - )) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| { let _ = app @@ -574,7 +572,7 @@ pub fn run() { .expect("failed to set focus"); })) .setup(move |app| { - let args = args.clone(); + // let args = args.clone(); // if cfg!(debug_assertions) { let log_path = get_tool_exe_path(String::from("\\easytier\\guiLogs")); app.handle().plugin( @@ -611,11 +609,11 @@ pub fn run() { .build(app)?; // 开机自启隐藏到托盘或者显示主窗口 - if !args.contains(&String::from(TASKAUTOSTART_ARG)) { - let main_window = app.get_webview_window("main").unwrap(); - main_window.show().expect("failed to show window"); - main_window.set_focus().expect("failed to set focus"); - } + // if !args.contains(&String::from(TASKAUTOSTART_ARG)) { + // let main_window = app.get_webview_window("main").unwrap(); + // main_window.show().expect("failed to show window"); + // main_window.set_focus().expect("failed to set focus"); + // } Ok(()) }) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d391cf9..af3a341 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -34,7 +34,17 @@ "csp": null } }, - "plugins": {}, + "plugins": { + "cli": { + "description": "easytier game CLI Plugin", + "args": [ + { + "name": "task-auto-start", + "description": "easytier game autostart" + } + ] + } + }, "bundle": { "active": false, "targets": "all",