//! System tray icon and context menu. //! //! Linux uses the StatusNotifierItem (KSNI) backend, which talks to the //! desktop panel over D-Bus and needs no GTK event loop. Windows uses the //! native notification-area backend. Both come from the `tray-icon` crate. use std::sync::OnceLock; use iced::Subscription; use iced::futures::StreamExt; use iced::futures::stream::{self, BoxStream}; use tokio::sync::broadcast; /// Events delivered to the Iced application loop. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Event { /// Left click on the icon, or the Show/Hide menu entry. Toggle, Quit, } static EVENTS: OnceLock> = OnceLock::new(); const TOGGLE_ID: &str = "moorly.tray.toggle"; const QUIT_ID: &str = "moorly.tray.quit"; /// Creates the tray icon once. Subsequent calls are a no-op. pub fn start() -> Result<(), String> { imp::start() } /// Releases the tray icon and its menu. Safe to call more than once. pub fn shutdown() { imp::shutdown(); } /// Updates the Show/Hide menu entry to match the main window state. pub fn set_window_visible(visible: bool) { imp::set_window_visible(visible); } pub fn subscription() -> Subscription { Subscription::run(event_stream) } fn event_stream() -> BoxStream<'static, Event> { let Some(events) = EVENTS.get() else { return stream::pending().boxed(); }; let receiver = events.subscribe(); stream::unfold(receiver, |mut receiver| async move { loop { match receiver.recv().await { Ok(event) => return Some((event, receiver)), Err(broadcast::error::RecvError::Lagged(_)) => continue, Err(broadcast::error::RecvError::Closed) => return None, } } }) .boxed() } #[cfg(any(target_os = "linux", target_os = "windows"))] mod imp { use std::cell::RefCell; use tray_icon::menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem}; use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent}; use super::{EVENTS, Event, QUIT_ID, TOGGLE_ID, broadcast}; thread_local! { // `TrayIcon` is not `Send`; it is created and dropped on the main // thread that also runs the Iced/winit event loop. static TRAY: RefCell> = const { RefCell::new(None) }; static TOGGLE_ITEM: RefCell> = const { RefCell::new(None) }; } pub(super) fn start() -> Result<(), String> { if EVENTS.get().is_some() { return Ok(()); } let (sender, _) = broadcast::channel(16); // The window starts visible, so the entry starts as "Hide Moorly". let toggle = MenuItem::with_id(TOGGLE_ID, "Hide Moorly", true, None); let separator = PredefinedMenuItem::separator(); let quit = MenuItem::with_id(QUIT_ID, "Quit Moorly", true, None); let menu = Menu::with_items(&[&toggle, &separator, &quit]) .map_err(|error| format!("Could not build the tray menu: {error}"))?; let mut builder = TrayIconBuilder::new() .with_tooltip("Moorly") .with_menu(Box::new(menu)) // Left click toggles the window; right click opens the menu. // These flags are honoured by Windows. KSNI hosts decide for // themselves and send us the left-click activation event. .with_menu_on_left_click(false) .with_menu_on_right_click(true); builder = with_app_icon(builder); let tray = builder .build() .map_err(|error| format!("Could not create the system tray icon: {error}"))?; let _ = EVENTS.set(sender.clone()); let tray_sender = sender.clone(); TrayIconEvent::set_event_handler(Some(move |event| { if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { let _ = tray_sender.send(Event::Toggle); } })); MenuEvent::set_event_handler(Some(move |event: MenuEvent| { let event = match event.id().as_ref() { TOGGLE_ID => Event::Toggle, QUIT_ID => Event::Quit, _ => return, }; let _ = sender.send(event); })); // Store after the handlers are installed so no early event is lost. TOGGLE_ITEM.with(|slot| *slot.borrow_mut() = Some(toggle)); TRAY.with(|slot| *slot.borrow_mut() = Some(tray)); Ok(()) } pub(super) fn shutdown() { TOGGLE_ITEM.with(|slot| slot.borrow_mut().take()); TRAY.with(|tray| { if let Some(tray) = tray.borrow_mut().take() { drop(tray); } }); } pub(super) fn set_window_visible(visible: bool) { TOGGLE_ITEM.with(|slot| { if let Some(item) = slot.borrow().as_ref() { item.set_text(if visible { "Hide Moorly" } else { "Show Moorly" }); } }); } #[cfg(target_os = "linux")] fn with_app_icon(builder: TrayIconBuilder) -> TrayIconBuilder { // This is the icon already declared by Moorly's desktop entry. builder.with_native_icon(tray_icon::NativeIcon::from_name("utilities-terminal")) } #[cfg(target_os = "windows")] fn with_app_icon(builder: TrayIconBuilder) -> TrayIconBuilder { use tray_icon::{Icon, NativeIcon}; // Reuse the executable's embedded icon when it has one. Builds without // an icon resource fall back to the system application icon. match Icon::from_resource(1, None).or_else(|_| Icon::from_resource_name("IDI_ICON1", None)) { Ok(icon) => builder.with_icon(icon), Err(_) => builder.with_native_icon(NativeIcon::Raw(2)), } } } #[cfg(not(any(target_os = "linux", target_os = "windows")))] mod imp { pub(super) fn start() -> Result<(), String> { Err("System tray integration is only implemented on Linux and Windows.".to_owned()) } pub(super) fn shutdown() {} pub(super) fn set_window_visible(_visible: bool) {} }