use crate::menu::Menu;
use std::sync::LazyLock;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::Child;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::Mutex;
pub const OPENED_PREFIX: &str = "menu:opened:";
const TRAYMENU_BINARY: &str = "hyprforge-traymenu";
#[derive(Default)]
pub struct OpenMenu(Mutex<Option<(u32, Child)>>);
static OPEN_MENU: LazyLock<OpenMenu> = LazyLock::new(OpenMenu::default);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchOutcome {
Spawned,
NotInstalled,
Failed,
}
pub async fn show(id: &str, menu: &Menu, x: i32, y: i32, events: &UnboundedSender<String>) -> LaunchOutcome {
show_with_binary(TRAYMENU_BINARY, id, menu, x, y, events, &OPEN_MENU).await
}
pub async fn show_with_binary(
binary: &str,
id: &str,
menu: &Menu,
x: i32,
y: i32,
events: &UnboundedSender<String>,
open: &OpenMenu,
) -> LaunchOutcome {
let _ = events.send(format!("{OPENED_PREFIX}{id}"));
let json = match serde_json::to_vec(menu) {
Ok(json) => json,
Err(e) => {
tracing::warn!(error = %e, "couldn't serialise the tray menu; not showing it");
return LaunchOutcome::Failed;
}
};
let mut guard = open.0.lock().await;
if let Some((_, mut previous)) = guard.take() {
if let Err(e) = previous.kill().await {
tracing::warn!(error = %e, "couldn't close the tray menu that was already open");
}
}
let mut child = match tokio::process::Command::new(binary)
.arg("--x")
.arg(x.to_string())
.arg("--y")
.arg(y.to_string())
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
{
Ok(child) => child,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::warn!(
"hyprforge-traymenu is not installed; falling back to the icon's primary action"
);
return LaunchOutcome::NotInstalled;
}
Err(e) => {
tracing::warn!(error = %e, "couldn't launch hyprforge-traymenu");
return LaunchOutcome::Failed;
}
};
if let Some(mut stdin) = child.stdin.take() {
if let Err(e) = stdin.write_all(&json).await {
tracing::warn!(error = %e, "couldn't hand the menu to hyprforge-traymenu");
}
}
let mut stdout = child.stdout.take();
let tracked = child.id();
match tracked {
Some(pid) => *guard = Some((pid, child)),
None => tracing::warn!("hyprforge-traymenu reported no pid immediately after spawn"),
}
drop(guard);
let mut printed = Vec::new();
if let Some(stdout) = stdout.as_mut() {
if let Err(e) = stdout.read_to_end(&mut printed).await {
tracing::warn!(error = %e, "couldn't read what hyprforge-traymenu chose");
return LaunchOutcome::Failed;
}
}
if let Some(pid) = tracked {
let mut guard = open.0.lock().await;
if guard.as_ref().is_some_and(|(open_pid, _)| *open_pid == pid) {
if let Some((_, mut child)) = guard.take() {
let _ = child.wait().await;
}
}
}
let action = String::from_utf8_lossy(&printed).trim().to_string();
if !action.is_empty() {
let _ = events.send(action);
}
LaunchOutcome::Spawned
}
#[cfg(test)]
mod tests {
use super::*;
use crate::menu::MenuItem;
fn menu() -> Menu {
Menu::new(vec![MenuItem::standard("home", "wifi:connect:home")])
}
#[tokio::test]
async fn a_missing_binary_is_reported_as_not_installed_rather_than_panicking() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let outcome =
show_with_binary("hyprforge-traymenu-does-not-exist-xyz", "hyprforge-network", &menu(), 10, 20, &tx, &OpenMenu::default())
.await;
assert_eq!(outcome, LaunchOutcome::NotInstalled);
assert_eq!(rx.recv().await.unwrap(), "menu:opened:hyprforge-network");
assert!(rx.try_recv().is_err(), "no action was chosen, so nothing else should arrive");
}
#[tokio::test]
async fn whatever_the_child_prints_on_stdout_reaches_the_events_channel() {
let _spawning = SPAWNING.lock().await;
let dir = tempfile::tempdir().unwrap();
let script = dir.path().join("echo-stdin.sh");
std::fs::write(&script, "#!/bin/sh\ncat\n").unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let outcome =
show_with_binary(script.to_str().unwrap(), "hyprforge-network", &menu(), 10, 20, &tx, &OpenMenu::default())
.await;
assert_eq!(outcome, LaunchOutcome::Spawned);
assert_eq!(rx.recv().await.unwrap(), "menu:opened:hyprforge-network");
let echoed = rx.recv().await.unwrap();
let restored: Menu = serde_json::from_str(&echoed).expect("the script must have echoed valid JSON back");
assert_eq!(restored, menu(), "the menu handed to stdin must be exactly what was echoed back");
}
static SPAWNING: Mutex<()> = Mutex::const_new(());
fn script(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join(name);
std::fs::write(&path, body).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}
#[tokio::test]
async fn a_right_click_on_another_icon_replaces_the_menu_already_open() {
let _spawning = SPAWNING.lock().await;
let dir = tempfile::tempdir().unwrap();
let forever =
script(dir.path(), "forever.sh", "#!/bin/sh\ncat >/dev/null\nexec sleep 300\n");
let echo = script(dir.path(), "echo-stdin.sh", "#!/bin/sh\ncat\n");
let open = std::sync::Arc::new(OpenMenu::default());
let (first_tx, _first_rx) = tokio::sync::mpsc::unbounded_channel();
let first = tokio::spawn({
let open = open.clone();
let forever = forever.clone();
async move {
show_with_binary(forever.to_str().unwrap(), "hyprforge-network", &menu(), 10, 20, &first_tx, &open)
.await
}
});
let giving_up_at = std::time::Instant::now() + std::time::Duration::from_secs(30);
while std::time::Instant::now() < giving_up_at {
if open.0.lock().await.is_some() {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert!(open.0.lock().await.is_some(), "the first menu should be the one that is open");
let (second_tx, mut second_rx) = tokio::sync::mpsc::unbounded_channel();
let outcome =
show_with_binary(echo.to_str().unwrap(), "hyprforge-bluetooth", &menu(), 30, 20, &second_tx, &open).await;
assert_eq!(outcome, LaunchOutcome::Spawned, "the second menu must open, not be refused");
assert_eq!(second_rx.recv().await.unwrap(), "menu:opened:hyprforge-bluetooth");
let echoed = second_rx.recv().await.unwrap();
serde_json::from_str::<Menu>(&echoed).expect("the second menu really ran and got its JSON");
let first = tokio::time::timeout(std::time::Duration::from_secs(5), first)
.await
.expect("the first menu must have been closed, not left open")
.unwrap();
assert_eq!(first, LaunchOutcome::Spawned, "being replaced is not a failure of the menu that was open");
}
#[tokio::test]
async fn a_menu_that_closes_on_its_own_leaves_nothing_behind_to_kill() {
let _spawning = SPAWNING.lock().await;
let dir = tempfile::tempdir().unwrap();
let echo = script(dir.path(), "echo-stdin.sh", "#!/bin/sh\ncat\n");
let open = OpenMenu::default();
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
show_with_binary(echo.to_str().unwrap(), "hyprforge-network", &menu(), 10, 20, &tx, &open).await;
assert!(open.0.lock().await.is_none(), "a menu that exited should not still be the open one");
}
}