1use std::path::Path;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::Mutex;
22
23use agentmux_common::quit_question::{ask_srv, goes_ahead};
24#[cfg(any(target_os = "windows", target_os = "linux"))]
25use agentmux_common::quit_question::DIALOG_TITLE;
26#[cfg(target_os = "linux")]
27use agentmux_common::quit_question::{KEEP_RUNNING, QUIT};
28
29static SRV: Mutex<Option<(String, String)>> = Mutex::new(None);
31
32pub fn srv_is_at(web_endpoint: &str, auth_key: &str) {
34 *SRV.lock().unwrap_or_else(|e| e.into_inner()) = Some((web_endpoint.to_string(), auth_key.to_string()));
35}
36
37pub fn quit_from_tray(data_dir: &Path, dir_hash: &str) {
40 static ASKING: AtomicBool = AtomicBool::new(false);
41 if ASKING.swap(true, Ordering::SeqCst) {
42 crate::log("quit: already asking about a quit");
43 return;
44 }
45 let (dir, hash) = (data_dir.to_path_buf(), dir_hash.to_string());
46 let spawned = std::thread::Builder::new().name("agentmux-quit-ask".into()).spawn(move || {
47 let srv = SRV.lock().unwrap_or_else(|e| e.into_inner()).clone();
48 let question = srv.and_then(|(endpoint, key)| ask_srv(&endpoint, &key));
49 if let Some(q) = &question {
50 crate::log(&format!("quit: {} of {} agents working; asking", q.working.len(), q.agents));
51 }
52 let go = goes_ahead(question.as_ref(), confirm);
53 ASKING.store(false, Ordering::SeqCst);
54 if go {
55 crate::host_quit::quit_host(&dir, &hash);
56 } else {
57 crate::log("quit: the person chose to keep running");
58 }
59 });
60 if spawned.is_err() {
61 ASKING.store(false, Ordering::SeqCst);
62 crate::host_quit::quit_host(data_dir, dir_hash);
63 }
64}
65
66#[cfg(target_os = "windows")]
69fn confirm(body: &str) -> Option<bool> {
70 use std::os::windows::ffi::OsStrExt;
71 use windows_sys::Win32::UI::WindowsAndMessaging::{
72 MessageBoxW, IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_SETFOREGROUND, MB_TOPMOST, MB_YESNO,
73 };
74 let wide = |s: &str| std::ffi::OsStr::new(s).encode_wide().chain(Some(0)).collect::<Vec<u16>>();
75 let (title, body) = (wide(DIALOG_TITLE), wide(body));
76 let answer = unsafe {
78 MessageBoxW(
79 std::ptr::null_mut(),
80 body.as_ptr(),
81 title.as_ptr(),
82 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2 | MB_SETFOREGROUND | MB_TOPMOST,
83 )
84 };
85 (answer != 0).then_some(answer == IDYES)
86}
87
88#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
93fn linux_answer(exit_code: Option<i32>, stderr: &str) -> Option<bool> {
94 const NO_DISPLAY: [&str; 5] = ["open display", "connect to display", "x display", "wl_display", "init server"];
96 let said = stderr.to_ascii_lowercase();
97 match exit_code {
98 Some(0) => Some(true),
99 Some(1) if !NO_DISPLAY.iter().any(|phrase| said.contains(phrase)) => Some(false),
100 _ => None,
101 }
102}
103
104#[cfg(target_os = "linux")]
107fn confirm(body: &str) -> Option<bool> {
108 let zenity_title = format!("--title={DIALOG_TITLE}");
109 let zenity_text = format!("--text={}", crate::upgrade_linux::pango_escape(body));
110 let zenity_ok = format!("--ok-label={QUIT}");
111 let zenity_cancel = format!("--cancel-label={KEEP_RUNNING}");
112 let dialogs: [(&str, Vec<&str>); 2] = [
113 ("zenity", vec!["--question", &zenity_title, &zenity_text, &zenity_ok, &zenity_cancel, "--default-cancel", "--width=460"]),
114 ("kdialog", vec!["--title", DIALOG_TITLE, "--yes-label", QUIT, "--no-label", KEEP_RUNNING, "--warningyesno", body]),
115 ];
116 for (program, args) in dialogs {
117 let mut cmd = std::process::Command::new(program);
118 cmd.args(&args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null());
119 for key in crate::upgrade_linux::NOT_INHERITED {
121 cmd.env_remove(key);
122 }
123 cmd.stderr(std::process::Stdio::piped());
124 match cmd.output() {
125 Ok(out) => {
126 let answer = linux_answer(out.status.code(), &String::from_utf8_lossy(&out.stderr));
127 if answer.is_none() {
128 crate::log(&format!("quit: {program} did not show the question ({}); quitting", out.status));
129 }
130 return answer;
131 }
132 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
133 Err(e) => {
134 crate::log(&format!("quit: couldn't open {program} to ask: {e}"));
135 return None;
136 }
137 }
138 }
139 crate::log("quit: neither zenity nor kdialog is installed to ask with");
140 None
141}
142
143#[cfg(target_os = "macos")]
145fn confirm(body: &str) -> Option<bool> {
146 match agentmux_common::quit_question::confirm_macos(body) {
147 Ok(answer) => Some(answer),
148 Err(why) => {
149 crate::log(&format!("quit: {why}; quitting"));
150 None
151 }
152 }
153}
154
155#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
156fn confirm(_body: &str) -> Option<bool> {
157 None
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
165 fn a_dialog_that_failed_is_not_an_answer_to_keep_running() {
166 assert_eq!(linux_answer(Some(0), ""), Some(true));
168 assert_eq!(linux_answer(Some(1), ""), Some(false));
169 assert_eq!(linux_answer(Some(1), "Gtk-Message: GtkDialog mapped without a transient parent"), Some(false));
170 assert_eq!(linux_answer(Some(1), "(zenity:4242): Gtk-WARNING **: cannot open display: "), None);
172 assert_eq!(linux_answer(Some(1), "qt.qpa.xcb: could not connect to display"), None);
173 assert_eq!(linux_answer(Some(5), ""), None, "zenity's timeout");
174 assert_eq!(linux_answer(Some(255), ""), None);
175 assert_eq!(linux_answer(None, ""), None, "ended by a signal");
176 }
177}