diff --git a/Cargo.lock b/Cargo.lock index 78ba7c5..c6a6973 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -117,6 +117,15 @@ dependencies = [ "libc", ] +[[package]] +name = "arc-swap" +version = "1.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92" +dependencies = [ + "rustversion", +] + [[package]] name = "argon2" version = "0.6.0" @@ -841,6 +850,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1256,6 +1274,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "ff" version = "0.14.0" @@ -1285,7 +1312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.9.1", "zlib-rs", ] @@ -2194,6 +2221,26 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" +[[package]] +name = "ksni" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" +dependencies = [ + "arc-swap", + "async-executor", + "async-io", + "async-lock", + "crossbeam-queue", + "futures-channel", + "futures-lite", + "futures-util", + "pastey", + "serde", + "task-local", + "zbus 5.19.0", +] + [[package]] name = "kurbo" version = "0.10.4" @@ -2398,6 +2445,16 @@ dependencies = [ "paste", ] +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -2459,12 +2516,31 @@ dependencies = [ "serde", "tokio", "toml", + "tray-icon", "ttf-parser", "uuid", "vt100", "windows-sys 0.61.2", ] +[[package]] +name = "muda" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "png", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "mundy" version = "0.2.3" @@ -3119,6 +3195,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.13.0" @@ -3248,6 +3330,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "polling" version = "3.11.0" @@ -4228,6 +4323,15 @@ dependencies = [ "libc", ] +[[package]] +name = "task-local" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" +dependencies = [ + "pin-project-lite", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4479,6 +4583,26 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tray-icon" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f5cc5858ecf9574ddd8f0032a2ff7ffd6f7724d2b81e48b9374984b3fd6ddc9" +dependencies = [ + "crossbeam-channel", + "ksni", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "once_cell", + "png", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "ttf-parser" version = "0.25.1" diff --git a/Cargo.toml b/Cargo.toml index a4af3ff..33d08fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,8 +23,10 @@ global-hotkey = "0.9.0" [target.'cfg(target_os = "linux")'.dependencies] ashpd = { version = "0.14.0", features = ["global_shortcuts"] } +tray-icon = { version = "0.26.1", default-features = false, features = ["ksni"] } [target.'cfg(windows)'.dependencies] +tray-icon = { version = "0.26.1", default-features = false } windows-sys = { version = "0.61.2", features = [ "Win32_Foundation", "Win32_Security", diff --git a/src/hotkeys.rs b/src/hotkeys.rs index aa31848..180e030 100644 --- a/src/hotkeys.rs +++ b/src/hotkeys.rs @@ -383,7 +383,7 @@ fn detect_backend() -> Backend { } #[cfg(target_os = "linux")] -fn is_wayland_session() -> bool { +pub(crate) fn is_wayland_session() -> bool { std::env::var_os("WAYLAND_DISPLAY").is_some() || std::env::var("XDG_SESSION_TYPE") .is_ok_and(|session| session.eq_ignore_ascii_case("wayland")) diff --git a/src/main.rs b/src/main.rs index 52f3d08..fb2af4a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,6 +23,8 @@ mod notifications; #[allow(dead_code)] mod terminal; mod theme; +#[cfg_attr(test, allow(dead_code))] +mod tray; const MENUBAR_HEIGHT: f32 = 40.0; /// Settings heading sizes: tab title, sub-section header, normal text, caption. @@ -123,6 +125,21 @@ fn boot() -> (Moorly, Task) { #[cfg(not(test))] hotkeys::start(global_hotkey_bindings(&state)); + #[cfg(not(test))] + match tray::start() { + Ok(()) => { + state.tray_available = true; + tray::set_window_visible(true); + } + Err(reason) => { + state.notifications.add( + notifications::Notification::new(notifications::NotificationKind::Warning, reason) + .title("System tray unavailable") + .persistent(), + ); + } + } + (state, Task::batch([task.map(|_| Message::Ignore), fonts])) } @@ -368,6 +385,7 @@ fn subscription(state: &Moorly) -> Subscription { terminal_keys, terminal_text, hotkeys::subscription().map(Message::Hotkey), + tray::subscription().map(Message::Tray), iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), window::events().map(|(window, event)| Message::WindowEvent(window, event)), iced::event::listen_with(pointer_event), @@ -1676,6 +1694,12 @@ struct Moorly { main_window: Option, focused_window: Option, main_window_hidden: bool, + /// Wayland cannot hide or restore a toplevel, so the window is destroyed + /// while hidden and recreated from this state on show. + hidden_main_window: Option, + tray_available: bool, + close_to_tray: bool, + close_to_tray_draft: bool, drag: Option, theme: theme::Preference, saved_theme: theme::Preference, @@ -2489,12 +2513,17 @@ impl Default for ConfigFile { struct GeneralConfig { #[serde(default = "default_true")] fade_settings: bool, + /// Closing the main window hides it instead of exiting. Defaults to the + /// old behaviour so upgrades do not strand anyone without a tray host. + #[serde(default)] + close_to_tray: bool, } impl Default for GeneralConfig { fn default() -> Self { Self { fade_settings: true, + close_to_tray: false, } } } @@ -4445,6 +4474,7 @@ fn new_tab_close_animation() -> Animation { fn apply_settings(state: &mut Moorly) { state.show_start_tab = state.show_start_tab_draft; state.fade_settings = state.fade_settings_draft; + state.close_to_tray = state.close_to_tray_draft; state.hide_tab_close = state.hide_tab_close_draft; state.show_new_session_button = state.show_new_session_button_draft; state.show_command_palette_description = state.show_command_palette_description_draft; @@ -4483,6 +4513,7 @@ fn apply_settings(state: &mut Moorly) { fn undo_settings(state: &mut Moorly) { state.show_start_tab_draft = state.show_start_tab; state.fade_settings_draft = state.fade_settings; + state.close_to_tray_draft = state.close_to_tray; state.hide_tab_close_draft = state.hide_tab_close; state.show_new_session_button_draft = state.show_new_session_button; state.show_command_palette_description_draft = state.show_command_palette_description; @@ -4533,6 +4564,7 @@ fn config_file(state: &Moorly) -> ConfigFile { ConfigFile { general: GeneralConfig { fade_settings: state.fade_settings, + close_to_tray: state.close_to_tray, }, startup: StartupConfig { show_start_tab: state.show_start_tab, @@ -4607,6 +4639,7 @@ impl Default for Moorly { builtin_toast_config(&config.appearance); let show_start_tab = config.startup.show_start_tab; let fade_settings = config.general.fade_settings; + let close_to_tray = config.general.close_to_tray; let hide_tab_close = config.appearance.hide_tab_close; let show_new_session_button = config.appearance.show_new_session_button; let show_command_palette_description = config.appearance.show_command_palette_description; @@ -4634,6 +4667,10 @@ impl Default for Moorly { main_window: None, focused_window: None, main_window_hidden: false, + hidden_main_window: None, + tray_available: false, + close_to_tray, + close_to_tray_draft: close_to_tray, drag: None, theme, saved_theme: theme, @@ -4762,6 +4799,7 @@ enum Message { SelectSettingsSection(SettingsSection), SetShowStartTab(bool), SetFadeSettings(bool), + SetCloseToTray(bool), SetHideTabClose(bool), SetShowNewSessionButton(bool), SetShowCommandPaletteDescription(bool), @@ -4900,6 +4938,7 @@ enum Message { ScrollTabs(window::Id, mouse::ScrollDelta), ScrollTabsBy(window::Id, f32), Hotkey(hotkeys::Event), + Tray(tray::Event), FinishToggleWindowVisibility(Option), Quit, } @@ -5509,6 +5548,7 @@ fn update(state: &mut Moorly, message: Message) -> Task { } Message::SetShowStartTab(value) => state.show_start_tab_draft = value, Message::SetFadeSettings(value) => state.fade_settings_draft = value, + Message::SetCloseToTray(value) => state.close_to_tray_draft = value, Message::SetHideTabClose(value) => state.hide_tab_close_draft = value, Message::SetShowNewSessionButton(value) => state.show_new_session_button_draft = value, Message::SetShowCommandPaletteDescription(value) => { @@ -6213,10 +6253,12 @@ fn update(state: &mut Moorly, message: Message) -> Task { return scroll_tabs_by(state, window, amount); } Message::Hotkey(event) => return handle_hotkey_event(state, event), + Message::Tray(event) => return handle_tray_event(state, event), Message::FinishToggleWindowVisibility(minimized) => { return finish_toggle_window_visibility(state, minimized); } Message::Quit => { + tray::shutdown(); hotkeys::shutdown(); // Drop PTY sessions explicitly so their child processes are // terminated before process::exit bypasses the state destructor. @@ -6245,12 +6287,17 @@ fn main_window_id(state: &Moorly) -> Option { } fn show_main_window(state: &mut Moorly) -> Task { + if let Some(window_state) = state.hidden_main_window.take() { + return reopen_main_window(state, window_state); + } + let Some(window) = main_window_id(state) else { return Task::none(); }; state.main_window_hidden = false; state.focused_window = Some(window); + tray::set_window_visible(true); Task::batch([ window::set_mode(window, window::Mode::Windowed), @@ -6259,39 +6306,126 @@ fn show_main_window(state: &mut Moorly) -> Task { ]) } -fn toggle_main_window(state: &mut Moorly) -> Task { - let Some(window) = main_window_id(state) else { - return Task::none(); +/// Wayland cannot unmap or restore an existing toplevel, so the hidden window +/// is recreated from its saved UI state. +fn reopen_main_window(state: &mut Moorly, window_state: WindowState) -> Task { + let settings = window::Settings { + size: window_state.size, + position: window_state + .position + .map_or(window::Position::Default, window::Position::Specific), + exit_on_close_request: false, + ..window::Settings::default() }; + let (id, open) = window::open(settings); + state.windows.insert(id, window_state); + state.window_order.push(id); + state.main_window = Some(id); + state.focused_window = Some(id); + state.main_window_hidden = false; + tray::set_window_visible(true); + + Task::batch([open.map(|_| Message::Ignore), window::gain_focus(id)]) +} + +fn toggle_main_window(state: &mut Moorly) -> Task { if state.main_window_hidden { return show_main_window(state); } + let Some(window) = main_window_id(state) else { + return Task::none(); + }; + // A minimized window is still visible as far as `Mode` is concerned, so // ask the platform before deciding to hide it. window::is_minimized(window).map(Message::FinishToggleWindowVisibility) } fn finish_toggle_window_visibility(state: &mut Moorly, minimized: Option) -> Task { - let Some(window) = main_window_id(state) else { - return Task::none(); - }; - if minimized == Some(true) { + // Wayland cannot unminimize either, so replace the window instead. + if needs_window_recreation() + && let Some(window) = main_window_id(state) + { + state.main_window_hidden = true; + tray::set_window_visible(false); + let close = detach_main_window(state, window); + let open = show_main_window(state); + return Task::batch([close, open]); + } + return show_main_window(state); } - state.main_window_hidden = true; - window::set_mode(window, window::Mode::Hidden) + hide_main_window(state) } -fn open_palette_from_hotkey(state: &mut Moorly) -> Task { +fn needs_window_recreation() -> bool { + #[cfg(target_os = "linux")] + { + hotkeys::is_wayland_session() + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +/// Hides the main window without closing it, keeping the application and its +/// sessions alive. Shared by the global hotkey and the tray. +fn hide_main_window(state: &mut Moorly) -> Task { + if state.main_window_hidden || state.hidden_main_window.is_some() { + return Task::none(); + } + let Some(window) = main_window_id(state) else { return Task::none(); }; + state.main_window_hidden = true; + tray::set_window_visible(false); + + if needs_window_recreation() { + detach_main_window(state, window) + } else { + window::set_mode(window, window::Mode::Hidden) + } +} + +/// Removes the main window from the UI state and destroys its native window, +/// keeping all tabs and sessions for a later restore. +fn detach_main_window(state: &mut Moorly, window: window::Id) -> Task { + let Some(window_state) = state.windows.remove(&window) else { + return Task::none(); + }; + + state.window_order.retain(|id| *id != window); + if state.focused_window == Some(window) { + state.focused_window = state.window_order.first().copied(); + } + if state.main_window == Some(window) { + state.main_window = None; + } + state.hidden_main_window = Some(window_state); + + window::close(window) +} + +fn handle_tray_event(state: &mut Moorly, event: tray::Event) -> Task { + match event { + tray::Event::Toggle => toggle_main_window(state), + tray::Event::Quit => update(state, Message::Quit), + } +} + +fn open_palette_from_hotkey(state: &mut Moorly) -> Task { let show = show_main_window(state); + let Some(window) = main_window_id(state) else { + return show; + }; + let palette = update(state, Message::ToggleCommandPalette(window)); Task::batch([show, palette]) @@ -6400,11 +6534,23 @@ fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> window_state.size = size; } } - window::Event::Focused => state.focused_window = Some(window), + window::Event::Focused => { + state.focused_window = Some(window); + if state.main_window == Some(window) { + tray::set_window_visible(true); + } + } window::Event::CloseRequested => { + // Keep sessions and the tray alive when the user opted in, but + // only if there is actually a tray icon to restore the window. + if state.main_window == Some(window) && state.close_to_tray && state.tray_available { + return hide_main_window(state); + } + remove_window(state, window); if state.windows.is_empty() { + tray::shutdown(); hotkeys::shutdown(); return iced::exit(); } @@ -6415,6 +6561,11 @@ fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> remove_window(state, window); if state.windows.is_empty() { + if state.hidden_main_window.is_some() { + return Task::none(); + } + + tray::shutdown(); hotkeys::shutdown(); return iced::exit(); } @@ -6844,6 +6995,8 @@ fn close_window_if_empty(state: &mut Moorly, window: window::Id) -> Task Element<'_, Message> { - row![ - styled_text(&state.typography.h3, "Fade In/Fade out animation"), - space::horizontal(), - toggler(state.fade_settings_draft).on_toggle(Message::SetFadeSettings), + column![ + row![ + styled_text(&state.typography.h3, "Fade In/Fade out animation"), + space::horizontal(), + toggler(state.fade_settings_draft).on_toggle(Message::SetFadeSettings), + ] + .align_y(Alignment::Center), + row![ + styled_text(&state.typography.h3, "Close window to tray"), + space::horizontal(), + toggler(state.close_to_tray_draft).on_toggle(Message::SetCloseToTray), + ] + .align_y(Alignment::Center), ] - .align_y(Alignment::Center) + .spacing(12) .into() } @@ -11098,6 +11260,10 @@ mod tests { main_window: Some(window), focused_window: Some(window), main_window_hidden: false, + hidden_main_window: None, + tray_available: false, + close_to_tray: false, + close_to_tray_draft: false, drag: None, theme: theme::Preference::default(), saved_theme: theme::Preference::default(), @@ -13918,4 +14084,28 @@ start_path = "/tmp" std::fs::remove_dir_all(&root).unwrap(); } + + #[test] + fn closing_the_window_only_hides_it_when_a_tray_is_available() { + let window = test_window(); + + let mut state = self::state(); + state.close_to_tray = true; + state.tray_available = true; + let _ = update( + &mut state, + Message::WindowEvent(window, super::window::Event::CloseRequested), + ); + assert!(state.windows.contains_key(&window) || state.hidden_main_window.is_some()); + assert!(state.main_window_hidden); + + let mut state = self::state(); + state.close_to_tray = true; + state.tray_available = false; + let _ = update( + &mut state, + Message::WindowEvent(window, super::window::Event::CloseRequested), + ); + assert!(!state.windows.contains_key(&window)); + } } diff --git a/src/tray.rs b/src/tray.rs new file mode 100644 index 0000000..da37c70 --- /dev/null +++ b/src/tray.rs @@ -0,0 +1,188 @@ +//! 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) {} +}