Tray: separate tray and window processes; device list without self
Release / tsunagi-linux-aarch64 (push) Successful in 2m44s
Release / tsunagi-linux-x86_64 (push) Successful in 4m37s
Release / tsunagi-macos-aarch64 (push) Canceled after 0s
Release / tsunagi-windows-x86_64 (push) Canceled after 0s
Release / Publish release (push) Canceled after 0s

The tray process holds only the icon and starts the same binary with
--window on Open; the window ends when closed, which works on Wayland where
a window cannot be hidden. The devices table now names devices as
hostname (id5), leaves out this device and counts the others.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Aleksandr BogomiakovandClaude committed 2026-10-02 19:23:06 +01:00
1 parent 69310108f4
commit f4dcdec662
6 files changed
+247 -172

No files matched your search

+123 -83
View File
@@ -1,31 +1,55 @@
//! The tray icon and its menu.
//! The tray: the icon, its menu, and starting the window.
//!
//! The menu is just Open and Quit; everything else (per-network switches,
//! join/leave) lives in the window. Menu clicks are read on a background
//! thread and turned into [`Action`]s, so they are handled even while the
//! window is hidden and egui would otherwise not be repainting.
//! This is the process that stays. It holds no window and no GUI toolkit of
//! its own; choosing Open starts this same binary again as the window, which
//! is a perfectly ordinary program that ends when it is closed.
use std::sync::mpsc;
use std::process::{Child, Command};
use std::sync::{Arc, Mutex};
use eframe::egui;
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem};
use tray_icon::{Icon, TrayIcon, TrayIconBuilder};
/// What the user picked from the tray menu.
pub(crate) enum Action {
/// Show (and focus) the window.
Open,
/// Quit the application.
Quit,
/// The window process, when there is one.
struct Window {
child: Mutex<Option<Child>>,
}
/// The live tray icon plus the channel of menu actions.
pub(crate) struct Tray {
/// Kept alive for as long as the app runs; dropping it removes the icon.
/// On Linux the icon lives on the GTK thread instead (it is not `Send`).
#[cfg(not(target_os = "linux"))]
_icon: TrayIcon,
actions: mpsc::Receiver<Action>,
impl Window {
/// Starts the window unless one is already open.
///
/// Raising an existing one is not something a process can ask for on
/// every platform, so choosing Open while it is open does nothing.
fn open(&self) {
let mut slot = self.child.lock().unwrap_or_else(|e| e.into_inner());
if let Some(child) = slot.as_mut() {
match child.try_wait() {
Ok(None) => return,
_ => *slot = None,
}
}
let started = std::env::current_exe()
.map_err(|err| err.to_string())
.and_then(|exe| {
Command::new(exe)
.arg(crate::WINDOW_ARG)
.spawn()
.map_err(|err| err.to_string())
});
match started {
Ok(child) => *slot = Some(child),
Err(err) => eprintln!("cannot open the window: {err}"),
}
}
/// Closes the window if it is open.
fn close(&self) {
let mut slot = self.child.lock().unwrap_or_else(|e| e.into_inner());
if let Some(mut child) = slot.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
/// A built tray icon and the ids of its menu items.
@@ -57,75 +81,91 @@ fn build() -> Result<Built, String> {
})
}
impl Tray {
/// Builds the tray and starts reading its menu events.
///
/// Created on the main thread on macOS and Windows (required on macOS). On
/// Linux the tray needs GTK, which eframe/winit never initialise, so it is
/// built on a dedicated thread that initialises GTK and runs its main loop.
/// `ctx` is used to wake the UI when a menu item is chosen.
pub(crate) fn new(ctx: egui::Context) -> Result<Self, String> {
#[cfg(target_os = "linux")]
let (open_id, quit_id) = {
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
std::thread::Builder::new()
.name("tray-gtk".into())
.spawn(move || {
if let Err(err) = gtk::init() {
let _ = ready_tx.send(Err(format!("cannot initialise GTK: {err}")));
return;
}
match build() {
Ok(built) => {
let _ = ready_tx.send(Ok((built.open, built.quit)));
gtk::main();
drop(built.icon);
}
Err(err) => {
let _ = ready_tx.send(Err(err));
}
}
})
.map_err(|err| err.to_string())?;
ready_rx
.recv()
.map_err(|_| "the tray thread exited before it was ready".to_string())??
};
#[cfg(not(target_os = "linux"))]
let (icon, open_id, quit_id) = {
let built = build()?;
(built.icon, built.open, built.quit)
};
/// Acts on menu choices as the platform's loop delivers them.
fn handle_menu(built: &Built, window: Arc<Window>) {
let (open, quit) = (built.open.clone(), built.quit.clone());
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
if event.id == open {
window.open();
} else if event.id == quit {
window.close();
std::process::exit(0);
}
}));
}
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
// The global menu-event channel is fed by the OS event loop.
while let Ok(event) = MenuEvent::receiver().recv() {
let action = if event.id == open_id {
Action::Open
} else if event.id == quit_id {
Action::Quit
} else {
continue;
};
if tx.send(action).is_err() {
break;
}
ctx.request_repaint();
/// Shows the icon and runs until Quit.
///
/// Linux: the tray needs GTK, which nothing else here initialises, so this
/// thread does and runs its main loop.
#[cfg(target_os = "linux")]
pub(crate) fn run() -> Result<(), Box<dyn std::error::Error>> {
gtk::init().map_err(|err| format!("cannot initialise GTK: {err}"))?;
let built = build()?;
handle_menu(
&built,
Arc::new(Window {
child: Mutex::new(None),
}),
);
gtk::main();
drop(built.icon);
Ok(())
}
/// Shows the icon and runs until Quit.
///
/// Windows and macOS: the icon needs an event loop on the main thread to be
/// served, and macOS wants it created once that loop is running. There are no
/// windows in it; it exists to be pumped.
#[cfg(not(target_os = "linux"))]
pub(crate) fn run() -> Result<(), Box<dyn std::error::Error>> {
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::window::WindowId;
struct Pump {
window: Arc<Window>,
icon: Option<TrayIcon>,
}
impl ApplicationHandler for Pump {
fn resumed(&mut self, _event_loop: &ActiveEventLoop) {
if self.icon.is_some() {
return;
}
});
match build() {
Ok(built) => {
handle_menu(&built, Arc::clone(&self.window));
self.icon = Some(built.icon);
}
Err(err) => {
eprintln!("cannot create the tray icon: {err}");
std::process::exit(1);
}
}
}
Ok(Self {
#[cfg(not(target_os = "linux"))]
_icon: icon,
actions: rx,
})
fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, _: WindowEvent) {}
}
/// The menu actions since the last call.
pub(crate) fn poll(&self) -> impl Iterator<Item = Action> + '_ {
self.actions.try_iter()
let mut builder = EventLoop::builder();
// macOS: live in the menu bar with no Dock icon.
#[cfg(target_os = "macos")]
{
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
builder.with_activation_policy(ActivationPolicy::Accessory);
}
let event_loop = builder.build()?;
let mut pump = Pump {
window: Arc::new(Window {
child: Mutex::new(None),
}),
icon: None,
};
event_loop.run_app(&mut pump)?;
Ok(())
}
/// A small round icon, drawn in code so there is no asset to ship yet.