hyprforge_tray/launch.rs
1//! Handing a right-click's menu to `hyprforge-traymenu` and reading back
2//! what was chosen.
3//!
4//! The popup path — see this crate's own module doc for when it is used
5//! and when `com.canonical.dbusmenu` is served instead. The menu
6//! this daemon already builds every poll tick is drawn by a *sibling
7//! process* instead of by whatever bar is running, over the shortest-lived
8//! IPC there is: a pipe to a child this process just spawned. The menu
9//! goes out as JSON on that child's stdin; the chosen row's own
10//! [`crate::menu::MenuItem::action`] string comes back on its stdout, one
11//! line, nothing more — there is no id-indirection to resolve, because
12//! `hyprforge-traymenu` is not a foreign dbusmenu client that could leak
13//! that string anywhere this daemon doesn't already trust.
14//!
15//! Nothing here is awaited from a D-Bus method handler. `sni.rs`'s
16//! `context_menu` spawns the whole sequence below on its own task and
17//! returns immediately — the host that asked for the menu is blocked on
18//! that method call returning, and `hyprforge-traymenu` can sit open for
19//! as long as the user is looking at it. Awaiting it inline would make a
20//! right click hang the bar for exactly that long, and some hosts time a
21//! D-Bus call like that out.
22
23use crate::menu::Menu;
24use std::sync::LazyLock;
25use tokio::io::{AsyncReadExt, AsyncWriteExt};
26use tokio::process::Child;
27use tokio::sync::mpsc::UnboundedSender;
28use tokio::sync::Mutex;
29
30/// Prefix of the event sent just before a menu is handed to
31/// `hyprforge-traymenu`; the item's own id follows, as
32/// `menu:opened:hyprforge-network`.
33///
34/// The popup path's form of `com.canonical.dbusmenu`'s `AboutToShow` —
35/// same purpose, same string, sent by `crate::dbusmenu` on that path, so
36/// the daemon reads one event whichever way a menu was served. `hyprforge-trayd`'s
37/// `handle_menu_clicks` is what actually reads this prefix; see its own
38/// doc for why the Wi-Fi item is the only one anything happens for.
39pub const OPENED_PREFIX: &str = "menu:opened:";
40
41/// The binary this crate looks for on `$PATH`. A parameter of
42/// [`show_with_binary`] rather than a literal there, so a test can point
43/// this whole sequence at something other than the real popup — see this
44/// module's own tests.
45pub(crate) const TRAYMENU_BINARY: &str = "hyprforge-traymenu";
46
47/// The one tray menu that may be open at a time, and the handle that
48/// closes it.
49///
50/// Right-clicking a second icon while the first icon's menu was still
51/// open used to do nothing at all: `hyprforge-traymenu` takes an `flock`
52/// single-instance lock (`hyprforge_popup::singleton`), the second copy
53/// found it held and exited quietly and successfully. That is the right
54/// answer for a keybind pressed twice — which is what the lock was
55/// written for — and the wrong one for a click on a *different* icon,
56/// where the user is asking for a different menu and gets no sign that
57/// they asked for anything. It read as the tray being broken: press
58/// escape, then right click, and only then does the other menu appear.
59///
60/// So this daemon closes the menu it opened before opening another. It
61/// keeps the whole [`Child`] rather than just a pid, because killing is
62/// only half of it: the `flock` is released when the kernel closes the
63/// dead process's descriptors, and a zombie nobody has waited on still
64/// holds them. [`Child::kill`] signals *and* reaps, so when it returns
65/// the lock is genuinely free for the process about to ask for it.
66/// Signalling a bare pid and trusting the owning task to reap it in
67/// time is the version of this that races the new popup's own `acquire`.
68#[derive(Default)]
69pub struct OpenMenu(Mutex<Option<(u32, Child)>>);
70
71/// The slot [`show`] uses. Process-wide because what it models is: there
72/// is one `hyprforge-traymenu` lock per session, so there is one open
73/// menu per daemon, whichever item was clicked. It is a
74/// parameter of [`show_with_binary`] rather than reached for directly,
75/// so tests get their own slot instead of racing each other through
76/// this one.
77static OPEN_MENU: LazyLock<OpenMenu> = LazyLock::new(OpenMenu::default);
78
79/// What became of one attempt to show the menu.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum LaunchOutcome {
82 /// The popup ran to completion (chosen, cancelled, or closed some
83 /// other way) and, if it chose something, that action has already
84 /// been sent to `events`.
85 Spawned,
86 /// `hyprforge-traymenu` is not on `$PATH` — the sibling-binary-absent
87 /// case CLAUDE.md is explicit a daemon must survive: keep running,
88 /// keep every other icon, and let the caller fall back to *something*
89 /// rather than silently doing nothing. `sni.rs::context_menu` is the
90 /// caller, and its fallback is the primary action — the same one a
91 /// left click already runs.
92 NotInstalled,
93 /// The menu couldn't be serialised, the child couldn't be waited on,
94 /// or its stdin couldn't be written. Rare, and not distinguished
95 /// further: every one of them means no popup appeared, so the same
96 /// fallback the caller uses for `NotInstalled` applies here too.
97 Failed,
98}
99
100/// Hands `menu` to `hyprforge-traymenu`, at the icon's own `(x, y)` —
101/// unmodified from whatever the host handed `ItemInterface::context_menu`,
102/// since this function knows nothing about `tray.toml` and no longer
103/// applies `Prefs::menu_y_offset` itself (the popup reads that, and
104/// anchors its own Y to the bar's reserved area — see
105/// `hyprforge_popup::place_below_bar`) — and forwards whatever action it
106/// printed back to `events`.
107///
108/// `id` is only ever used for the [`OPENED_PREFIX`] event, sent before
109/// anything is spawned — the same point in the sequence the old
110/// `about_to_show` fired at, so a Wi-Fi menu's scan-on-open behaviour
111/// (`hyprforge-trayd`'s `scan_then_refresh`) still fires at the moment a
112/// user is about to see the menu, not some other time.
113pub async fn show(id: &str, menu: &Menu, x: i32, y: i32, events: &UnboundedSender<String>) -> LaunchOutcome {
114 show_with_binary(TRAYMENU_BINARY, id, menu, x, y, events, &OPEN_MENU).await
115}
116
117/// [`show`], with the binary to run as a parameter — see
118/// `TRAYMENU_BINARY`'s own doc for why.
119pub async fn show_with_binary(
120 binary: &str,
121 id: &str,
122 menu: &Menu,
123 x: i32,
124 y: i32,
125 events: &UnboundedSender<String>,
126 open: &OpenMenu,
127) -> LaunchOutcome {
128 // Sent unconditionally, before anything can fail below: a menu that
129 // is about to be shown is about to be shown even if the popup then
130 // turns out to be missing, and a Wi-Fi list that never refreshes
131 // because the popup binary is absent is a worse failure than a scan
132 // nobody's about to look at.
133 let _ = events.send(format!("{OPENED_PREFIX}{id}"));
134
135 let json = match serde_json::to_vec(menu) {
136 Ok(json) => json,
137 Err(e) => {
138 // Never a menu label in this line — a serialisation failure
139 // is a shape problem (a signature drift like the one
140 // `dbusmenu.rs` warns about), not something with
141 // content worth naming.
142 tracing::warn!(error = %e, "couldn't serialise the tray menu; not showing it");
143 return LaunchOutcome::Failed;
144 }
145 };
146
147 // Close whatever is already open, and do it *before* spawning: the
148 // new popup refuses to start while another copy holds the lock, so
149 // the order here is the whole fix. Held across the spawn below too,
150 // so two right clicks arriving together cannot both get past this
151 // point and race each other for the lock.
152 let mut guard = open.0.lock().await;
153 if let Some((_, mut previous)) = guard.take() {
154 // A kill, not a polite close: there is no protocol for asking
155 // the popup to go away, and anything it printed on the way out
156 // would arrive here as an action the user never chose.
157 if let Err(e) = previous.kill().await {
158 tracing::warn!(error = %e, "couldn't close the tray menu that was already open");
159 }
160 }
161
162 let mut child = match tokio::process::Command::new(binary)
163 .arg("--x")
164 .arg(x.to_string())
165 .arg("--y")
166 .arg(y.to_string())
167 .stdin(std::process::Stdio::piped())
168 .stdout(std::process::Stdio::piped())
169 // Same reasoning as `spawn_settings` in trayd.rs: a GUI's own
170 // renderer chatter has no business in this daemon's log.
171 .stderr(std::process::Stdio::null())
172 .spawn()
173 {
174 Ok(child) => child,
175 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
176 tracing::warn!(
177 "hyprforge-traymenu is not installed; falling back to the icon's primary action"
178 );
179 return LaunchOutcome::NotInstalled;
180 }
181 Err(e) => {
182 tracing::warn!(error = %e, "couldn't launch hyprforge-traymenu");
183 return LaunchOutcome::Failed;
184 }
185 };
186
187 if let Some(mut stdin) = child.stdin.take() {
188 if let Err(e) = stdin.write_all(&json).await {
189 tracing::warn!(error = %e, "couldn't hand the menu to hyprforge-traymenu");
190 }
191 // `stdin` drops here, closing the pipe — `hyprforge-traymenu`
192 // reads to EOF, so this is what lets it stop waiting for more.
193 }
194
195 // `stdout` is read here rather than through `wait_with_output`,
196 // because the `Child` itself now has somewhere else to be: the slot,
197 // where the *next* right click can reach it. Reading the pipe to EOF
198 // waits for the same thing waiting on the child would — the pipe
199 // closes when the process exits, whether it chose a row, was
200 // cancelled, or was killed by a later click replacing it.
201 let mut stdout = child.stdout.take();
202 let tracked = child.id();
203 match tracked {
204 Some(pid) => *guard = Some((pid, child)),
205 // Only reachable for a child that has already been waited on,
206 // which cannot have happened one statement after spawning it.
207 // Handled rather than unwrapped, and the cost of being wrong is
208 // one menu that a later right click replaces the slow way (the
209 // user pressing escape) rather than a panic in a daemon.
210 None => tracing::warn!("hyprforge-traymenu reported no pid immediately after spawn"),
211 }
212 drop(guard);
213
214 // No bound on this wait: the popup is waiting on a *person*, not on
215 // another program that is supposed to answer quickly — see this
216 // module's own doc for why that is not the same "never wait without
217 // a bound" hazard `hyprforge_core::command::output` guards against.
218 // This runs on its own spawned task (`sni.rs::context_menu`), never on
219 // a D-Bus dispatch path, so however long a user takes costs nothing
220 // this daemon's event loop needs.
221 let mut printed = Vec::new();
222 if let Some(stdout) = stdout.as_mut() {
223 if let Err(e) = stdout.read_to_end(&mut printed).await {
224 tracing::warn!(error = %e, "couldn't read what hyprforge-traymenu chose");
225 return LaunchOutcome::Failed;
226 }
227 }
228
229 // Reap it, but only if it is still the menu that is open. A later
230 // right click may have replaced this one while the read above was
231 // waiting on a person, and that click already killed and reaped it —
232 // matching on the pid is what keeps this from waiting on a child
233 // somebody else has taken responsibility for.
234 if let Some(pid) = tracked {
235 let mut guard = open.0.lock().await;
236 if guard.as_ref().is_some_and(|(open_pid, _)| *open_pid == pid) {
237 if let Some((_, mut child)) = guard.take() {
238 let _ = child.wait().await;
239 }
240 }
241 }
242
243 let action = String::from_utf8_lossy(&printed).trim().to_string();
244 if !action.is_empty() {
245 let _ = events.send(action);
246 }
247 LaunchOutcome::Spawned
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253 use crate::menu::MenuItem;
254
255 fn menu() -> Menu {
256 Menu::new(vec![MenuItem::standard("home", "wifi:connect:home")])
257 }
258
259 /// The fallback path a missing sibling binary has to take — CLAUDE.md
260 /// is explicit that this must be a state with a message, never a
261 /// crash and never silence.
262 #[tokio::test]
263 async fn a_missing_binary_is_reported_as_not_installed_rather_than_panicking() {
264 // See `SPAWNING`: a spawn that finds nothing still forks first,
265 // and that fork is the one the other tests' scripts race.
266 let _spawning = SPAWNING.lock().await;
267 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
268 let outcome =
269 show_with_binary("hyprforge-traymenu-does-not-exist-xyz", "hyprforge-network", &menu(), 10, 20, &tx, &OpenMenu::default())
270 .await;
271 assert_eq!(outcome, LaunchOutcome::NotInstalled);
272 // The opened event still fires even though nothing could be shown.
273 assert_eq!(rx.recv().await.unwrap(), "menu:opened:hyprforge-network");
274 assert!(rx.try_recv().is_err(), "no action was chosen, so nothing else should arrive");
275 }
276
277 /// The plumbing end to end, standing in a tiny throwaway script for
278 /// `hyprforge-traymenu`: whatever a child prints on its stdout must
279 /// reach `events` unchanged, and the JSON handed to its stdin must be
280 /// exactly what was asked to be shown.
281 ///
282 /// Plain `cat` cannot play this part: [`show_with_binary`] always
283 /// passes `--x`/`--y`, and GNU `cat` treats an unrecognised `--x` as
284 /// an error and exits without ever reading stdin — silently, since
285 /// this function nulls the child's stderr the same way
286 /// `spawn_settings` does. That produced empty output rather than an
287 /// echo, which is not a failure this function reports (an empty
288 /// action is a legitimate "nothing was chosen") — it is instead a
289 /// second `rx.recv().await` in *this test* blocking forever on a
290 /// message that was never going to arrive. A `#!/bin/sh -c 'cat'`
291 /// script ignores its own arguments and only ever touches stdin, so
292 /// it echoes regardless of what `--x`/`--y` this test passes.
293 #[tokio::test]
294 async fn whatever_the_child_prints_on_stdout_reaches_the_events_channel() {
295 // See `SPAWNING`: held for the whole body, because the
296 // hazard is a fork anywhere else while this test's script
297 // is still open for writing.
298 let _spawning = SPAWNING.lock().await;
299 let dir = tempfile::tempdir().unwrap();
300 let script = dir.path().join("echo-stdin.sh");
301 std::fs::write(&script, "#!/bin/sh\ncat\n").unwrap();
302 {
303 use std::os::unix::fs::PermissionsExt;
304 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
305 }
306
307 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
308 let outcome =
309 show_with_binary(script.to_str().unwrap(), "hyprforge-network", &menu(), 10, 20, &tx, &OpenMenu::default())
310 .await;
311 assert_eq!(outcome, LaunchOutcome::Spawned);
312
313 assert_eq!(rx.recv().await.unwrap(), "menu:opened:hyprforge-network");
314 let echoed = rx.recv().await.unwrap();
315 let restored: Menu = serde_json::from_str(&echoed).expect("the script must have echoed valid JSON back");
316 assert_eq!(restored, menu(), "the menu handed to stdin must be exactly what was echoed back");
317 }
318
319 /// Serialises "write an executable, then exec it" across the tests
320 /// in this module.
321 ///
322 /// Without it these fail intermittently — measured at 2 runs in 12
323 /// of the whole crate, and never once in 25 runs of the test alone,
324 /// which is the signature of a race with a *sibling* test rather
325 /// than a bug in the test itself.
326 ///
327 /// The race is `ETXTBSY`, and it is a real Unix one rather than
328 /// anything specific to this code. When one thread has an
329 /// executable open for writing and another thread forks, the child
330 /// inherits that open write descriptor; exec of that same file then
331 /// fails with "text file busy". Every test here writes a stand-in
332 /// script and immediately runs it, and `show_with_binary` forks — so
333 /// with more than one running at once, one test's fork can poison
334 /// another test's exec.
335 ///
336 /// *Every* test that spawns takes it, including the one whose binary
337 /// does not exist. A spawn that ends in "not found" still forks
338 /// first, and its child holds a copy of the descriptor table while it
339 /// tries each `$PATH` entry in turn — long enough to be the fork this
340 /// lock is about. That test once went without the lock, because it
341 /// writes no script, and a CI runner caught
342 /// `whatever_the_child_prints_on_stdout_reaches_the_events_channel`
343 /// in that window. Measured in a standalone program: a thread spawning
344 /// a missing binary in a loop made 240 of 2000 write-then-exec runs
345 /// fail with `ETXTBSY`.
346 ///
347 /// A `tokio::sync::Mutex` rather than a `std` one because it is held
348 /// across the `.await` on the child.
349 static SPAWNING: Mutex<()> = Mutex::const_new(());
350
351 /// Writes an executable script and hands back its path. The scripts
352 /// here stand in for `hyprforge-traymenu` — see the test above for
353 /// why plain `cat` cannot play the part.
354 fn script(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
355 use std::os::unix::fs::PermissionsExt;
356 let path = dir.join(name);
357 std::fs::write(&path, body).unwrap();
358 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
359 path
360 }
361
362 /// The bug a user reported as "I have to hit escape first": right
363 /// click the Wi-Fi icon, then right click Bluetooth, and nothing
364 /// happens — the second popup finds the first one's single-instance
365 /// lock held and exits without drawing anything.
366 ///
367 /// The first menu stands in as a script that never exits on its own,
368 /// so the only way this test can finish is the second call actually
369 /// closing it. A `timeout` rather than an unbounded await, because
370 /// the failure this is written against is precisely "the first menu
371 /// stays open forever" — and a test that hangs reports far worse
372 /// than one that fails.
373 #[tokio::test]
374 async fn a_right_click_on_another_icon_replaces_the_menu_already_open() {
375 // See `SPAWNING`: held for the whole body, because the
376 // hazard is a fork anywhere else while this test's script
377 // is still open for writing.
378 let _spawning = SPAWNING.lock().await;
379 let dir = tempfile::tempdir().unwrap();
380 // Reads its stdin away so the write side never blocks, then sits
381 // there holding its stdout open: no EOF, no exit, until killed.
382 // `exec`, so the process that ends up holding that pipe is the
383 // very pid this spawned — a plain `sleep 300` would leave a
384 // grandchild inheriting stdout and outliving the kill, which is
385 // a shape `hyprforge-traymenu` itself never has, and would make
386 // this test measure the script instead of the code under it.
387 let forever =
388 script(dir.path(), "forever.sh", "#!/bin/sh\ncat >/dev/null\nexec sleep 300\n");
389 let echo = script(dir.path(), "echo-stdin.sh", "#!/bin/sh\ncat\n");
390
391 let open = std::sync::Arc::new(OpenMenu::default());
392 let (first_tx, _first_rx) = tokio::sync::mpsc::unbounded_channel();
393 let first = tokio::spawn({
394 let open = open.clone();
395 let forever = forever.clone();
396 async move {
397 show_with_binary(forever.to_str().unwrap(), "hyprforge-network", &menu(), 10, 20, &first_tx, &open)
398 .await
399 }
400 });
401
402 // Wait for the first menu to actually be open before replacing
403 // it — polled rather than slept, since what matters is the slot
404 // being occupied, not any particular length of time.
405 //
406 // The bound is deliberately far longer than this can take. It
407 // exists so a menu that never opens fails rather than hangs the
408 // suite; it is not a claim about how quickly one does. The same
409 // helper in `hyprforge-greet` gave up after a second — fifty
410 // times its real figure — and still went red on a loaded CI
411 // runner, which is a test reporting someone else's scheduling
412 // as a bug here.
413 let giving_up_at = std::time::Instant::now() + std::time::Duration::from_secs(30);
414 while std::time::Instant::now() < giving_up_at {
415 if open.0.lock().await.is_some() {
416 break;
417 }
418 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
419 }
420 assert!(open.0.lock().await.is_some(), "the first menu should be the one that is open");
421
422 let (second_tx, mut second_rx) = tokio::sync::mpsc::unbounded_channel();
423 let outcome =
424 show_with_binary(echo.to_str().unwrap(), "hyprforge-bluetooth", &menu(), 30, 20, &second_tx, &open).await;
425 assert_eq!(outcome, LaunchOutcome::Spawned, "the second menu must open, not be refused");
426 assert_eq!(second_rx.recv().await.unwrap(), "menu:opened:hyprforge-bluetooth");
427 let echoed = second_rx.recv().await.unwrap();
428 serde_json::from_str::<Menu>(&echoed).expect("the second menu really ran and got its JSON");
429
430 let first = tokio::time::timeout(std::time::Duration::from_secs(5), first)
431 .await
432 .expect("the first menu must have been closed, not left open")
433 .unwrap();
434 assert_eq!(first, LaunchOutcome::Spawned, "being replaced is not a failure of the menu that was open");
435 }
436
437 /// The other half of the same property: once a menu has closed on
438 /// its own, nothing is left in the slot for the next right click to
439 /// kill. A stale entry there would mean the next click spends a
440 /// signal on a pid that may since belong to somebody else.
441 #[tokio::test]
442 async fn a_menu_that_closes_on_its_own_leaves_nothing_behind_to_kill() {
443 // See `SPAWNING`: held for the whole body, because the
444 // hazard is a fork anywhere else while this test's script
445 // is still open for writing.
446 let _spawning = SPAWNING.lock().await;
447 let dir = tempfile::tempdir().unwrap();
448 let echo = script(dir.path(), "echo-stdin.sh", "#!/bin/sh\ncat\n");
449
450 let open = OpenMenu::default();
451 let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
452 show_with_binary(echo.to_str().unwrap(), "hyprforge-network", &menu(), 10, 20, &tx, &open).await;
453
454 assert!(open.0.lock().await.is_none(), "a menu that exited should not still be the open one");
455 }
456}