diff --git a/README.md b/README.md index bc771aba..3e84d027 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,11 @@ If you need to migrate data between the desktop app and a source-based deploymen ## FAQ + +### What is the difference between minimizing and closing on Windows? + +Minimizing keeps the window on the taskbar. Closing lets you choose **Minimize to Tray** or **Quit**. If you remember your choice, select **Reset Close Choice** in the tray menu to restore the prompt. + ### Is it suitable for server deployment? diff --git a/README_zh.md b/README_zh.md index 10fe2b40..9e972aec 100644 --- a/README_zh.md +++ b/README_zh.md @@ -90,6 +90,11 @@ AstrBot Desktop 是面向本地桌面使用的 AstrBot 打包发行版。它内 ## 常见问题 + +### Windows 上最小化和关闭有什么区别? + +最小化后仍可从任务栏恢复。点关闭可选择「最小化到托盘」或「退出」;勾选「记住我的选择」后,可以在托盘菜单点「恢复关闭时询问」。 + ### 适合部署在服务器上吗? diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 958e4b3a..b22a27ae 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -36,6 +36,7 @@ windows-sys = { version = "0.59", features = [ "Win32_Foundation", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Threading", + "Win32_UI_Controls", "Win32_UI_WindowsAndMessaging", ] } diff --git a/src-tauri/src/app_runtime.rs b/src-tauri/src/app_runtime.rs index 79e6f0c7..6fa930da 100644 --- a/src-tauri/src/app_runtime.rs +++ b/src-tauri/src/app_runtime.rs @@ -140,54 +140,53 @@ fn configure_plugins(builder: Builder) -> Builder { } fn configure_window_events(builder: Builder) -> Builder { + use app_runtime_events::{MainWindowAction, MainWindowEvent}; + builder.on_window_event(|window, event| { - let is_quitting = window.app_handle().state::().is_quitting(); - let desktop_settings = window.app_handle().state::().get(); - let action = match &event { - WindowEvent::CloseRequested { .. } => app_runtime_events::main_window_action( - window.label(), - is_quitting, - false, - true, - false, - desktop_settings.close_to_tray, - ), - WindowEvent::Focused(false) => app_runtime_events::main_window_action( - window.label(), - is_quitting, - matches!(window.is_minimized(), Ok(true)), - false, - true, - desktop_settings.close_to_tray, + let app_handle = window.app_handle(); + let is_windows = cfg!(windows); + let window_event = match event { + WindowEvent::CloseRequested { .. } => MainWindowEvent::CloseRequested( + app_handle + .state::() + .get() + .close_action(is_windows), ), - _ => app_runtime_events::MainWindowAction::None, + // Do not turn Windows taskbar minimization into tray hiding. + WindowEvent::Focused(false) if !is_windows => MainWindowEvent::FocusLost { + minimized: window.is_minimized().unwrap_or(false), + }, + _ => return, }; + let action = app_runtime_events::main_window_action( + window.label(), + app_handle.state::().is_quitting(), + is_windows, + window_event, + ); match action { - app_runtime_events::MainWindowAction::PreventCloseAndHide => { + MainWindowAction::PreventClose(choice) => { if let WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); + window::actions::apply_close_action(app_handle, choice); } - window::actions::hide_main_window( - window.app_handle(), - DEFAULT_SHELL_LOCALE, - append_desktop_log, - ); } - app_runtime_events::MainWindowAction::PreventCloseAndExit => { + MainWindowAction::ShowClosePrompt => { + #[cfg(windows)] if let WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); + window::close_prompt::show(window); } - lifecycle::events::handle_tray_quit(window.app_handle()); } - app_runtime_events::MainWindowAction::HideIfMinimized => { + MainWindowAction::HideIfMinimized => { window::actions::hide_main_window( window.app_handle(), DEFAULT_SHELL_LOCALE, append_desktop_log, ); } - app_runtime_events::MainWindowAction::None => {} + MainWindowAction::None => {} } }) } diff --git a/src-tauri/src/app_runtime_events.rs b/src-tauri/src/app_runtime_events.rs index 867fc936..4f803cac 100644 --- a/src-tauri/src/app_runtime_events.rs +++ b/src-tauri/src/app_runtime_events.rs @@ -1,13 +1,21 @@ use tauri::{webview::PageLoadEvent, RunEvent}; +use crate::desktop_settings::CloseAction; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum MainWindowAction { None, - PreventCloseAndHide, - PreventCloseAndExit, + PreventClose(CloseAction), + ShowClosePrompt, HideIfMinimized, } +#[derive(Debug, Clone, Copy)] +pub(crate) enum MainWindowEvent { + CloseRequested(Option), + FocusLost { minimized: bool }, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum PageLoadAction { None, @@ -27,30 +35,21 @@ pub(crate) enum RunEventAction { pub(crate) fn main_window_action( window_label: &str, is_quitting: bool, - minimized_on_focus_lost: bool, - is_close_requested: bool, - is_focus_lost: bool, - close_to_tray: bool, + is_windows: bool, + event: MainWindowEvent, ) -> MainWindowAction { - if window_label != "main" { + if window_label != "main" || is_quitting { return MainWindowAction::None; } - if is_close_requested { - return if is_quitting { - MainWindowAction::None - } else if close_to_tray { - MainWindowAction::PreventCloseAndHide - } else { - MainWindowAction::PreventCloseAndExit - }; - } - - if is_focus_lost && minimized_on_focus_lost && !is_quitting { - return MainWindowAction::HideIfMinimized; + match event { + MainWindowEvent::CloseRequested(Some(choice)) => MainWindowAction::PreventClose(choice), + MainWindowEvent::CloseRequested(None) => MainWindowAction::ShowClosePrompt, + MainWindowEvent::FocusLost { minimized: true } if !is_windows => { + MainWindowAction::HideIfMinimized + } + _ => MainWindowAction::None, } - - MainWindowAction::None } pub(crate) fn page_load_action( @@ -94,42 +93,94 @@ pub(crate) fn run_event_action(event: &RunEvent) -> RunEventAction { #[cfg(test)] mod tests { use super::{ - main_window_action, page_load_action, run_event_action, MainWindowAction, PageLoadAction, - RunEventAction, + main_window_action, page_load_action, run_event_action, MainWindowAction, MainWindowEvent, + PageLoadAction, RunEventAction, }; use tauri::{webview::PageLoadEvent, RunEvent}; + use crate::desktop_settings::CloseAction; + #[cfg(target_os = "macos")] use super::reopen_event_action; #[test] fn main_window_action_ignores_non_main_windows() { assert_eq!( - main_window_action("settings", false, false, true, false, true), + main_window_action( + "settings", + false, + false, + MainWindowEvent::CloseRequested(Some(CloseAction::HideToTray)), + ), MainWindowAction::None ); } #[test] fn main_window_action_hides_on_close_when_not_quitting() { + for is_windows in [false, true] { + assert_eq!( + main_window_action( + "main", + false, + is_windows, + MainWindowEvent::CloseRequested(Some(CloseAction::HideToTray)), + ), + MainWindowAction::PreventClose(CloseAction::HideToTray) + ); + } + } + + #[test] + fn main_window_action_exits_when_exit_is_configured() { + for is_windows in [false, true] { + assert_eq!( + main_window_action( + "main", + false, + is_windows, + MainWindowEvent::CloseRequested(Some(CloseAction::Exit)), + ), + MainWindowAction::PreventClose(CloseAction::Exit) + ); + } + } + + #[test] + fn windows_minimized_focus_loss_keeps_the_window_on_the_taskbar() { assert_eq!( - main_window_action("main", false, false, true, false, true), - MainWindowAction::PreventCloseAndHide + main_window_action( + "main", + false, + true, + MainWindowEvent::FocusLost { minimized: true } + ), + MainWindowAction::None ); } #[test] - fn main_window_action_allows_close_when_close_to_tray_is_disabled() { + fn close_without_a_saved_choice_prompts_unless_already_quitting() { + let event = MainWindowEvent::CloseRequested(None); assert_eq!( - main_window_action("main", false, false, true, false, false), - MainWindowAction::PreventCloseAndExit + main_window_action("main", false, true, event), + MainWindowAction::ShowClosePrompt + ); + assert_eq!( + main_window_action("main", true, true, event), + MainWindowAction::None ); } #[test] - fn main_window_action_hides_on_minimized_focus_loss() { + fn non_windows_minimized_focus_loss_still_hides_the_window() { assert_eq!( - main_window_action("main", false, true, false, true, true), + main_window_action( + "main", + false, + false, + MainWindowEvent::FocusLost { minimized: true } + ), MainWindowAction::HideIfMinimized ); } diff --git a/src-tauri/src/app_types.rs b/src-tauri/src/app_types.rs index 0e80c834..d737fe83 100644 --- a/src-tauri/src/app_types.rs +++ b/src-tauri/src/app_types.rs @@ -21,7 +21,10 @@ pub(crate) struct TrayMenuState { pub(crate) restart_backend_item: MenuItem, pub(crate) launch_at_login_item: CheckMenuItem, pub(crate) silent_launch_item: CheckMenuItem, - pub(crate) close_to_tray_item: CheckMenuItem, + #[cfg(not(windows))] + pub(crate) close_behavior_item: CheckMenuItem, + #[cfg(windows)] + pub(crate) close_behavior_item: MenuItem, pub(crate) plugin_ui_extensions_item: CheckMenuItem, pub(crate) clear_plugin_ui_extension_grants_item: MenuItem, pub(crate) quit_item: MenuItem, diff --git a/src-tauri/src/desktop_settings.rs b/src-tauri/src/desktop_settings.rs index 6b3e0bb4..18937d44 100644 --- a/src-tauri/src/desktop_settings.rs +++ b/src-tauri/src/desktop_settings.rs @@ -36,10 +36,27 @@ impl DesktopSettingsCache { pub(crate) enum DesktopSettingKey { LaunchAtLogin, SilentLaunch, + #[cfg(any(not(windows), test))] CloseToTray, PluginUiExtensions, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum CloseAction { + HideToTray, + Exit, +} + +fn deserialize_windows_close_action<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + Ok(serde_json::from_value(Value::deserialize(deserializer)?).ok()) +} + fn default_launch_at_login() -> bool { false } @@ -77,6 +94,13 @@ pub(crate) struct DesktopSettings { pub(crate) silent_launch: bool, #[serde(rename = "closeToTray", default = "default_close_to_tray")] pub(crate) close_to_tray: bool, + #[serde( + rename = "windowsCloseAction", + default, + deserialize_with = "deserialize_windows_close_action", + skip_serializing_if = "Option::is_none" + )] + windows_close_action: Option, #[serde( rename = "pluginUiExtensionsEnabled", default = "default_plugin_ui_extensions_enabled" @@ -98,6 +122,7 @@ impl Default for DesktopSettings { launch_at_login: default_launch_at_login(), silent_launch: default_silent_launch(), close_to_tray: default_close_to_tray(), + windows_close_action: None, plugin_ui_extensions_enabled: default_plugin_ui_extensions_enabled(), plugin_ui_extension_grants: Vec::new(), other: Map::new(), @@ -106,10 +131,21 @@ impl Default for DesktopSettings { } impl DesktopSettings { + pub(crate) fn close_action(&self, is_windows: bool) -> Option { + if is_windows { + self.windows_close_action + } else if self.close_to_tray { + Some(CloseAction::HideToTray) + } else { + Some(CloseAction::Exit) + } + } + fn set(&mut self, key: DesktopSettingKey, value: bool) { match key { DesktopSettingKey::LaunchAtLogin => self.launch_at_login = value, DesktopSettingKey::SilentLaunch => self.silent_launch = value, + #[cfg(any(not(windows), test))] DesktopSettingKey::CloseToTray => self.close_to_tray = value, DesktopSettingKey::PluginUiExtensions => self.plugin_ui_extensions_enabled = value, } @@ -224,6 +260,23 @@ pub(crate) fn write_desktop_setting( packaged_root_dir: Option<&Path>, key: DesktopSettingKey, value: bool, +) -> Result { + update_desktop_settings(packaged_root_dir, |state| state.set(key, value)) +} + +#[cfg(any(windows, test))] +pub(crate) fn write_windows_close_action( + packaged_root_dir: Option<&Path>, + action: Option, +) -> Result { + update_desktop_settings(packaged_root_dir, |state| { + state.windows_close_action = action + }) +} + +fn update_desktop_settings( + packaged_root_dir: Option<&Path>, + update: impl FnOnce(&mut DesktopSettings), ) -> Result { let _state_guard = crate::desktop_state::lock_desktop_state(); let Some(state_path) = crate::desktop_state::resolve_desktop_state_path(packaged_root_dir) @@ -235,7 +288,7 @@ pub(crate) fn write_desktop_setting( }; let mut state = load_state(&state_path)?; - state.set(key, value); + update(&mut state); save_state(&state_path, &state)?; Ok(state) } @@ -350,6 +403,36 @@ mod tests { assert_eq!(DesktopSettings::default(), settings(false, false, true)); } + #[test] + fn windows_close_choice_can_be_remembered_and_reset_without_changing_legacy_settings() { + let _root_guard = EnvVarGuard::clear(crate::ASTRBOT_ROOT_ENV); + let root = tempfile::tempdir().unwrap(); + let path = state_path(root.path()); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, r#"{"closeToTray":false,"locale":"en-US"}"#).unwrap(); + + let read = || read_desktop_settings(Some(root.path())); + assert_eq!(read().close_action(true), None); + assert_eq!(read().close_action(false), Some(CloseAction::Exit)); + + for action in [Some(CloseAction::HideToTray), Some(CloseAction::Exit), None] { + write_windows_close_action(Some(root.path()), action).unwrap(); + let saved = read(); + assert_eq!(saved.close_action(true), action); + assert_eq!(saved.close_action(false), Some(CloseAction::Exit)); + assert_eq!(saved.other["locale"], "en-US"); + } + } + + #[test] + fn invalid_windows_close_choice_prompts_without_resetting_other_settings() { + let settings: DesktopSettings = + serde_json::from_str(r#"{"windowsCloseAction":"unknown","silentLaunch":true}"#) + .unwrap(); + assert_eq!(settings.close_action(true), None); + assert!(settings.silent_launch); + } + #[test] fn read_desktop_settings_maps_camel_case_fields() { let _root_guard = EnvVarGuard::clear(crate::ASTRBOT_ROOT_ENV); diff --git a/src-tauri/src/shell_locale.rs b/src-tauri/src/shell_locale.rs index bb5f7765..de260fee 100644 --- a/src-tauri/src/shell_locale.rs +++ b/src-tauri/src/shell_locale.rs @@ -20,7 +20,7 @@ pub struct ShellTexts { pub tray_restart_backend: &'static str, pub tray_launch_at_login: &'static str, pub tray_silent_launch: &'static str, - pub tray_close_to_tray: &'static str, + pub tray_close_behavior: &'static str, pub tray_plugin_ui_extensions: &'static str, pub tray_clear_plugin_ui_extension_grants: &'static str, pub tray_quit: &'static str, @@ -42,7 +42,11 @@ pub fn shell_texts_for_locale(locale: &str) -> ShellTexts { tray_restart_backend: "Restart Backend", tray_launch_at_login: "Launch at Login", tray_silent_launch: "Silent Launch", - tray_close_to_tray: "Close to Tray", + tray_close_behavior: if cfg!(windows) { + "Reset Close Choice" + } else { + "Close to Tray" + }, tray_plugin_ui_extensions: "Allow Plugin UI Extensions", tray_clear_plugin_ui_extension_grants: "Clear Plugin UI Authorizations", tray_quit: "Quit", @@ -56,7 +60,11 @@ pub fn shell_texts_for_locale(locale: &str) -> ShellTexts { tray_restart_backend: "重启后端", tray_launch_at_login: "开机自启", tray_silent_launch: "静默启动", - tray_close_to_tray: "关闭到托盘", + tray_close_behavior: if cfg!(windows) { + "恢复关闭时询问" + } else { + "关闭到托盘" + }, tray_plugin_ui_extensions: "允许插件界面扩展", tray_clear_plugin_ui_extension_grants: "清除插件界面授权", tray_quit: "退出", @@ -261,7 +269,14 @@ mod tests { assert_eq!(texts.tray_hide, "Hide AstrBot"); assert_eq!(texts.tray_launch_at_login, "Launch at Login"); assert_eq!(texts.tray_silent_launch, "Silent Launch"); - assert_eq!(texts.tray_close_to_tray, "Close to Tray"); + assert_eq!( + texts.tray_close_behavior, + if cfg!(windows) { + "Reset Close Choice" + } else { + "Close to Tray" + } + ); assert_eq!( texts.tray_plugin_ui_extensions, "Allow Plugin UI Extensions" @@ -279,7 +294,14 @@ mod tests { assert_eq!(texts.tray_hide, "隐藏 AstrBot"); assert_eq!(texts.tray_launch_at_login, "开机自启"); assert_eq!(texts.tray_silent_launch, "静默启动"); - assert_eq!(texts.tray_close_to_tray, "关闭到托盘"); + assert_eq!( + texts.tray_close_behavior, + if cfg!(windows) { + "恢复关闭时询问" + } else { + "关闭到托盘" + } + ); assert_eq!(texts.tray_plugin_ui_extensions, "允许插件界面扩展"); assert_eq!( texts.tray_clear_plugin_ui_extension_grants, diff --git a/src-tauri/src/tray/labels.rs b/src-tauri/src/tray/labels.rs index e9c31156..379ff033 100644 --- a/src-tauri/src/tray/labels.rs +++ b/src-tauri/src/tray/labels.rs @@ -105,9 +105,17 @@ pub fn update_tray_menu_labels_with_visibility( actions::TRAY_MENU_SILENT_LAUNCH, &log, ); + #[cfg(windows)] + set_menu_text_safe( + &tray_state.close_behavior_item, + shell_texts.tray_close_behavior, + actions::TRAY_MENU_CLOSE_TO_TRAY, + &log, + ); + #[cfg(not(windows))] set_check_menu_text_safe( - &tray_state.close_to_tray_item, - shell_texts.tray_close_to_tray, + &tray_state.close_behavior_item, + shell_texts.tray_close_behavior, actions::TRAY_MENU_CLOSE_TO_TRAY, &log, ); diff --git a/src-tauri/src/tray/menu_handler.rs b/src-tauri/src/tray/menu_handler.rs index f54bc815..6559cbfc 100644 --- a/src-tauri/src/tray/menu_handler.rs +++ b/src-tauri/src/tray/menu_handler.rs @@ -128,7 +128,8 @@ fn handle_silent_launch_toggle(app_handle: &AppHandle) { ); } -fn handle_close_to_tray_toggle(app_handle: &AppHandle) { +#[cfg(not(windows))] +fn handle_close_behavior_menu_item(app_handle: &AppHandle) { let Some(tray_state) = app_handle.try_state::() else { return; }; @@ -136,11 +137,16 @@ fn handle_close_to_tray_toggle(app_handle: &AppHandle) { app_handle, desktop_settings::DesktopSettingKey::CloseToTray, |settings| (settings.close_to_tray, !settings.close_to_tray), - &tray_state.close_to_tray_item, + &tray_state.close_behavior_item, actions::TRAY_MENU_CLOSE_TO_TRAY, ); } +#[cfg(windows)] +fn handle_close_behavior_menu_item(app_handle: &AppHandle) { + window::close_prompt::reset_choice(app_handle); +} + fn handle_plugin_ui_extensions_toggle(app_handle: &AppHandle) { let Some(tray_state) = app_handle.try_state::() else { return; @@ -231,7 +237,7 @@ pub fn handle_tray_menu_event(app_handle: &AppHandle, menu_id: &str) { } Some(actions::TrayMenuAction::LaunchAtLogin) => handle_launch_at_login_toggle(app_handle), Some(actions::TrayMenuAction::SilentLaunch) => handle_silent_launch_toggle(app_handle), - Some(actions::TrayMenuAction::CloseToTray) => handle_close_to_tray_toggle(app_handle), + Some(actions::TrayMenuAction::CloseToTray) => handle_close_behavior_menu_item(app_handle), Some(actions::TrayMenuAction::PluginUiExtensions) => { handle_plugin_ui_extensions_toggle(app_handle) } diff --git a/src-tauri/src/tray/setup.rs b/src-tauri/src/tray/setup.rs index 49bf34e5..af0cd29c 100644 --- a/src-tauri/src/tray/setup.rs +++ b/src-tauri/src/tray/setup.rs @@ -74,10 +74,20 @@ pub fn setup_tray(app_handle: &AppHandle) -> Result<(), String> { None::<&str>, ) .map_err(|error| format!("Failed to create tray silent launch menu item: {error}"))?; - let close_to_tray_item = CheckMenuItem::with_id( + #[cfg(windows)] + let close_behavior_item = MenuItem::with_id( app_handle, actions::TRAY_MENU_CLOSE_TO_TRAY, - shell_texts.tray_close_to_tray, + shell_texts.tray_close_behavior, + true, + None::<&str>, + ) + .map_err(|error| format!("Failed to create tray reset close choice menu item: {error}"))?; + #[cfg(not(windows))] + let close_behavior_item = CheckMenuItem::with_id( + app_handle, + actions::TRAY_MENU_CLOSE_TO_TRAY, + shell_texts.tray_close_behavior, true, desktop_settings.close_to_tray, None::<&str>, @@ -122,7 +132,7 @@ pub fn setup_tray(app_handle: &AppHandle) -> Result<(), String> { &settings_separator, &launch_at_login_item, &silent_launch_item, - &close_to_tray_item, + &close_behavior_item, &plugin_ui_extensions_item, &clear_plugin_ui_extension_grants_item, &separator, @@ -137,7 +147,7 @@ pub fn setup_tray(app_handle: &AppHandle) -> Result<(), String> { restart_backend_item: restart_backend_item.clone(), launch_at_login_item: launch_at_login_item.clone(), silent_launch_item: silent_launch_item.clone(), - close_to_tray_item: close_to_tray_item.clone(), + close_behavior_item: close_behavior_item.clone(), plugin_ui_extensions_item: plugin_ui_extensions_item.clone(), clear_plugin_ui_extension_grants_item: clear_plugin_ui_extension_grants_item.clone(), quit_item: quit_item.clone(), diff --git a/src-tauri/src/window/actions.rs b/src-tauri/src/window/actions.rs index 1f2f4026..5bcddbb1 100644 --- a/src-tauri/src/window/actions.rs +++ b/src-tauri/src/window/actions.rs @@ -1,6 +1,18 @@ use tauri::{AppHandle, Manager}; -use crate::{tray, window::main_window}; +use crate::{ + append_desktop_log, desktop_settings::CloseAction, lifecycle, tray, window::main_window, + DEFAULT_SHELL_LOCALE, +}; + +pub(crate) fn apply_close_action(app_handle: &AppHandle, choice: CloseAction) { + match choice { + CloseAction::HideToTray => { + hide_main_window(app_handle, DEFAULT_SHELL_LOCALE, append_desktop_log); + } + CloseAction::Exit => lifecycle::events::handle_tray_quit(app_handle), + } +} pub fn show_main_window(app_handle: &AppHandle, default_shell_locale: &'static str, log: F) where diff --git a/src-tauri/src/window/close_prompt.rs b/src-tauri/src/window/close_prompt.rs new file mode 100644 index 00000000..f5359d0c --- /dev/null +++ b/src-tauri/src/window/close_prompt.rs @@ -0,0 +1,164 @@ +use std::{ + mem::{size_of, zeroed}, + ptr::null_mut, + sync::atomic::AtomicBool, +}; + +use tauri::{AppHandle, Manager, Window}; +use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogResult}; +use windows_sys::{ + core::w, + Win32::UI::{ + Controls::{ + TaskDialogIndirect, TASKDIALOGCONFIG, TASKDIALOG_BUTTON, TDF_ALLOW_DIALOG_CANCELLATION, + }, + WindowsAndMessaging::{IDCANCEL, IDNO, IDYES}, + }, +}; + +use crate::{ + app_types::AtomicFlagGuard, + append_desktop_log, + desktop_settings::{self, CloseAction}, + runtime_paths, shell_locale, BackendState, DesktopSettingsCache, DEFAULT_SHELL_LOCALE, +}; + +static PROMPT_OPEN: AtomicBool = AtomicBool::new(false); + +fn is_english() -> bool { + shell_locale::resolve_shell_locale( + DEFAULT_SHELL_LOCALE, + runtime_paths::default_packaged_root_dir(), + ) == "en-US" +} + +fn task_dialog(window: &Window, english: bool) -> Result, String> { + let [question, tray, exit, cancel, remember] = if english { + [ + w!("Close AstrBot?"), + w!("Minimize to Tray"), + w!("Quit"), + w!("Cancel"), + w!("Remember my choice"), + ] + } else { + [ + w!("关闭 AstrBot?"), + w!("最小化到托盘"), + w!("退出"), + w!("取消"), + w!("记住我的选择"), + ] + }; + let buttons = + [(IDYES, tray), (IDNO, exit), (IDCANCEL, cancel)].map(|(id, text)| TASKDIALOG_BUTTON { + nButtonID: id, + pszButtonText: text, + }); + let owner = window.hwnd().map_err(|error| error.to_string())?; + let config = TASKDIALOGCONFIG { + cbSize: size_of::() as u32, + hwndParent: owner.0, + dwFlags: TDF_ALLOW_DIALOG_CANCELLATION, + pszWindowTitle: w!("AstrBot"), + pszMainInstruction: question, + cButtons: buttons.len() as u32, + pButtons: buttons.as_ptr(), + nDefaultButton: IDCANCEL, + pszVerificationText: remember, + // SAFETY: Unused fields are null pointers, zero flags/counts, or an absent callback. + ..unsafe { zeroed() } + }; + let (mut button, mut checked) = (0, 0); + // SAFETY: The owner is a Tauri window and all buffers live through the synchronous call. + // https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-taskdialogindirect + let result = unsafe { TaskDialogIndirect(&config, &mut button, null_mut(), &mut checked) }; + if result < 0 { + return Err(format!("TaskDialogIndirect failed: {result:#010x}")); + } + Ok(match button { + IDYES => Some((CloseAction::HideToTray, checked != 0)), + IDNO => Some((CloseAction::Exit, checked != 0)), + _ => None, + }) +} + +fn save_choice(app: &AppHandle, choice: Option) -> Result<(), String> { + let root = runtime_paths::default_packaged_root_dir(); + app.state::() + .update(|_| desktop_settings::write_windows_close_action(root.as_deref(), choice)) +} + +fn preference_error_text(english: bool) -> &'static str { + if english { + "The close preference could not be saved. Your previous preference is unchanged." + } else { + "无法保存关闭偏好,原有设置未更改。" + } +} + +pub(crate) fn reset_choice(app: &AppHandle) { + if let Err(error) = save_choice(app, None) { + append_desktop_log(&format!("failed to reset Windows close choice: {error}")); + app.dialog() + .message(preference_error_text(is_english())) + .show(|_| {}); + } +} + +pub(crate) fn show(window: &Window) { + let Some(guard) = AtomicFlagGuard::try_set(&PROMPT_OPEN) else { + return; + }; + let window = window.clone(); + // Let the close handler return before the modal dialog starts sending messages to its owner. + tauri::async_runtime::spawn_blocking(move || { + let app = window.app_handle(); + let english = is_english(); + let choice = match task_dialog(&window, english) { + Ok(choice) => choice, + Err(error) => { + append_desktop_log(&format!("failed to show Windows close prompt: {error}")); + let message = if english { + "Minimize AstrBot to the tray? Choose No to quit." + } else { + "将 AstrBot 最小化到托盘?选择「否」退出。" + }; + match app + .dialog() + .message(message) + .parent(&window) + .buttons(MessageDialogButtons::YesNoCancel) + .blocking_show_with_result() + { + MessageDialogResult::Yes => Some((CloseAction::HideToTray, false)), + MessageDialogResult::No => Some((CloseAction::Exit, false)), + _ => None, + } + } + }; + let Some((choice, remember)) = + choice.filter(|_| !app.state::().is_quitting()) + else { + return; + }; + if remember { + if let Err(error) = save_choice(app, Some(choice)) { + append_desktop_log(&format!("failed to remember Windows close choice: {error}")); + app.dialog() + .message(preference_error_text(english)) + .parent(&window) + .blocking_show(); + } + } + let handle = app.clone(); + if let Err(error) = app.run_on_main_thread(move || { + let _guard = guard; + if !handle.state::().is_quitting() { + super::actions::apply_close_action(&handle, choice); + } + }) { + append_desktop_log(&format!("failed to apply Windows close choice: {error}")); + } + }); +} diff --git a/src-tauri/src/window/mod.rs b/src-tauri/src/window/mod.rs index bf143683..3329d169 100644 --- a/src-tauri/src/window/mod.rs +++ b/src-tauri/src/window/mod.rs @@ -1,3 +1,5 @@ pub(crate) mod actions; +#[cfg(windows)] +pub(crate) mod close_prompt; pub(crate) mod main_window; pub(crate) mod startup_loading;